loop.spec.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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('same-tick idle steering inherits one-send-one-turn FIFO behavior', async () => {
  310. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  311. const ctx = await harness(adapter)
  312. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  313. const idle = waitForIdle(ctx, agent)
  314. agent.steer([{ type: 'text', text: 'first idle steer' }])
  315. agent.steer([{ type: 'text', text: 'second idle steer' }])
  316. await idle
  317. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  318. expect(agent.session.events
  319. .filter(event => event.type === 'user/message')
  320. .map(event => event.data.content)).toEqual([
  321. [{ type: 'text', text: 'first idle steer' }],
  322. [{ type: 'text', text: 'second idle steer' }],
  323. ])
  324. expect(adapter.requests).toHaveLength(2)
  325. })
  326. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  327. const adapter = new MockAdapter([textResponse('ok')])
  328. const ctx = await harness(adapter)
  329. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  330. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  331. // The idle inject records a self-contained turn (turn/start → context/message
  332. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  333. await new Promise(r => setTimeout(r, 20))
  334. expect(agent.status).toBe('idle')
  335. expect(adapter.requests).toHaveLength(0)
  336. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  337. expect(injectedTurn).toHaveLength(1)
  338. const it0 = injectedTurn[0]!
  339. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  340. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  341. send(agent, 'go')
  342. await waitForIdle(ctx, agent)
  343. const flat = JSON.stringify(adapter.requests[0]!.messages)
  344. expect(flat).toContain('file changed: a.ts')
  345. expect(flat).not.toContain('<context source=')
  346. })
  347. it('inject() persists structured context content verbatim with durable hidden meta', async () => {
  348. const adapter = new MockAdapter([textResponse('ok')])
  349. const ctx = await harness(adapter)
  350. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  351. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  352. const meta = {
  353. kind: 'workspace-instructions',
  354. version: 1,
  355. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  356. }
  357. agent.inject([{ type: 'text', text }], {
  358. source: { kind: 'plugin', plugin: 'workspace-context' },
  359. meta,
  360. })
  361. send(agent, 'go')
  362. await waitForIdle(ctx, agent)
  363. const contextEvent = agent.session.events.find(event => event.type === 'context/message')
  364. expect(contextEvent?.type === 'context/message' && contextEvent.data).toMatchObject({ meta })
  365. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  366. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  367. expect(requestText).not.toContain('<context source=')
  368. })
  369. it('defers inject() during tool execution until after the tool result', async () => {
  370. const adapter = new MockAdapter([
  371. toolCallResponse('c1', 'noticer', {}, 'calling'),
  372. textResponse('done'),
  373. ])
  374. const ctx = await harness(adapter)
  375. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  376. let visibleDuringTool = false
  377. const meta = { kind: 'deferred-test', version: 1 }
  378. ctx.tools.register(defineTool({
  379. name: 'noticer',
  380. description: 'injects a notice',
  381. parameters: {},
  382. async execute() {
  383. await Promise.resolve()
  384. const first = { type: 'text' as const, text: 'mid-turn notice' }
  385. agent.inject([first], {
  386. source: { kind: 'plugin', plugin: 'x' },
  387. meta,
  388. })
  389. first.text = 'mutated after inject'
  390. agent.inject([{ type: 'text', text: 'second notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  391. visibleDuringTool = agent.session.events.some(e => e.type === 'context/message')
  392. return [{ type: 'text', text: 'ok' }]
  393. },
  394. }))
  395. send(agent, 'go')
  396. await waitForIdle(ctx, agent)
  397. expect(visibleDuringTool).toBe(false)
  398. // The injection stays in the open turn, but its user-role context cannot
  399. // split the assistant tool call from the provider's tool-result message.
  400. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  401. expect(turnStarts).toHaveLength(1)
  402. const ts0 = turnStarts[0]!
  403. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  404. const result = agent.session.events.find(e => e.type === 'tool/result')!
  405. const contexts = agent.session.events.filter(e => e.type === 'context/message')
  406. expect(contexts).toHaveLength(2)
  407. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  408. expect(contexts[0]?.type === 'context/message' && contexts[0].data).toMatchObject({
  409. meta,
  410. })
  411. expect(contexts.flatMap(event => event.type === 'context/message' ? event.data.content : []))
  412. .toEqual([
  413. { type: 'text', text: 'mid-turn notice' },
  414. { type: 'text', text: 'second notice' },
  415. ])
  416. const secondRequest = adapter.requests[1]!.messages
  417. const resultIndex = secondRequest.findIndex(message =>
  418. message.content.some(block => block.type === 'tool-result'))
  419. const contextIndexes = secondRequest.flatMap((message, index) =>
  420. message.content.some(block => block.type === 'text'
  421. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  422. ? [index]
  423. : [])
  424. expect(resultIndex).toBeGreaterThanOrEqual(0)
  425. expect(contextIndexes).toHaveLength(2)
  426. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  427. })
  428. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  429. const adapter = new MockAdapter([
  430. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  431. textResponse('done'),
  432. ])
  433. const ctx = await harness(adapter)
  434. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  435. ctx.tools.register(defineTool({
  436. name: 'invalid-injector',
  437. description: 'attempts an invalid context injection',
  438. parameters: {},
  439. async execute() {
  440. expect(() => {
  441. agent.inject([{ type: 'text', text: 'invalid' }], {
  442. source: { kind: 'plugin', plugin: 'test' },
  443. meta: { bigint: 1n } as never,
  444. })
  445. }).toThrow('agent context must be losslessly JSON-serializable')
  446. return [{ type: 'text', text: 'rejected invalid context' }]
  447. },
  448. }))
  449. send(agent, 'go')
  450. await waitForIdle(ctx, agent)
  451. expect(agent.session.events.some(event => event.type === 'context/message')).toBe(false)
  452. })
  453. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  454. // force-continue: model never calls tools, but a plugin forces 3 steps
  455. const adapter = new MockAdapter([
  456. textResponse('step 1'),
  457. textResponse('step 2'),
  458. textResponse('step 3'),
  459. ])
  460. const ctx = await harness(adapter)
  461. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  462. let steps = 0
  463. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  464. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  465. if (steps < 3) return { action: 'continue' as const }
  466. return next()
  467. })
  468. send(agent, 'go')
  469. await waitForIdle(ctx, agent)
  470. expect(steps).toBe(3)
  471. expect(adapter.requests).toHaveLength(3)
  472. })
  473. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  474. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  475. const ctx = await harness(adapter)
  476. ctx.tools.register(defineTool({
  477. name: 'echo',
  478. description: '',
  479. parameters: { text: { type: 'string' } },
  480. async execute(args) {
  481. return [{ type: 'text', text: String(args.text) }]
  482. },
  483. }))
  484. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  485. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  486. send(agent, 'go')
  487. await waitForIdle(ctx, agent)
  488. // only one model call despite the tool call requesting a follow-up
  489. expect(adapter.requests).toHaveLength(1)
  490. // tool still executed before the decision
  491. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  492. })
  493. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  494. const adapter = new MockAdapter([textResponse('ok')])
  495. const ctx = await harness(adapter)
  496. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  497. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  498. // The seed is frozen — config is not a mutable per-call knob; a switch
  499. // is proposed by returning a replacement, and the loop logs it.
  500. expect(Object.isFrozen(config)).toBe(true)
  501. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  502. return { ...config, model: 'other-model' }
  503. })
  504. send(agent, 'hi')
  505. await waitForIdle(ctx, agent)
  506. expect(adapter.requests[0]!.model).toBe('other-model')
  507. // The header event records what the request ACTUALLY used — the switch is
  508. // a reconstructable fact, not silent drift.
  509. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  510. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  511. })
  512. it('agent/pre-step fires once per step before the step is opened', async () => {
  513. const adapter = new MockAdapter([
  514. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  515. textResponse('done'),
  516. ])
  517. const ctx = await harness(adapter)
  518. ctx.tools.register(defineTool({
  519. name: 'echo', description: 'echo', parameters: {},
  520. async execute() { return [{ type: 'text', text: 'echoed' }] },
  521. }))
  522. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  523. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  524. ctx.on('agent/pre-step', (subject, turn, step, signal) => {
  525. if (subject === agent) fires.push({ turn, step, signal })
  526. })
  527. send(agent, 'go')
  528. await waitForIdle(ctx, agent)
  529. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  530. { turn: 1, step: 1 },
  531. { turn: 1, step: 2 },
  532. ])
  533. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  534. })
  535. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  536. // The append lands before step/start, yet derive happens afterwards and the
  537. // same step's request must include it.
  538. const adapter = new MockAdapter([textResponse('ok')])
  539. const ctx = await harness(adapter)
  540. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  541. let injected = false
  542. ctx.on('agent/pre-step', (subject) => {
  543. if (subject === agent && !injected) {
  544. injected = true
  545. subject.session.append('context/message', {
  546. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  547. source: { kind: 'plugin', plugin: 'test' },
  548. }, { surfaceOp: 'append' })
  549. }
  550. })
  551. send(agent, 'go')
  552. await waitForIdle(ctx, agent)
  553. // The adapter's request includes the node injected during pre-step (derive
  554. // reflects it).
  555. const text = JSON.stringify(adapter.requests[0]!.messages)
  556. expect(text).toContain('INJECTED-IN-PRE-STEP')
  557. // And the injected event sits BEFORE the first step/start in the log —
  558. // the seam fired outside the step.
  559. const events = agent.session.events
  560. const injectedSeq = events.find(e => e.type === 'context/message')!.seq
  561. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  562. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  563. })
  564. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  565. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  566. // closing, the turn records error, and the loop remains available.
  567. const adapter = new MockAdapter([textResponse('second turn ok')])
  568. const ctx = await harness(adapter)
  569. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  570. let throwOnce = true
  571. ctx.on('agent/pre-step', () => {
  572. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  573. })
  574. const errors: Error[] = []
  575. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  576. send(agent, 'first')
  577. await waitForIdle(ctx, agent)
  578. // The first turn failed at step 1 (no model call happened), surfaced via
  579. // agent/error, with the durable failure on turn/end.reason.
  580. expect(errors).toHaveLength(1)
  581. expect(errors[0]!.message).toContain('boom in pre-step')
  582. expect(adapter.requests.length).toBe(0)
  583. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  584. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  585. // The step opened-and-closed count stays balanced even though it never ran.
  586. const types = agent.session.events.map(e => e.type)
  587. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  588. // The loop survived: a second prompt runs a normal completed turn.
  589. send(agent, 'second')
  590. await waitForIdle(ctx, agent)
  591. expect(adapter.requests.length).toBe(1)
  592. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  593. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  594. })
  595. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  596. const adapter = new MockAdapter(['hang'])
  597. const ctx = await harness(adapter)
  598. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  599. const reasons: TurnEndReason[] = []
  600. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  601. send(agent, 'go')
  602. // wait until the stream is hanging, then cancel
  603. await new Promise(r => setTimeout(r, 30))
  604. expect(agent.status).toBe('running')
  605. agent.cancel('user interrupt')
  606. await waitForIdle(ctx, agent)
  607. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  608. })
  609. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  610. // A single step that ends with a max-tokens finish (no tool calls): the
  611. // turn stops by default and ends max-tokens, not completed.
  612. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  613. const ctx = await harness(adapter)
  614. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  615. const reasons: TurnEndReason[] = []
  616. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  617. send(agent, 'go')
  618. await waitForIdle(ctx, agent)
  619. expect(adapter.requests).toHaveLength(1)
  620. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  621. // Assert the durable row, not only the live listener.
  622. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  623. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  624. })
  625. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  626. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  627. // must be FORCED to reach step 2 which finishes normally (stop).
  628. const adapter = new MockAdapter([
  629. maxTokensResponse('first half'),
  630. textResponse('second half'),
  631. ])
  632. const ctx = await harness(adapter)
  633. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  634. let steps = 0
  635. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  636. // Force exactly one continuation (step 1 → step 2), then defer to default
  637. // (step 2 is a plain stop with no tool calls → stops).
  638. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  639. if (steps < 2) return { action: 'continue' as const }
  640. return next()
  641. })
  642. const reasons: TurnEndReason[] = []
  643. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  644. send(agent, 'go')
  645. await waitForIdle(ctx, agent)
  646. expect(steps).toBe(2)
  647. expect(adapter.requests).toHaveLength(2)
  648. expect(adapter.requests[1]!.messages).toEqual([
  649. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  650. { role: 'assistant', content: [{ type: 'text', text: 'first half' }], provenance: { provider: 'mock', model: 'mock' } },
  651. ])
  652. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  653. })
  654. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  655. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  656. // stop. The per-turn reason must be independent — turn 2 ends completed.
  657. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  658. const ctx = await harness(adapter)
  659. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  660. const reasons: TurnEndReason[] = []
  661. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  662. send(agent, 'first')
  663. await waitForIdle(ctx, agent)
  664. send(agent, 'second')
  665. await waitForIdle(ctx, agent)
  666. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  667. })
  668. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  669. const callId = CallId('c1')
  670. const adapter = new MockAdapter([[
  671. { type: 'block-start', index: 0, blockType: 'tool-call' },
  672. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  673. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  674. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  675. { type: 'finish', reason: { kind: 'max-tokens' } },
  676. ]])
  677. const ctx = await harness(adapter)
  678. let executions = 0
  679. ctx.tools.register(defineTool({
  680. name: 'echo',
  681. description: '',
  682. parameters: { text: { type: 'string' } },
  683. async execute() {
  684. executions += 1
  685. return [{ type: 'text', text: 'should not run' }]
  686. },
  687. }))
  688. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  689. const reasons: TurnEndReason[] = []
  690. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  691. send(agent, 'go')
  692. await waitForIdle(ctx, agent)
  693. expect(executions).toBe(0)
  694. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  695. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  696. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  697. // Empty content still needs an assistant/message to carry usage; derivation
  698. // skips that host so it does not create a spurious assistant turn.
  699. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  700. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  701. turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' }, usage: { inputTokens: 10, outputTokens: 5 },
  702. })
  703. })
  704. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  705. // The truncated tool call is dropped from durable content, while the
  706. // successful provider call still needs an exact replay anchor.
  707. const callId = CallId('c1')
  708. const adapter = new MockAdapter([[
  709. { type: 'block-start', index: 0, blockType: 'tool-call' },
  710. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  711. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  712. { type: 'finish', reason: { kind: 'max-tokens' } },
  713. ]])
  714. const ctx = await harness(adapter)
  715. ctx.tools.register(defineTool({
  716. name: 'echo',
  717. description: '',
  718. parameters: { text: { type: 'string' } },
  719. async execute() { return [{ type: 'text', text: 'should not run' }] },
  720. }))
  721. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  722. const reasons: TurnEndReason[] = []
  723. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  724. send(agent, 'go')
  725. await waitForIdle(ctx, agent)
  726. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  727. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  728. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  729. turn: 1,
  730. step: 1,
  731. content: [],
  732. provenance: { provider: 'mock', model: 'mock' },
  733. })
  734. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  735. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  736. })
  737. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  738. // A clean content-less call stays absent from derived messages but remains
  739. // a durable successful-call boundary for replay consumers.
  740. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  741. const ctx = await harness(adapter)
  742. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  743. const reasons: TurnEndReason[] = []
  744. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  745. send(agent, 'go')
  746. await waitForIdle(ctx, agent)
  747. expect(reasons).toEqual([{ kind: 'completed' }])
  748. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  749. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  750. turn: 1,
  751. step: 1,
  752. content: [],
  753. provenance: { provider: 'mock', model: 'mock' },
  754. })
  755. expect(assistant.sourceEventSeqs?.length).toBe(1)
  756. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  757. })
  758. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  759. const callId = CallId('c1')
  760. const adapter = new MockAdapter([[
  761. { type: 'block-start', index: 0, blockType: 'text' },
  762. { type: 'text-delta', index: 0, text: 'partial text' },
  763. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  764. { type: 'block-start', index: 1, blockType: 'tool-call' },
  765. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  766. { type: 'finish', reason: { kind: 'max-tokens' } },
  767. ]])
  768. const ctx = await harness(adapter)
  769. let stepResults = 0
  770. ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
  771. stepResults += 1
  772. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  773. return next()
  774. })
  775. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  776. send(agent, 'go')
  777. await waitForIdle(ctx, agent)
  778. expect(stepResults).toBe(1)
  779. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  780. expect(agent.session.deriveMessages()).toEqual([
  781. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  782. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }], provenance: { provider: 'mock', model: 'mock' } },
  783. ])
  784. })
  785. it('contains a step/end observer failure without changing continuation', async () => {
  786. const adapter = new MockAdapter([
  787. toolCallResponse('c1', 'echo', { text: 'x' }),
  788. textResponse('continued after tool call'),
  789. ])
  790. const ctx = await harness(adapter)
  791. ctx.tools.register(defineTool({
  792. name: 'echo',
  793. description: '',
  794. parameters: { text: { type: 'string' } },
  795. async execute(args) {
  796. return [{ type: 'text', text: String(args.text) }]
  797. },
  798. }))
  799. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  800. let threw = false
  801. // Post-commit session observers cannot control the loop. The tool call still
  802. // drives the second model request, and the turn completes normally.
  803. ctx.on('session/event', (_session, event) => {
  804. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  805. })
  806. send(agent, 'go')
  807. await waitForIdle(ctx, agent)
  808. expect(adapter.requests).toHaveLength(2)
  809. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  810. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  811. })
  812. it('keeps same-tick sends in separate turns and checkpoints before the next starts', async () => {
  813. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer')])
  814. const ctx = await harness(adapter)
  815. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  816. const firstFlush = Promise.withResolvers<undefined>()
  817. const releaseFirstFlush = Promise.withResolvers<undefined>()
  818. let flushes = 0
  819. ctx.on('session/flush', async (session) => {
  820. if (session !== agent.session) return
  821. flushes += 1
  822. if (flushes === 1) {
  823. firstFlush.resolve(undefined)
  824. await releaseFirstFlush.promise
  825. }
  826. })
  827. const turns: number[] = []
  828. ctx.on('session/event', (session, event) => {
  829. if (session === agent.session && event.type === 'turn/start') turns.push(event.data.turn)
  830. })
  831. const idle = waitForIdle(ctx, agent)
  832. send(agent, 'first message')
  833. send(agent, 'second message')
  834. await firstFlush.promise
  835. expect(turns).toEqual([1])
  836. expect(adapter.requests).toHaveLength(1)
  837. releaseFirstFlush.resolve(undefined)
  838. await idle
  839. expect(turns).toEqual([1, 2])
  840. expect(flushes).toBe(2)
  841. expect(adapter.requests).toHaveLength(2)
  842. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first answer')
  843. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  844. })
  845. it('holds a turn-end listener send behind the closing turn checkpoint', async () => {
  846. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer')])
  847. const ctx = await harness(adapter)
  848. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  849. const firstFlush = Promise.withResolvers<undefined>()
  850. const releaseFirstFlush = Promise.withResolvers<undefined>()
  851. let flushes = 0
  852. ctx.on('session/flush', async (session) => {
  853. if (session !== agent.session) return
  854. flushes += 1
  855. if (flushes === 1) {
  856. firstFlush.resolve(undefined)
  857. await releaseFirstFlush.promise
  858. }
  859. })
  860. const turns: number[] = []
  861. const statuses: string[] = []
  862. ctx.on('agent/status', (subject, status) => {
  863. if (subject === agent) statuses.push(status)
  864. })
  865. ctx.on('session/event', (session, event) => {
  866. if (session !== agent.session) return
  867. if (event.type === 'turn/start') turns.push(event.data.turn)
  868. if (event.type === 'turn/end' && event.data.turn === 1) send(agent, 'turn-end listener message')
  869. })
  870. const idle = waitForIdle(ctx, agent)
  871. send(agent, 'first message')
  872. await firstFlush.promise
  873. expect(turns).toEqual([1])
  874. expect(adapter.requests).toHaveLength(1)
  875. releaseFirstFlush.resolve(undefined)
  876. await idle
  877. expect(turns).toEqual([1, 2])
  878. expect(statuses).toEqual(['running', 'idle'])
  879. expect(adapter.requests).toHaveLength(2)
  880. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first answer')
  881. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('turn-end listener message')
  882. })
  883. it('keeps a reentrant agent/queued send as the next independent turn', async () => {
  884. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  885. const ctx = await harness(adapter)
  886. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  887. let nested = false
  888. ctx.on('agent/queued', (subject) => {
  889. if (subject !== agent || nested) return
  890. nested = true
  891. send(agent, 'queued listener message')
  892. })
  893. const idle = waitForIdle(ctx, agent)
  894. send(agent, 'outer message')
  895. await idle
  896. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  897. const messages = agent.session.events
  898. .filter(event => event.type === 'user/message')
  899. .map(event => event.data.content)
  900. expect(turns).toHaveLength(2)
  901. expect(messages).toEqual([
  902. [{ type: 'text', text: 'outer message' }],
  903. [{ type: 'text', text: 'queued listener message' }],
  904. ])
  905. })
  906. it('preserves independent turn sources across an adjacent microtask send', async () => {
  907. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  908. const ctx = await harness(adapter)
  909. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  910. const idle = waitForIdle(ctx, agent)
  911. agent.send([{ type: 'text', text: 'user message' }])
  912. await Promise.resolve()
  913. agent.send(
  914. [{ type: 'text', text: 'plugin message' }],
  915. { source: { kind: 'plugin', plugin: 'test' } },
  916. )
  917. await idle
  918. const triggers = agent.session.events
  919. .filter(event => event.type === 'turn/start')
  920. .map(event => event.data.trigger)
  921. const sources = agent.session.events
  922. .filter(event => event.type === 'user/message')
  923. .map(event => event.data.source)
  924. expect(triggers).toEqual([
  925. { kind: 'message', source: { kind: 'user' } },
  926. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  927. ])
  928. expect(sources).toEqual([
  929. { kind: 'user' },
  930. { kind: 'plugin', plugin: 'test' },
  931. ])
  932. })
  933. it('keeps a session-listener send after dequeue in the following turn', async () => {
  934. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  935. const ctx = await harness(adapter)
  936. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  937. const turns: number[] = []
  938. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  939. // queue two messages while idle — first starts turn 1 immediately;
  940. // queue the second during turn 1 when the first assistant chunk streams
  941. let queued = false
  942. ctx.on('session/event', (_s, event) => {
  943. if (event.type === 'assistant/chunk' && !queued) {
  944. queued = true
  945. send(agent, 'second message')
  946. }
  947. })
  948. send(agent, 'first message')
  949. await waitForIdle(ctx, agent)
  950. expect(turns).toEqual([1, 2])
  951. expect(adapter.requests).toHaveLength(2)
  952. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  953. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  954. })
  955. it('keeps a model-adapter callback send in the following turn', async () => {
  956. const agentRef: { current?: Agent } = {}
  957. const adapter = new MockAdapter([
  958. () => {
  959. const agent = agentRef.current
  960. if (agent === undefined) throw new Error('model callback ran before agent setup')
  961. send(agent, 'model callback message')
  962. return textResponse('first')
  963. },
  964. textResponse('second'),
  965. ])
  966. const ctx = await harness(adapter)
  967. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  968. agentRef.current = agent
  969. const idle = waitForIdle(ctx, agent)
  970. send(agent, 'outer message')
  971. await idle
  972. const messages = agent.session.events
  973. .filter(event => event.type === 'user/message')
  974. .map(event => event.data.content)
  975. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  976. expect(messages).toEqual([
  977. [{ type: 'text', text: 'outer message' }],
  978. [{ type: 'text', text: 'model callback message' }],
  979. ])
  980. })
  981. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  982. const adapter = new MockAdapter([textResponse('ok')])
  983. const ctx = await harness(adapter)
  984. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  985. let flushed = 0
  986. let flushedBeforeIdle = false
  987. ctx.on('session/flush', async (session) => {
  988. await new Promise(r => setTimeout(r, 10))
  989. flushed++
  990. flushedBeforeIdle = agent.status !== 'idle'
  991. void session
  992. })
  993. send(agent, 'hi')
  994. await waitForIdle(ctx, agent)
  995. expect(flushed).toBe(1)
  996. expect(flushedBeforeIdle).toBe(true)
  997. })
  998. it('errors from the model surface as agent/error and end the turn', async () => {
  999. const adapter = new MockAdapter([]) // script exhausted → throws
  1000. const ctx = await harness(adapter)
  1001. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1002. const errors: Error[] = []
  1003. const reasons: TurnEndReason[] = []
  1004. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  1005. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1006. send(agent, 'hi')
  1007. await waitForIdle(ctx, agent)
  1008. expect(errors).toHaveLength(1)
  1009. expect(errors[0]!.message).toContain('script exhausted')
  1010. expect(reasons[0]).toMatchObject({ kind: 'error' })
  1011. // The durable failure lives entirely on turn/end.reason (with the failing
  1012. // step), not a standalone error event.
  1013. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  1014. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  1015. })
  1016. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  1017. const adapter = new MockAdapter(['hang'])
  1018. const ctx = await harness(adapter)
  1019. let agent!: Agent
  1020. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1021. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1022. }, { inject: ['agentLoop'] }))
  1023. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1024. send(agent, 'go')
  1025. await new Promise(r => setTimeout(r, 30))
  1026. expect(agent.status).toBe('running')
  1027. await fiber.dispose()
  1028. await driverDone(agent)
  1029. expect(agent.status).toBe('disposed')
  1030. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1031. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  1032. })
  1033. it('creates agents from config on startup', async () => {
  1034. const adapter = new MockAdapter([textResponse('from config')])
  1035. const ctx = new Context()
  1036. await ctx.plugin(LlmService)
  1037. await ctx.plugin(SessionStore)
  1038. await ctx.plugin(SystemPrompt)
  1039. await ctx.plugin(ToolRegistry)
  1040. await ctx.plugin(AgentRegistry)
  1041. await ctx.plugin(AgentLoop, {
  1042. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  1043. })
  1044. ctx.llm.registerAdapter(['mock'], adapter)
  1045. const agent = ctx.agents.list()[0]!
  1046. expect(agent).toBeDefined()
  1047. expect(agent.id).toBe(agent.session.id)
  1048. expect(agent.id).toMatch(/^config-agent-session-/)
  1049. expect(agent.options.model).toBe('mock')
  1050. // the agent is alive: send triggers a turn
  1051. send(agent, 'hi')
  1052. await waitForIdle(ctx, agent)
  1053. expect(adapter.requests).toHaveLength(1)
  1054. })
  1055. it('attaches config agent cwd to the fresh session header', async () => {
  1056. const ctx = new Context()
  1057. await ctx.plugin(LlmService)
  1058. await ctx.plugin(SessionStore)
  1059. await ctx.plugin(SystemPrompt)
  1060. await ctx.plugin(ToolRegistry)
  1061. await ctx.plugin(AgentRegistry)
  1062. await ctx.plugin(AgentLoop, {
  1063. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1064. })
  1065. const agent = ctx.agents.list()[0]!
  1066. expect(agent.session.header.cwd).toBe('/work/project')
  1067. })
  1068. it('replays a session log into an identical derived history', async () => {
  1069. const adapter = new MockAdapter([
  1070. toolCallResponse('c1', 'echo', { text: 'x' }),
  1071. textResponse('done'),
  1072. ])
  1073. const ctx = await harness(adapter)
  1074. ctx.tools.register(defineTool({
  1075. name: 'echo',
  1076. description: '',
  1077. parameters: { text: { type: 'string' } },
  1078. async execute(args) {
  1079. return [{ type: 'text', text: String(args.text) }]
  1080. },
  1081. }))
  1082. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1083. send(agent, 'run')
  1084. await waitForIdle(ctx, agent)
  1085. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1086. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1087. // event-by-event identity of types
  1088. expect(replayed.events.map(e => e.type)).toEqual(
  1089. agent.session.events.map(e => e.type))
  1090. })
  1091. })