loop.spec.ts 46 KB

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