loop.spec.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, StreamChunk } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  9. import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from './mock-adapter.ts'
  10. async function harness(adapter: MockAdapter, persona = '') {
  11. const ctx = new Context()
  12. await ctx.plugin(LlmService)
  13. await ctx.plugin(SessionStore)
  14. await ctx.plugin(SystemPrompt, { persona })
  15. await ctx.plugin(ToolRegistry)
  16. await ctx.plugin(AgentRegistry)
  17. await ctx.plugin(AgentLoop, { agents: [] })
  18. ctx.llm.registerAdapter(['mock'], adapter)
  19. return ctx
  20. }
  21. /**
  22. * Wait for the agent's NEXT transition to idle. Always event-based: callers
  23. * invoke this right after send(), when the loop hasn't woken yet (status is
  24. * still 'idle' synchronously), so polling the current status would lie.
  25. */
  26. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  27. return new Promise((resolve) => {
  28. const dispose = ctx.on('agent/status', (subject, status) => {
  29. if (subject === agent && status === 'idle') {
  30. dispose()
  31. resolve()
  32. }
  33. })
  34. })
  35. }
  36. function send(agent: ReactLoopAgent, text: string) {
  37. agent.send([{ type: 'text', text }])
  38. }
  39. describe('agent loop', () => {
  40. it('runs a simple turn: queued message → model → idle, with ordered events', async () => {
  41. const adapter = new MockAdapter([textResponse('hello there')])
  42. const ctx = await harness(adapter)
  43. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  44. // All boundaries — turn and step — are durable session events on the
  45. // session/event feed (no agent/* mirror). Record them in fire order to
  46. // assert the full boundary nesting.
  47. const order: string[] = []
  48. ctx.on('session/event', (_session, event) => {
  49. if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end') {
  50. order.push(event.type)
  51. }
  52. })
  53. send(agent, 'hi')
  54. await waitForIdle(ctx, agent)
  55. expect(order).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end'])
  56. const types = agent.session.events.map(e => e.type)
  57. // turn/start opens the turn, THEN the queued user message is recorded inside
  58. // it (every event is turn-enclosed), then the assembled message (carrying the
  59. // step's usage).
  60. expect(types[0]).toBe('turn/start')
  61. expect(types[1]).toBe('user/message')
  62. expect(types).toContain('assistant/message')
  63. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  64. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data.usage).toEqual({ inputTokens: 10, outputTokens: 'hello there'.length })
  65. expect(types.at(-1)).toBe('turn/end')
  66. // derived history: user + assistant
  67. const messages = agent.session.deriveMessages()
  68. expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
  69. expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }])
  70. })
  71. it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
  72. const adapter = new MockAdapter([
  73. toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'),
  74. textResponse('done'),
  75. ])
  76. const ctx = await harness(adapter)
  77. ctx.tools.register(defineTool({
  78. name: 'echo',
  79. description: 'echo back',
  80. parameters: { text: { type: 'string' } },
  81. async execute(args) {
  82. return [{ type: 'text', text: `echo: ${args.text}` }]
  83. },
  84. }))
  85. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  86. send(agent, 'use the tool')
  87. await waitForIdle(ctx, agent)
  88. // two model calls happened (tool-call step, then final step)
  89. expect(adapter.requests).toHaveLength(2)
  90. // the second request's derived history contains the tool result
  91. const secondMessages = adapter.requests[1]!.messages
  92. const toolResultMessage = secondMessages.find(m =>
  93. m.content.some(b => b.type === 'tool-result'))
  94. expect(toolResultMessage).toBeDefined()
  95. const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
  96. expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
  97. expect((block).content).toEqual([{ type: 'text', text: 'echo: ping' }])
  98. // session log records call + result
  99. const types = agent.session.events.map(e => e.type)
  100. expect(types).toContain('tool/call')
  101. expect(types).toContain('tool/result')
  102. })
  103. it('threads a tool-attached meta (execute object return) onto the tool/result event', async () => {
  104. const adapter = new MockAdapter([
  105. toolCallResponse('c1', 'writer', { path: 'a.txt' }, 'writing'),
  106. textResponse('done'),
  107. ])
  108. const ctx = await harness(adapter)
  109. // A tool that returns the { content, meta } object form: the loop must
  110. // persist `meta` on the tool/result event so a UI reproduces the card on replay.
  111. ctx.tools.register(defineTool({
  112. name: 'writer',
  113. description: 'writes a file',
  114. parameters: { path: { type: 'string' } },
  115. async execute() {
  116. return { content: [{ type: 'text', text: 'ok' }], meta: { diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] } }
  117. },
  118. }))
  119. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  120. send(agent, 'use the tool')
  121. await waitForIdle(ctx, agent)
  122. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  123. expect(toolResult?.type === 'tool/result' && toolResult.data.meta)
  124. .toEqual({ diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] })
  125. })
  126. it('renders harness identity, then the persona, then tool guidance — with {{variables}} resolved', async () => {
  127. const adapter = new MockAdapter([textResponse('ok')])
  128. // The persona is a TEMPLATE: {{model}} is the loop-registered variable
  129. // projecting this agent's configured model, so the model knows its own name.
  130. const ctx = await harness(adapter, 'You are a test agent on {{model}}.')
  131. ctx.systemPrompt.section({ name: 'tool:noop', order: 100, text: 'Use the noop tool wisely.' })
  132. ctx.tools.register(defineTool({
  133. name: 'noop',
  134. description: 'does nothing',
  135. parameters: {},
  136. async execute() {
  137. return []
  138. },
  139. }))
  140. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  141. send(agent, 'hi')
  142. await waitForIdle(ctx, agent)
  143. const request = adapter.requests[0]
  144. expect(request!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are a test agent on mock.\n\nUse the noop tool wisely.')
  145. expect(request!.tools?.map(t => t.name)).toEqual(['noop'])
  146. })
  147. it('resolves {{cwd}} from the agent session workspace (factory create with meta.cwd)', async () => {
  148. const adapter = new MockAdapter([textResponse('ok')])
  149. const ctx = await harness(adapter, 'Working in {{cwd}}.')
  150. const handle = await ctx.agents.create({
  151. sessionId: SessionId('s-cwd'),
  152. meta: { cwd: '/work/space' },
  153. agentOptions: { provider: 'mock', model: 'mock' },
  154. })
  155. const agent = handle.agent as ReactLoopAgent
  156. send(agent, 'hi')
  157. await waitForIdle(ctx, agent)
  158. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nWorking in /work/space.')
  159. })
  160. it('contains a strict-variable render failure: the turn errors, the loop keeps serving turns', async () => {
  161. // A missing cwd variable must fail one turn without preventing a later valid turn.
  162. const adapter = new MockAdapter([textResponse('ok after rescue')])
  163. const ctx = await harness(adapter, 'In {{cwd}}.')
  164. const errors: Error[] = []
  165. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  166. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  167. send(agent, 'hi')
  168. await waitForIdle(ctx, agent)
  169. expect(adapter.requests).toHaveLength(0) // the request was never sent
  170. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  171. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  172. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  173. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  174. // agent completes a real model turn.
  175. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  176. assembly.variables['cwd'] = '/rescued'
  177. return next()
  178. })
  179. send(agent, 'again')
  180. await waitForIdle(ctx, agent)
  181. expect(adapter.requests).toHaveLength(1)
  182. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  183. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  184. expect(turnEnds).toHaveLength(2)
  185. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  186. })
  187. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  188. // AgentOptions.model unset: the model arrives in the agent/request
  189. // waterfall (the loop's documented fallback — see runStep's no-model
  190. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  191. // states the fact early on system-prompt/assemble — the owner of a
  192. // late-bound fact owns stating it wherever it is claimed.
  193. const adapter = new MockAdapter([textResponse('ok')])
  194. const ctx = await harness(adapter, 'You run on {{model}}.')
  195. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  196. assembly.variables['provider'] = 'mock'
  197. assembly.variables['model'] = 'mock'
  198. return next()
  199. })
  200. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  201. return { ...config, provider: 'mock', model: 'mock' }
  202. })
  203. const agent = ctx.agentLoop.create(SessionId('a-late-model'), {})
  204. send(agent, 'hi')
  205. await waitForIdle(ctx, agent)
  206. expect(adapter.requests).toHaveLength(1)
  207. expect(adapter.requests[0]!.model).toBe('mock')
  208. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  209. })
  210. it.each([
  211. ['BigInt', { n: 1n }],
  212. ['Map', new Map([['key', 'value']])],
  213. ['class instance', new (class ResultMeta { x = 1 })()],
  214. ])('normalizes non-JSON tool meta (%s) before the durable result commit', async (_kind, meta) => {
  215. const adapter = new MockAdapter([
  216. toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'),
  217. textResponse('recovered'),
  218. ])
  219. const ctx = await harness(adapter)
  220. ctx.tools.register(defineTool({
  221. name: 'bad-meta',
  222. description: 'returns invalid durable metadata',
  223. parameters: {},
  224. execute: () => Promise.resolve({ content: [{ type: 'text' as const, text: 'apparent success' }], meta }),
  225. }))
  226. const agent = ctx.agentLoop.create(SessionId('bad-meta-agent'), { provider: 'mock', model: 'mock' })
  227. send(agent, 'use the tool')
  228. await waitForIdle(ctx, agent)
  229. const result = agent.session.events.find(event => event.type === 'tool/result')
  230. expect(result?.type).toBe('tool/result')
  231. if (result?.type === 'tool/result') {
  232. expect(result.data.callId).toBe('bad-meta-call')
  233. expect(result.data.isError).toBe(true)
  234. expect(result.data.meta).toBeUndefined()
  235. expect(result.data.content).toEqual([{
  236. type: 'text',
  237. text: 'Error: tool result must be losslessly JSON-serializable',
  238. }])
  239. }
  240. // The normalized failure was durably logged and fed back to the model; the
  241. // turn continued normally instead of failing after an apparent success.
  242. expect(adapter.requests).toHaveLength(2)
  243. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('losslessly JSON-serializable')
  244. })
  245. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  246. // The documented escape valve: a deployment that must drop the harness
  247. // openers short-circuits the assemble waterfall; the request then carries
  248. // NO system field at all (not an empty string).
  249. const adapter = new MockAdapter([textResponse('ok')])
  250. const ctx = await harness(adapter)
  251. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  252. const agent = ctx.agentLoop.create(SessionId('a-no-system'), { provider: 'mock', model: 'mock' })
  253. send(agent, 'hi')
  254. await waitForIdle(ctx, agent)
  255. expect(adapter.requests).toHaveLength(1)
  256. expect('system' in adapter.requests[0]!).toBe(false)
  257. })
  258. it('records raw chunks for replay as assistant/chunk session events', async () => {
  259. const adapter = new MockAdapter([textResponse('abc')])
  260. const ctx = await harness(adapter)
  261. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  262. send(agent, 'hi')
  263. await waitForIdle(ctx, agent)
  264. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  265. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  266. expect(chunkEvents).toHaveLength(7)
  267. // replay: chunk events alone re-assemble to the recorded assistant message
  268. const deltaText = chunkEvents
  269. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  270. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  271. .map(c => c.text)
  272. .join('')
  273. expect(deltaText).toBe('abc')
  274. })
  275. it('injects steering between steps and continues the turn', async () => {
  276. const adapter = new MockAdapter([
  277. toolCallResponse('c1', 'slow', {}),
  278. textResponse('addressed the steering'),
  279. ])
  280. const ctx = await harness(adapter)
  281. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  282. ctx.tools.register(defineTool({
  283. name: 'slow',
  284. description: '',
  285. parameters: {},
  286. async execute() {
  287. // steer while the turn is running (during tool execution)
  288. agent.steer([{ type: 'text', text: 'change of plans' }])
  289. return [{ type: 'text', text: 'tool done' }]
  290. },
  291. }))
  292. send(agent, 'start')
  293. await waitForIdle(ctx, agent)
  294. const types = agent.session.events.map(e => e.type)
  295. expect(types).toContain('steering/message')
  296. // steering recorded before the second step's request derived its history
  297. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  298. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  299. expect(secondStepStart).toBeDefined()
  300. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  301. // the second model request saw the steering content
  302. const secondRequest = adapter.requests[1]
  303. const flat = JSON.stringify(secondRequest!.messages)
  304. expect(flat).toContain('change of plans')
  305. })
  306. it('steering while idle behaves like send (starts a turn)', async () => {
  307. const adapter = new MockAdapter([textResponse('ok')])
  308. const ctx = await harness(adapter)
  309. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  310. agent.steer([{ type: 'text', text: 'hello' }])
  311. await waitForIdle(ctx, agent)
  312. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  313. })
  314. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  315. const adapter = new MockAdapter([textResponse('ok')])
  316. const ctx = await harness(adapter)
  317. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  318. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  319. // The idle inject records a self-contained turn (turn/start → context/message
  320. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  321. await new Promise(r => setTimeout(r, 20))
  322. expect(agent.status).toBe('idle')
  323. expect(adapter.requests).toHaveLength(0)
  324. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  325. expect(injectedTurn).toHaveLength(1)
  326. const it0 = injectedTurn[0]!
  327. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  328. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  329. send(agent, 'go')
  330. await waitForIdle(ctx, agent)
  331. const flat = JSON.stringify(adapter.requests[0]!.messages)
  332. expect(flat).toContain('file changed: a.ts')
  333. expect(flat).toContain('<context source=\\"plugin\\">')
  334. })
  335. it('inject() can persist raw structured context without the generic context envelope', async () => {
  336. const adapter = new MockAdapter([textResponse('ok')])
  337. const ctx = await harness(adapter)
  338. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  339. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  340. const meta = {
  341. kind: 'workspace-instructions',
  342. version: 1,
  343. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  344. }
  345. agent.inject([{ type: 'text', text }], {
  346. source: { kind: 'plugin', plugin: 'workspace-context' },
  347. envelope: 'raw',
  348. meta,
  349. })
  350. send(agent, 'go')
  351. await waitForIdle(ctx, agent)
  352. const contextEvent = agent.session.events.find(event => event.type === 'context/message')
  353. expect(contextEvent?.type === 'context/message' && contextEvent.data).toMatchObject({ envelope: 'raw', meta })
  354. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  355. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  356. expect(requestText).not.toContain('<context source=')
  357. })
  358. it('defers inject() during tool execution until after the tool result', async () => {
  359. const adapter = new MockAdapter([
  360. toolCallResponse('c1', 'noticer', {}, 'calling'),
  361. textResponse('done'),
  362. ])
  363. const ctx = await harness(adapter)
  364. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  365. let visibleDuringTool = false
  366. const meta = { kind: 'deferred-test', version: 1 }
  367. ctx.tools.register(defineTool({
  368. name: 'noticer',
  369. description: 'injects a notice',
  370. parameters: {},
  371. async execute() {
  372. await Promise.resolve()
  373. const first = { type: 'text' as const, text: 'mid-turn notice' }
  374. agent.inject([first], {
  375. source: { kind: 'plugin', plugin: 'x' },
  376. envelope: 'raw',
  377. meta,
  378. })
  379. first.text = 'mutated after inject'
  380. agent.inject([{ type: 'text', text: 'second notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  381. visibleDuringTool = agent.session.events.some(e => e.type === 'context/message')
  382. return [{ type: 'text', text: 'ok' }]
  383. },
  384. }))
  385. send(agent, 'go')
  386. await waitForIdle(ctx, agent)
  387. expect(visibleDuringTool).toBe(false)
  388. // The injection stays in the open turn, but its user-role context cannot
  389. // split the assistant tool call from the provider's tool-result message.
  390. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  391. expect(turnStarts).toHaveLength(1)
  392. const ts0 = turnStarts[0]!
  393. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  394. const result = agent.session.events.find(e => e.type === 'tool/result')!
  395. const contexts = agent.session.events.filter(e => e.type === 'context/message')
  396. expect(contexts).toHaveLength(2)
  397. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  398. expect(contexts[0]?.type === 'context/message' && contexts[0].data).toMatchObject({
  399. envelope: 'raw',
  400. meta,
  401. })
  402. expect(contexts.flatMap(event => event.type === 'context/message' ? event.data.content : []))
  403. .toEqual([
  404. { type: 'text', text: 'mid-turn notice' },
  405. { type: 'text', text: 'second notice' },
  406. ])
  407. const secondRequest = adapter.requests[1]!.messages
  408. const resultIndex = secondRequest.findIndex(message =>
  409. message.content.some(block => block.type === 'tool-result'))
  410. const contextIndexes = secondRequest.flatMap((message, index) =>
  411. message.content.some(block => block.type === 'text'
  412. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  413. ? [index]
  414. : [])
  415. expect(resultIndex).toBeGreaterThanOrEqual(0)
  416. expect(contextIndexes).toHaveLength(2)
  417. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  418. })
  419. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  420. const adapter = new MockAdapter([
  421. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  422. textResponse('done'),
  423. ])
  424. const ctx = await harness(adapter)
  425. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  426. ctx.tools.register(defineTool({
  427. name: 'invalid-injector',
  428. description: 'attempts an invalid context injection',
  429. parameters: {},
  430. async execute() {
  431. expect(() => {
  432. agent.inject([{ type: 'text', text: 'invalid' }], {
  433. source: { kind: 'plugin', plugin: 'test' },
  434. meta: { bigint: 1n } as never,
  435. })
  436. }).toThrow('agent context must be losslessly JSON-serializable')
  437. return [{ type: 'text', text: 'rejected invalid context' }]
  438. },
  439. }))
  440. send(agent, 'go')
  441. await waitForIdle(ctx, agent)
  442. expect(agent.session.events.some(event => event.type === 'context/message')).toBe(false)
  443. })
  444. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  445. // force-continue: model never calls tools, but a plugin forces 3 steps
  446. const adapter = new MockAdapter([
  447. textResponse('step 1'),
  448. textResponse('step 2'),
  449. textResponse('step 3'),
  450. ])
  451. const ctx = await harness(adapter)
  452. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  453. let steps = 0
  454. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  455. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  456. if (steps < 3) return { action: 'continue' as const }
  457. return next()
  458. })
  459. send(agent, 'go')
  460. await waitForIdle(ctx, agent)
  461. expect(steps).toBe(3)
  462. expect(adapter.requests).toHaveLength(3)
  463. })
  464. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  465. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  466. const ctx = await harness(adapter)
  467. ctx.tools.register(defineTool({
  468. name: 'echo',
  469. description: '',
  470. parameters: { text: { type: 'string' } },
  471. async execute(args) {
  472. return [{ type: 'text', text: String(args.text) }]
  473. },
  474. }))
  475. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  476. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  477. send(agent, 'go')
  478. await waitForIdle(ctx, agent)
  479. // only one model call despite the tool call requesting a follow-up
  480. expect(adapter.requests).toHaveLength(1)
  481. // tool still executed before the decision
  482. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  483. })
  484. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  485. const adapter = new MockAdapter([textResponse('ok')])
  486. const ctx = await harness(adapter)
  487. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  488. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  489. // The seed is frozen — config is not a mutable per-call knob; a switch
  490. // is proposed by returning a replacement, and the loop logs it.
  491. expect(Object.isFrozen(config)).toBe(true)
  492. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  493. return { ...config, model: 'other-model' }
  494. })
  495. send(agent, 'hi')
  496. await waitForIdle(ctx, agent)
  497. expect(adapter.requests[0]!.model).toBe('other-model')
  498. // The header event records what the request ACTUALLY used — the switch is
  499. // a reconstructable fact, not silent drift.
  500. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  501. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  502. })
  503. it('agent/pre-step fires once per step before the step is opened', async () => {
  504. // Two steps (a tool call, then a final text turn) → two model calls → two
  505. // pre-step fires, each carrying the assembled full system prompt, BEFORE
  506. // the step is opened and its request is derived (the request the adapter
  507. // sees reflects any surface state at fire time).
  508. const adapter = new MockAdapter([
  509. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  510. textResponse('done'),
  511. ])
  512. const ctx = await harness(adapter)
  513. ctx.tools.register(defineTool({
  514. name: 'echo', description: 'echo', parameters: {},
  515. async execute() { return [{ type: 'text', text: 'echoed' }] },
  516. }))
  517. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  518. const fires: { turn: number; step: number; fullSystemPrompt: string }[] = []
  519. ctx.on('agent/pre-step', (subject, turn, step, fullSystemPrompt) => {
  520. if (subject === agent) fires.push({ turn, step, fullSystemPrompt })
  521. })
  522. send(agent, 'go')
  523. await waitForIdle(ctx, agent)
  524. // One fire per step, in order, each with the assembled system prompt
  525. // (here just the loop's own harness-identity section — no persona set).
  526. const HARNESS = 'You are an AI agent powered by the DeepSeek Harness SDK.'
  527. expect(fires).toEqual([
  528. { turn: 1, step: 1, fullSystemPrompt: HARNESS },
  529. { turn: 1, step: 2, fullSystemPrompt: HARNESS },
  530. ])
  531. })
  532. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  533. // The append lands before step/start, yet derive happens afterwards and the
  534. // same step's request must include it.
  535. const adapter = new MockAdapter([textResponse('ok')])
  536. const ctx = await harness(adapter)
  537. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  538. let injected = false
  539. ctx.on('agent/pre-step', (subject) => {
  540. if (subject === agent && !injected) {
  541. injected = true
  542. subject.session.append('context/message', {
  543. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  544. source: { kind: 'plugin', plugin: 'test' },
  545. }, { surfaceOp: 'append' })
  546. }
  547. })
  548. send(agent, 'go')
  549. await waitForIdle(ctx, agent)
  550. // The adapter's request includes the node injected during pre-step (derive
  551. // reflects it).
  552. const text = JSON.stringify(adapter.requests[0]!.messages)
  553. expect(text).toContain('INJECTED-IN-PRE-STEP')
  554. // And the injected event sits BEFORE the first step/start in the log —
  555. // the seam fired outside the step.
  556. const events = agent.session.events
  557. const injectedSeq = events.find(e => e.type === 'context/message')!.seq
  558. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  559. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  560. })
  561. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  562. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  563. // closing, the turn records error, and the loop remains available.
  564. const adapter = new MockAdapter([textResponse('second turn ok')])
  565. const ctx = await harness(adapter)
  566. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  567. let throwOnce = true
  568. ctx.on('agent/pre-step', () => {
  569. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  570. })
  571. const errors: Error[] = []
  572. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  573. send(agent, 'first')
  574. await waitForIdle(ctx, agent)
  575. // The first turn failed at step 1 (no model call happened), surfaced via
  576. // agent/error, with the durable failure on turn/end.reason.
  577. expect(errors).toHaveLength(1)
  578. expect(errors[0]!.message).toContain('boom in pre-step')
  579. expect(adapter.requests.length).toBe(0)
  580. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  581. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  582. // The step opened-and-closed count stays balanced even though it never ran.
  583. const types = agent.session.events.map(e => e.type)
  584. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  585. // The loop survived: a second prompt runs a normal completed turn.
  586. send(agent, 'second')
  587. await waitForIdle(ctx, agent)
  588. expect(adapter.requests.length).toBe(1)
  589. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  590. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  591. })
  592. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  593. const adapter = new MockAdapter(['hang'])
  594. const ctx = await harness(adapter)
  595. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  596. const reasons: TurnEndReason[] = []
  597. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  598. send(agent, 'go')
  599. // wait until the stream is hanging, then cancel
  600. await new Promise(r => setTimeout(r, 30))
  601. expect(agent.status).toBe('running')
  602. agent.cancel('user interrupt')
  603. await waitForIdle(ctx, agent)
  604. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  605. })
  606. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  607. // A single step that ends with a max-tokens finish (no tool calls): the
  608. // turn stops by default and ends max-tokens, not completed.
  609. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  610. const ctx = await harness(adapter)
  611. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  612. const reasons: TurnEndReason[] = []
  613. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  614. send(agent, 'go')
  615. await waitForIdle(ctx, agent)
  616. expect(adapter.requests).toHaveLength(1)
  617. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  618. // Assert the durable row, not only the live listener.
  619. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  620. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  621. })
  622. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  623. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  624. // must be FORCED to reach step 2 which finishes normally (stop).
  625. const adapter = new MockAdapter([
  626. maxTokensResponse('first half'),
  627. textResponse('second half'),
  628. ])
  629. const ctx = await harness(adapter)
  630. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  631. let steps = 0
  632. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  633. // Force exactly one continuation (step 1 → step 2), then defer to default
  634. // (step 2 is a plain stop with no tool calls → stops).
  635. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  636. if (steps < 2) return { action: 'continue' as const }
  637. return next()
  638. })
  639. const reasons: TurnEndReason[] = []
  640. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  641. send(agent, 'go')
  642. await waitForIdle(ctx, agent)
  643. expect(steps).toBe(2)
  644. expect(adapter.requests).toHaveLength(2)
  645. expect(adapter.requests[1]!.messages).toEqual([
  646. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  647. { role: 'assistant', content: [{ type: 'text', text: 'first half' }], provenance: { provider: 'mock', model: 'mock' } },
  648. ])
  649. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  650. })
  651. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  652. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  653. // stop. The per-turn reason must be independent — turn 2 ends completed.
  654. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  655. const ctx = await harness(adapter)
  656. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  657. const reasons: TurnEndReason[] = []
  658. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  659. send(agent, 'first')
  660. await waitForIdle(ctx, agent)
  661. send(agent, 'second')
  662. await waitForIdle(ctx, agent)
  663. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  664. })
  665. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  666. const callId = CallId('c1')
  667. const adapter = new MockAdapter([[
  668. { type: 'block-start', index: 0, blockType: 'tool-call' },
  669. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  670. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  671. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  672. { type: 'finish', reason: { kind: 'max-tokens' } },
  673. ]])
  674. const ctx = await harness(adapter)
  675. let executions = 0
  676. ctx.tools.register(defineTool({
  677. name: 'echo',
  678. description: '',
  679. parameters: { text: { type: 'string' } },
  680. async execute() {
  681. executions += 1
  682. return [{ type: 'text', text: 'should not run' }]
  683. },
  684. }))
  685. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  686. const reasons: TurnEndReason[] = []
  687. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  688. send(agent, 'go')
  689. await waitForIdle(ctx, agent)
  690. expect(executions).toBe(0)
  691. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  692. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  693. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  694. // Empty content still needs an assistant/message to carry usage; derivation
  695. // skips that host so it does not create a spurious assistant turn.
  696. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  697. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  698. turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' }, usage: { inputTokens: 10, outputTokens: 5 },
  699. })
  700. })
  701. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  702. // The truncated tool call is dropped from durable content, while the
  703. // successful provider call still needs an exact replay anchor.
  704. const callId = CallId('c1')
  705. const adapter = new MockAdapter([[
  706. { type: 'block-start', index: 0, blockType: 'tool-call' },
  707. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  708. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  709. { type: 'finish', reason: { kind: 'max-tokens' } },
  710. ]])
  711. const ctx = await harness(adapter)
  712. ctx.tools.register(defineTool({
  713. name: 'echo',
  714. description: '',
  715. parameters: { text: { type: 'string' } },
  716. async execute() { return [{ type: 'text', text: 'should not run' }] },
  717. }))
  718. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  719. const reasons: TurnEndReason[] = []
  720. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  721. send(agent, 'go')
  722. await waitForIdle(ctx, agent)
  723. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  724. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  725. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  726. turn: 1,
  727. step: 1,
  728. content: [],
  729. provenance: { provider: 'mock', model: 'mock' },
  730. })
  731. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  732. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  733. })
  734. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  735. // A clean content-less call stays absent from derived messages but remains
  736. // a durable successful-call boundary for replay consumers.
  737. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  738. const ctx = await harness(adapter)
  739. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  740. const reasons: TurnEndReason[] = []
  741. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  742. send(agent, 'go')
  743. await waitForIdle(ctx, agent)
  744. expect(reasons).toEqual([{ kind: 'completed' }])
  745. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  746. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  747. turn: 1,
  748. step: 1,
  749. content: [],
  750. provenance: { provider: 'mock', model: 'mock' },
  751. })
  752. expect(assistant.sourceEventSeqs?.length).toBe(1)
  753. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  754. })
  755. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  756. const callId = CallId('c1')
  757. const adapter = new MockAdapter([[
  758. { type: 'block-start', index: 0, blockType: 'text' },
  759. { type: 'text-delta', index: 0, text: 'partial text' },
  760. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  761. { type: 'block-start', index: 1, blockType: 'tool-call' },
  762. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  763. { type: 'finish', reason: { kind: 'max-tokens' } },
  764. ]])
  765. const ctx = await harness(adapter)
  766. let stepResults = 0
  767. ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
  768. stepResults += 1
  769. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  770. return next()
  771. })
  772. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  773. send(agent, 'go')
  774. await waitForIdle(ctx, agent)
  775. expect(stepResults).toBe(1)
  776. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  777. expect(agent.session.deriveMessages()).toEqual([
  778. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  779. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }], provenance: { provider: 'mock', model: 'mock' } },
  780. ])
  781. })
  782. it('contains a step/end observer failure without changing continuation', async () => {
  783. const adapter = new MockAdapter([
  784. toolCallResponse('c1', 'echo', { text: 'x' }),
  785. textResponse('continued after tool call'),
  786. ])
  787. const ctx = await harness(adapter)
  788. ctx.tools.register(defineTool({
  789. name: 'echo',
  790. description: '',
  791. parameters: { text: { type: 'string' } },
  792. async execute(args) {
  793. return [{ type: 'text', text: String(args.text) }]
  794. },
  795. }))
  796. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  797. let threw = false
  798. // Post-commit session observers cannot control the loop. The tool call still
  799. // drives the second model request, and the turn completes normally.
  800. ctx.on('session/event', (_session, event) => {
  801. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  802. })
  803. send(agent, 'go')
  804. await waitForIdle(ctx, agent)
  805. expect(adapter.requests).toHaveLength(2)
  806. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  807. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  808. })
  809. it('chains queued messages into consecutive turns', async () => {
  810. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  811. const ctx = await harness(adapter)
  812. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  813. const turns: number[] = []
  814. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  815. // queue two messages while idle — first starts turn 1 immediately;
  816. // queue the second during turn 1 when the first assistant chunk streams
  817. let queued = false
  818. ctx.on('session/event', (_s, event) => {
  819. if (event.type === 'assistant/chunk' && !queued) {
  820. queued = true
  821. send(agent, 'second message')
  822. }
  823. })
  824. send(agent, 'first message')
  825. await waitForIdle(ctx, agent)
  826. expect(turns).toEqual([1, 2])
  827. expect(adapter.requests).toHaveLength(2)
  828. })
  829. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  830. const adapter = new MockAdapter([textResponse('ok')])
  831. const ctx = await harness(adapter)
  832. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  833. let flushed = 0
  834. let flushedBeforeIdle = false
  835. ctx.on('session/flush', async (session) => {
  836. await new Promise(r => setTimeout(r, 10))
  837. flushed++
  838. flushedBeforeIdle = agent.status !== 'idle'
  839. void session
  840. })
  841. send(agent, 'hi')
  842. await waitForIdle(ctx, agent)
  843. expect(flushed).toBe(1)
  844. expect(flushedBeforeIdle).toBe(true)
  845. })
  846. it('errors from the model surface as agent/error and end the turn', async () => {
  847. const adapter = new MockAdapter([]) // script exhausted → throws
  848. const ctx = await harness(adapter)
  849. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  850. const errors: Error[] = []
  851. const reasons: TurnEndReason[] = []
  852. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  853. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  854. send(agent, 'hi')
  855. await waitForIdle(ctx, agent)
  856. expect(errors).toHaveLength(1)
  857. expect(errors[0]!.message).toContain('script exhausted')
  858. expect(reasons[0]).toMatchObject({ kind: 'error' })
  859. // The durable failure lives entirely on turn/end.reason (with the failing
  860. // step), not a standalone error event.
  861. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  862. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  863. })
  864. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  865. const adapter = new MockAdapter(['hang'])
  866. const ctx = await harness(adapter)
  867. let agent!: ReactLoopAgent
  868. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  869. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  870. }, { inject: ['agentLoop'] }))
  871. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  872. send(agent, 'go')
  873. await new Promise(r => setTimeout(r, 30))
  874. expect(agent.status).toBe('running')
  875. await fiber.dispose()
  876. await agent.done
  877. expect(agent.status).toBe('disposed')
  878. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  879. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  880. })
  881. it('creates agents from config on startup', async () => {
  882. const adapter = new MockAdapter([textResponse('from config')])
  883. const ctx = new Context()
  884. await ctx.plugin(LlmService)
  885. await ctx.plugin(SessionStore)
  886. await ctx.plugin(SystemPrompt)
  887. await ctx.plugin(ToolRegistry)
  888. await ctx.plugin(AgentRegistry)
  889. await ctx.plugin(AgentLoop, {
  890. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  891. })
  892. ctx.llm.registerAdapter(['mock'], adapter)
  893. const agent = ctx.agents.list()[0]! as ReactLoopAgent
  894. expect(agent).toBeDefined()
  895. expect(agent.id).toBe(agent.session.id)
  896. expect(agent.id).toMatch(/^config-agent-session-/)
  897. expect(agent.options.model).toBe('mock')
  898. // the agent is alive: send triggers a turn
  899. send(agent, 'hi')
  900. await waitForIdle(ctx, agent)
  901. expect(adapter.requests).toHaveLength(1)
  902. })
  903. it('attaches config agent cwd to the fresh session header', async () => {
  904. const ctx = new Context()
  905. await ctx.plugin(LlmService)
  906. await ctx.plugin(SessionStore)
  907. await ctx.plugin(SystemPrompt)
  908. await ctx.plugin(ToolRegistry)
  909. await ctx.plugin(AgentRegistry)
  910. await ctx.plugin(AgentLoop, {
  911. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  912. })
  913. const agent = ctx.agents.list()[0]! as ReactLoopAgent
  914. expect(agent.session.header.cwd).toBe('/work/project')
  915. })
  916. it('replays a session log into an identical derived history', async () => {
  917. const adapter = new MockAdapter([
  918. toolCallResponse('c1', 'echo', { text: 'x' }),
  919. textResponse('done'),
  920. ])
  921. const ctx = await harness(adapter)
  922. ctx.tools.register(defineTool({
  923. name: 'echo',
  924. description: '',
  925. parameters: { text: { type: 'string' } },
  926. async execute(args) {
  927. return [{ type: 'text', text: String(args.text) }]
  928. },
  929. }))
  930. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  931. send(agent, 'run')
  932. await waitForIdle(ctx, agent)
  933. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  934. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  935. // event-by-event identity of types
  936. expect(replayed.events.map(e => e.type)).toEqual(
  937. agent.session.events.map(e => e.type))
  938. })
  939. })