1
0

loop.spec.ts 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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, type JsonValue } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineContentToolFixture, 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.followup([{ 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(defineContentToolFixture({
  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. const durableResult = agent.session.events.find(event => event.type === 'tool/result')
  106. expect(durableResult?.type === 'tool/result' && 'value' in durableResult.data).toBe(false)
  107. })
  108. it('persists presentation metadata projected from the canonical value', async () => {
  109. const adapter = new MockAdapter([
  110. toolCallResponse('c1', 'writer', { path: 'a.txt' }, 'writing'),
  111. textResponse('done'),
  112. ])
  113. const ctx = await harness(adapter)
  114. ctx.tools.register(defineTool({
  115. name: 'writer',
  116. description: 'writes a file',
  117. parameters: { path: { type: 'string' } },
  118. output: {
  119. schema: { type: 'string' },
  120. render: () => [{ type: 'text', text: 'ok' }],
  121. presentationMeta: (_args, value) => ({ diffs: [{ path: value, oldText: null, newText: 'x' }] }),
  122. },
  123. async execute() {
  124. return 'a.txt'
  125. },
  126. }))
  127. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  128. send(agent, 'use the tool')
  129. await waitForIdle(ctx, agent)
  130. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  131. expect(toolResult?.type === 'tool/result' && toolResult.data.meta)
  132. .toEqual({ diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] })
  133. })
  134. it('renders harness identity, then the persona, then tool guidance — with {{variables}} resolved', async () => {
  135. const adapter = new MockAdapter([textResponse('ok')])
  136. // The persona is a TEMPLATE: {{model}} is the loop-registered variable
  137. // projecting this agent's configured model, so the model knows its own name.
  138. const ctx = await harness(adapter, 'You are a test agent on {{model}}.')
  139. ctx.systemPrompt.section({ name: 'tool:noop', order: 100, text: 'Use the noop tool wisely.' })
  140. ctx.tools.register(defineContentToolFixture({
  141. name: 'noop',
  142. description: 'does nothing',
  143. parameters: {},
  144. async execute() {
  145. return []
  146. },
  147. }))
  148. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  149. send(agent, 'hi')
  150. await waitForIdle(ctx, agent)
  151. const request = adapter.requests[0]
  152. 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.')
  153. expect(request!.tools?.map(t => t.name)).toEqual(['noop'])
  154. })
  155. it('resolves {{cwd}} from the agent session workspace (factory create with meta.cwd)', async () => {
  156. const adapter = new MockAdapter([textResponse('ok')])
  157. const ctx = await harness(adapter, 'Working in {{cwd}}.')
  158. const handle = await ctx.agents.create({
  159. sessionId: SessionId('s-cwd'),
  160. meta: { cwd: '/work/space' },
  161. agentOptions: { provider: 'mock', model: 'mock' },
  162. })
  163. const agent = handle.agent
  164. send(agent, 'hi')
  165. await waitForIdle(ctx, agent)
  166. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nWorking in /work/space.')
  167. })
  168. it('contains a strict-variable render failure: the turn errors, the loop keeps serving turns', async () => {
  169. // A missing cwd variable must fail one turn without preventing a later valid turn.
  170. const adapter = new MockAdapter([textResponse('ok after rescue')])
  171. const ctx = await harness(adapter, 'In {{cwd}}.')
  172. const errors: Error[] = []
  173. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  174. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  175. send(agent, 'hi')
  176. await waitForIdle(ctx, agent)
  177. expect(adapter.requests).toHaveLength(0) // the request was never sent
  178. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  179. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  180. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  181. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  182. // agent completes a real model turn.
  183. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  184. assembly.variables['cwd'] = '/rescued'
  185. return next()
  186. })
  187. send(agent, 'again')
  188. await waitForIdle(ctx, agent)
  189. expect(adapter.requests).toHaveLength(1)
  190. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  191. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  192. expect(turnEnds).toHaveLength(2)
  193. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  194. })
  195. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  196. // AgentOptions.model unset: the model arrives in the agent/request
  197. // waterfall (the loop's documented fallback — see runStep's no-model
  198. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  199. // states the fact early on system-prompt/assemble — the owner of a
  200. // late-bound fact owns stating it wherever it is claimed.
  201. const adapter = new MockAdapter([textResponse('ok')])
  202. const ctx = await harness(adapter, 'You run on {{model}}.')
  203. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  204. assembly.variables['provider'] = 'mock'
  205. assembly.variables['model'] = 'mock'
  206. return next()
  207. })
  208. ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => {
  209. return { ...config, provider: 'mock', model: 'mock' }
  210. })
  211. const agent = ctx.agentLoop.create(SessionId('a-late-model'), {})
  212. send(agent, 'hi')
  213. await waitForIdle(ctx, agent)
  214. expect(adapter.requests).toHaveLength(1)
  215. expect(adapter.requests[0]!.model).toBe('mock')
  216. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  217. })
  218. it.each([
  219. ['BigInt', { n: 1n }],
  220. ['Map', new Map([['key', 'value']])],
  221. ['class instance', new (class ResultMeta { x = 1 })()],
  222. ])('rejects non-JSON presentation metadata (%s) before the durable result commit', async (_kind, meta) => {
  223. const adapter = new MockAdapter([
  224. toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'),
  225. textResponse('recovered'),
  226. ])
  227. const ctx = await harness(adapter)
  228. ctx.tools.register(defineTool({
  229. name: 'bad-meta',
  230. description: 'returns invalid durable metadata',
  231. parameters: {},
  232. output: {
  233. schema: { type: 'string' },
  234. render: (_args, value) => [{ type: 'text', text: value }],
  235. presentationMeta: () => meta as unknown as JsonValue,
  236. },
  237. execute: () => Promise.resolve('apparent success'),
  238. }))
  239. const agent = ctx.agentLoop.create(SessionId('bad-meta-agent'), { provider: 'mock', model: 'mock' })
  240. send(agent, 'use the tool')
  241. await waitForIdle(ctx, agent)
  242. const result = agent.session.events.find(event => event.type === 'tool/result')
  243. expect(result?.type).toBe('tool/result')
  244. if (result?.type === 'tool/result') {
  245. expect(result.data.callId).toBe('bad-meta-call')
  246. expect(result.data.isError).toBe(true)
  247. expect(result.data.meta).toBeUndefined()
  248. expect(result.data.error).toEqual({ name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' })
  249. expect(result.data.content).toEqual([{
  250. type: 'text',
  251. text: 'Error: tool "bad-meta" returned invalid output: output.presentationMeta returned non-lossless JSON',
  252. }])
  253. }
  254. // The normalized failure was durably logged and fed back to the model; the
  255. // turn continued normally instead of failing after an apparent success.
  256. expect(adapter.requests).toHaveLength(2)
  257. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('output.presentationMeta returned non-lossless JSON')
  258. })
  259. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  260. // The documented escape valve: a deployment that must drop the harness
  261. // openers short-circuits the assemble waterfall; the request then carries
  262. // NO system field at all (not an empty string).
  263. const adapter = new MockAdapter([textResponse('ok')])
  264. const ctx = await harness(adapter)
  265. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  266. const agent = ctx.agentLoop.create(SessionId('a-no-system'), { provider: 'mock', model: 'mock' })
  267. send(agent, 'hi')
  268. await waitForIdle(ctx, agent)
  269. expect(adapter.requests).toHaveLength(1)
  270. expect('system' in adapter.requests[0]!).toBe(false)
  271. })
  272. it('records raw chunks for replay as assistant/chunk session events', async () => {
  273. const adapter = new MockAdapter([textResponse('abc')])
  274. const ctx = await harness(adapter)
  275. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  276. send(agent, 'hi')
  277. await waitForIdle(ctx, agent)
  278. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  279. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  280. expect(chunkEvents).toHaveLength(7)
  281. // replay: chunk events alone re-assemble to the recorded assistant message
  282. const deltaText = chunkEvents
  283. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  284. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  285. .map(c => c.text)
  286. .join('')
  287. expect(deltaText).toBe('abc')
  288. })
  289. it('injects steering between steps and continues the turn', async () => {
  290. const adapter = new MockAdapter([
  291. toolCallResponse('c1', 'slow', {}),
  292. textResponse('addressed the steering'),
  293. ])
  294. const ctx = await harness(adapter)
  295. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  296. ctx.tools.register(defineContentToolFixture({
  297. name: 'slow',
  298. description: '',
  299. parameters: {},
  300. async execute() {
  301. // steer while the turn is running (during tool execution)
  302. agent.steer([{ type: 'text', text: 'change of plans' }])
  303. return [{ type: 'text', text: 'tool done' }]
  304. },
  305. }))
  306. send(agent, 'start')
  307. await waitForIdle(ctx, agent)
  308. const types = agent.session.events.map(e => e.type)
  309. expect(types).toContain('steering/message')
  310. // steering recorded before the second step's request derived its history
  311. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  312. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  313. expect(secondStepStart).toBeDefined()
  314. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  315. // the second model request saw the steering content
  316. const secondRequest = adapter.requests[1]
  317. const flat = JSON.stringify(secondRequest!.messages)
  318. expect(flat).toContain('change of plans')
  319. })
  320. it('same-tick idle steering inherits one-send-one-turn FIFO behavior', async () => {
  321. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  322. const ctx = await harness(adapter)
  323. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  324. const idle = waitForIdle(ctx, agent)
  325. agent.steer([{ type: 'text', text: 'first idle steer' }])
  326. agent.steer([{ type: 'text', text: 'second idle steer' }])
  327. await idle
  328. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  329. expect(agent.session.events
  330. .filter(event => event.type === 'user/message')
  331. .map(event => event.data.content)).toEqual([
  332. [{ type: 'text', text: 'first idle steer' }],
  333. [{ type: 'text', text: 'second idle steer' }],
  334. ])
  335. expect(adapter.requests).toHaveLength(2)
  336. })
  337. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  338. const adapter = new MockAdapter([textResponse('ok')])
  339. const ctx = await harness(adapter)
  340. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  341. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  342. // The idle inject records a self-contained turn (turn/start → user/message
  343. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  344. await new Promise(r => setTimeout(r, 20))
  345. expect(agent.status).toBe('idle')
  346. expect(adapter.requests).toHaveLength(0)
  347. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  348. expect(injectedTurn).toHaveLength(1)
  349. const it0 = injectedTurn[0]!
  350. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  351. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  352. send(agent, 'go')
  353. await waitForIdle(ctx, agent)
  354. const flat = JSON.stringify(adapter.requests[0]!.messages)
  355. expect(flat).toContain('file changed: a.ts')
  356. expect(flat).not.toContain('<context source=')
  357. })
  358. it('inject() persists structured context content verbatim with durable hidden meta', async () => {
  359. const adapter = new MockAdapter([textResponse('ok')])
  360. const ctx = await harness(adapter)
  361. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  362. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  363. const meta = {
  364. kind: 'workspace-instructions',
  365. version: 1,
  366. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  367. }
  368. agent.inject([{ type: 'text', text }], {
  369. source: { kind: 'plugin', plugin: 'workspace-context' },
  370. meta,
  371. })
  372. send(agent, 'go')
  373. await waitForIdle(ctx, agent)
  374. const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  375. expect(contextEvent?.type === 'user/message' && contextEvent.data).toMatchObject({ meta })
  376. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  377. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  378. expect(requestText).not.toContain('<context source=')
  379. })
  380. it('defers inject() during tool execution until after the tool result', async () => {
  381. const adapter = new MockAdapter([
  382. toolCallResponse('c1', 'noticer', {}, 'calling'),
  383. textResponse('done'),
  384. ])
  385. const ctx = await harness(adapter)
  386. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  387. let visibleDuringTool = false
  388. const meta = { kind: 'deferred-test', version: 1 }
  389. ctx.tools.register(defineContentToolFixture({
  390. name: 'noticer',
  391. description: 'injects a notice',
  392. parameters: {},
  393. async execute() {
  394. await Promise.resolve()
  395. const first = { type: 'text' as const, text: 'mid-turn notice' }
  396. agent.inject([first], {
  397. source: { kind: 'plugin', plugin: 'x' },
  398. meta,
  399. })
  400. first.text = 'mutated after inject'
  401. agent.inject([{ type: 'text', text: 'second notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  402. visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  403. return [{ type: 'text', text: 'ok' }]
  404. },
  405. }))
  406. send(agent, 'go')
  407. await waitForIdle(ctx, agent)
  408. expect(visibleDuringTool).toBe(false)
  409. // The injection stays in the open turn, but its user-role context cannot
  410. // split the assistant tool call from the provider's tool-result message.
  411. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  412. expect(turnStarts).toHaveLength(1)
  413. const ts0 = turnStarts[0]!
  414. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  415. const result = agent.session.events.find(e => e.type === 'tool/result')!
  416. const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  417. expect(contexts).toHaveLength(2)
  418. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  419. expect(contexts[0]?.type === 'user/message' && contexts[0].data).toMatchObject({
  420. meta,
  421. })
  422. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  423. .toEqual([
  424. { type: 'text', text: 'mid-turn notice' },
  425. { type: 'text', text: 'second notice' },
  426. ])
  427. const secondRequest = adapter.requests[1]!.messages
  428. const resultIndex = secondRequest.findIndex(message =>
  429. message.content.some(block => block.type === 'tool-result'))
  430. const contextIndexes = secondRequest.flatMap((message, index) =>
  431. message.content.some(block => block.type === 'text'
  432. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  433. ? [index]
  434. : [])
  435. expect(resultIndex).toBeGreaterThanOrEqual(0)
  436. expect(contextIndexes).toHaveLength(2)
  437. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  438. })
  439. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  440. const adapter = new MockAdapter([
  441. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  442. textResponse('done'),
  443. ])
  444. const ctx = await harness(adapter)
  445. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  446. ctx.tools.register(defineContentToolFixture({
  447. name: 'invalid-injector',
  448. description: 'attempts an invalid context injection',
  449. parameters: {},
  450. async execute() {
  451. expect(() => {
  452. agent.inject([{ type: 'text', text: 'invalid' }], {
  453. source: { kind: 'plugin', plugin: 'test' },
  454. meta: { bigint: 1n } as never,
  455. })
  456. }).toThrow('agent context must be losslessly JSON-serializable')
  457. return [{ type: 'text', text: 'rejected invalid context' }]
  458. },
  459. }))
  460. send(agent, 'go')
  461. await waitForIdle(ctx, agent)
  462. expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  463. })
  464. it('preserves SendOptions.meta on the durable user/message and steering/message', async () => {
  465. const adapter = new MockAdapter([toolCallResponse('c1', 'noop', {}), textResponse('done')])
  466. const ctx = await harness(adapter)
  467. ctx.tools.register(defineContentToolFixture({
  468. name: 'noop', description: '', parameters: {},
  469. async execute() {
  470. // Running steer carries its own meta onto the durable steering/message.
  471. agent.steer([{ type: 'text', text: 's' }], { source: { kind: 'plugin', plugin: 'p' }, meta: { steer: 1 } })
  472. return []
  473. },
  474. }))
  475. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  476. agent.followup([{ type: 'text', text: 'go' }], { meta: { prompt: 1 } })
  477. await waitForIdle(ctx, agent)
  478. const user = agent.session.events.find(e => e.type === 'user/message')
  479. expect(user?.type === 'user/message' && user.data.meta).toEqual({ prompt: 1 })
  480. const steering = agent.session.events.find(e => e.type === 'steering/message')
  481. expect(steering?.type === 'steering/message' && steering.data.meta).toEqual({ steer: 1 })
  482. })
  483. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  484. // force-continue: model never calls tools, but a plugin forces 3 steps
  485. const adapter = new MockAdapter([
  486. textResponse('step 1'),
  487. textResponse('step 2'),
  488. textResponse('step 3'),
  489. ])
  490. const ctx = await harness(adapter)
  491. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  492. let steps = 0
  493. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  494. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => {
  495. if (steps < 3) return { action: 'continue' as const }
  496. return next()
  497. })
  498. send(agent, 'go')
  499. await waitForIdle(ctx, agent)
  500. expect(steps).toBe(3)
  501. expect(adapter.requests).toHaveLength(3)
  502. })
  503. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  504. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  505. const ctx = await harness(adapter)
  506. ctx.tools.register(defineContentToolFixture({
  507. name: 'echo',
  508. description: '',
  509. parameters: { text: { type: 'string' } },
  510. async execute(args) {
  511. return [{ type: 'text', text: String(args.text) }]
  512. },
  513. }))
  514. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  515. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  516. send(agent, 'go')
  517. await waitForIdle(ctx, agent)
  518. // only one model call despite the tool call requesting a follow-up
  519. expect(adapter.requests).toHaveLength(1)
  520. // tool still executed before the decision
  521. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  522. })
  523. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  524. const adapter = new MockAdapter([textResponse('ok')])
  525. const ctx = await harness(adapter)
  526. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  527. ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => {
  528. // The seed is frozen — config is not a mutable per-call knob; a switch
  529. // is proposed by returning a replacement, and the loop logs it.
  530. expect(Object.isFrozen(config)).toBe(true)
  531. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  532. return { ...config, model: 'other-model' }
  533. })
  534. send(agent, 'hi')
  535. await waitForIdle(ctx, agent)
  536. expect(adapter.requests[0]!.model).toBe('other-model')
  537. // The header event records what the request ACTUALLY used — the switch is
  538. // a reconstructable fact, not silent drift.
  539. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  540. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  541. })
  542. it('agent/pre-step fires once per step before the step is opened', async () => {
  543. const adapter = new MockAdapter([
  544. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  545. textResponse('done'),
  546. ])
  547. const ctx = await harness(adapter)
  548. ctx.tools.register(defineContentToolFixture({
  549. name: 'echo', description: 'echo', parameters: {},
  550. async execute() { return [{ type: 'text', text: 'echoed' }] },
  551. }))
  552. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  553. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  554. ctx.on('agent/pre-step', (subject, turn, step, signal) => {
  555. if (subject === agent) fires.push({ turn, step, signal })
  556. })
  557. send(agent, 'go')
  558. await waitForIdle(ctx, agent)
  559. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  560. { turn: 1, step: 1 },
  561. { turn: 1, step: 2 },
  562. ])
  563. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  564. })
  565. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  566. // The append lands before step/start, yet derive happens afterwards and the
  567. // same step's request must include it.
  568. const adapter = new MockAdapter([textResponse('ok')])
  569. const ctx = await harness(adapter)
  570. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  571. let injected = false
  572. ctx.on('agent/pre-step', (subject) => {
  573. if (subject === agent && !injected) {
  574. injected = true
  575. subject.session.append('user/message', {
  576. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  577. source: { kind: 'plugin', plugin: 'test' },
  578. }, { surfaceOp: 'append' })
  579. }
  580. })
  581. send(agent, 'go')
  582. await waitForIdle(ctx, agent)
  583. // The adapter's request includes the node injected during pre-step (derive
  584. // reflects it).
  585. const text = JSON.stringify(adapter.requests[0]!.messages)
  586. expect(text).toContain('INJECTED-IN-PRE-STEP')
  587. // And the injected event sits BEFORE the first step/start in the log —
  588. // the seam fired outside the step.
  589. const events = agent.session.events
  590. const injectedSeq = events.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')!.seq
  591. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  592. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  593. })
  594. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  595. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  596. // closing, the turn records error, and the loop remains available.
  597. const adapter = new MockAdapter([textResponse('second turn ok')])
  598. const ctx = await harness(adapter)
  599. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  600. let throwOnce = true
  601. ctx.on('agent/pre-step', () => {
  602. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  603. })
  604. const errors: Error[] = []
  605. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  606. send(agent, 'first')
  607. await waitForIdle(ctx, agent)
  608. // The first turn failed at step 1 (no model call happened), surfaced via
  609. // agent/error, with the durable failure on turn/end.reason.
  610. expect(errors).toHaveLength(1)
  611. expect(errors[0]!.message).toContain('boom in pre-step')
  612. expect(adapter.requests.length).toBe(0)
  613. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  614. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  615. // The step opened-and-closed count stays balanced even though it never ran.
  616. const types = agent.session.events.map(e => e.type)
  617. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  618. // The loop survived: a second prompt runs a normal completed turn.
  619. send(agent, 'second')
  620. await waitForIdle(ctx, agent)
  621. expect(adapter.requests.length).toBe(1)
  622. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  623. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  624. })
  625. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  626. const adapter = new MockAdapter(['hang'])
  627. const ctx = await harness(adapter)
  628. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  629. const reasons: TurnEndReason[] = []
  630. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  631. send(agent, 'go')
  632. // wait until the stream is hanging, then cancel
  633. await new Promise(r => setTimeout(r, 30))
  634. expect(agent.status).toBe('running')
  635. agent.cancel({ kind: 'user' })
  636. await waitForIdle(ctx, agent)
  637. expect(reasons).toEqual([{ kind: 'aborted' }])
  638. })
  639. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  640. // A single step that ends with a max-tokens finish (no tool calls): the
  641. // turn stops by default and ends max-tokens, not completed.
  642. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  643. const ctx = await harness(adapter)
  644. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  645. const reasons: TurnEndReason[] = []
  646. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  647. send(agent, 'go')
  648. await waitForIdle(ctx, agent)
  649. expect(adapter.requests).toHaveLength(1)
  650. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  651. // Assert the durable row, not only the live listener.
  652. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  653. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  654. })
  655. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  656. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  657. // must be FORCED to reach step 2 which finishes normally (stop).
  658. const adapter = new MockAdapter([
  659. maxTokensResponse('first half'),
  660. textResponse('second half'),
  661. ])
  662. const ctx = await harness(adapter)
  663. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  664. let steps = 0
  665. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  666. // Force exactly one continuation (step 1 → step 2), then defer to default
  667. // (step 2 is a plain stop with no tool calls → stops).
  668. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => {
  669. if (steps < 2) return { action: 'continue' as const }
  670. return next()
  671. })
  672. const reasons: TurnEndReason[] = []
  673. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  674. send(agent, 'go')
  675. await waitForIdle(ctx, agent)
  676. expect(steps).toBe(2)
  677. expect(adapter.requests).toHaveLength(2)
  678. expect(adapter.requests[1]!.messages).toEqual([
  679. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  680. { role: 'assistant', content: [{ type: 'text', text: 'first half' }], provenance: { provider: 'mock', model: 'mock' } },
  681. ])
  682. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  683. })
  684. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  685. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  686. // stop. The per-turn reason must be independent — turn 2 ends completed.
  687. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  688. const ctx = await harness(adapter)
  689. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  690. const reasons: TurnEndReason[] = []
  691. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  692. send(agent, 'first')
  693. await waitForIdle(ctx, agent)
  694. send(agent, 'second')
  695. await waitForIdle(ctx, agent)
  696. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  697. })
  698. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  699. const callId = CallId('c1')
  700. const adapter = new MockAdapter([[
  701. { type: 'block-start', index: 0, blockType: 'tool-call' },
  702. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  703. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  704. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  705. { type: 'finish', reason: { kind: 'max-tokens' } },
  706. ]])
  707. const ctx = await harness(adapter)
  708. let executions = 0
  709. ctx.tools.register(defineContentToolFixture({
  710. name: 'echo',
  711. description: '',
  712. parameters: { text: { type: 'string' } },
  713. async execute() {
  714. executions += 1
  715. return [{ type: 'text', text: 'should not run' }]
  716. },
  717. }))
  718. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  719. const reasons: TurnEndReason[] = []
  720. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  721. send(agent, 'go')
  722. await waitForIdle(ctx, agent)
  723. expect(executions).toBe(0)
  724. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  725. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  726. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  727. // Empty content still needs an assistant/message to carry usage; derivation
  728. // skips that host so it does not create a spurious assistant turn.
  729. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  730. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  731. turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' }, usage: { inputTokens: 10, outputTokens: 5 },
  732. })
  733. })
  734. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  735. // The truncated tool call is dropped from durable content, while the
  736. // successful provider call still needs an exact replay anchor.
  737. const callId = CallId('c1')
  738. const adapter = new MockAdapter([[
  739. { type: 'block-start', index: 0, blockType: 'tool-call' },
  740. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  741. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  742. { type: 'finish', reason: { kind: 'max-tokens' } },
  743. ]])
  744. const ctx = await harness(adapter)
  745. ctx.tools.register(defineContentToolFixture({
  746. name: 'echo',
  747. description: '',
  748. parameters: { text: { type: 'string' } },
  749. async execute() { return [{ type: 'text', text: 'should not run' }] },
  750. }))
  751. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  752. const reasons: TurnEndReason[] = []
  753. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  754. send(agent, 'go')
  755. await waitForIdle(ctx, agent)
  756. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  757. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  758. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  759. turn: 1,
  760. step: 1,
  761. content: [],
  762. provenance: { provider: 'mock', model: 'mock' },
  763. })
  764. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  765. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  766. })
  767. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  768. // A clean content-less call stays absent from derived messages but remains
  769. // a durable successful-call boundary for replay consumers.
  770. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  771. const ctx = await harness(adapter)
  772. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  773. const reasons: TurnEndReason[] = []
  774. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  775. send(agent, 'go')
  776. await waitForIdle(ctx, agent)
  777. expect(reasons).toEqual([{ kind: 'completed' }])
  778. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  779. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  780. turn: 1,
  781. step: 1,
  782. content: [],
  783. provenance: { provider: 'mock', model: 'mock' },
  784. })
  785. expect(assistant.sourceEventSeqs?.length).toBe(1)
  786. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  787. })
  788. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  789. const callId = CallId('c1')
  790. const adapter = new MockAdapter([[
  791. { type: 'block-start', index: 0, blockType: 'text' },
  792. { type: 'text-delta', index: 0, text: 'partial text' },
  793. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  794. { type: 'block-start', index: 1, blockType: 'tool-call' },
  795. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  796. { type: 'finish', reason: { kind: 'max-tokens' } },
  797. ]])
  798. const ctx = await harness(adapter)
  799. let stepResults = 0
  800. ctx.on('agent/step-result', async (_agent, _turn, _step, message, _signal, next) => {
  801. stepResults += 1
  802. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  803. return next()
  804. })
  805. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  806. send(agent, 'go')
  807. await waitForIdle(ctx, agent)
  808. expect(stepResults).toBe(1)
  809. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  810. expect(agent.session.deriveMessages()).toEqual([
  811. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  812. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }], provenance: { provider: 'mock', model: 'mock' } },
  813. ])
  814. })
  815. it('contains a step/end observer failure without changing continuation', async () => {
  816. const adapter = new MockAdapter([
  817. toolCallResponse('c1', 'echo', { text: 'x' }),
  818. textResponse('continued after tool call'),
  819. ])
  820. const ctx = await harness(adapter)
  821. ctx.tools.register(defineContentToolFixture({
  822. name: 'echo',
  823. description: '',
  824. parameters: { text: { type: 'string' } },
  825. async execute(args) {
  826. return [{ type: 'text', text: String(args.text) }]
  827. },
  828. }))
  829. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  830. let threw = false
  831. // Post-commit session observers cannot control the loop. The tool call still
  832. // drives the second model request, and the turn completes normally.
  833. ctx.on('session/event', (_session, event) => {
  834. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  835. })
  836. send(agent, 'go')
  837. await waitForIdle(ctx, agent)
  838. expect(adapter.requests).toHaveLength(2)
  839. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  840. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  841. })
  842. it('keeps same-tick sends in separate turns and checkpoints before the next starts', async () => {
  843. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer')])
  844. const ctx = await harness(adapter)
  845. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  846. const firstFlush = Promise.withResolvers<undefined>()
  847. const releaseFirstFlush = Promise.withResolvers<undefined>()
  848. let flushes = 0
  849. ctx.on('session/flush', async (session) => {
  850. if (session !== agent.session) return
  851. flushes += 1
  852. if (flushes === 1) {
  853. firstFlush.resolve(undefined)
  854. await releaseFirstFlush.promise
  855. }
  856. })
  857. const turns: number[] = []
  858. ctx.on('session/event', (session, event) => {
  859. if (session === agent.session && event.type === 'turn/start') turns.push(event.data.turn)
  860. })
  861. const idle = waitForIdle(ctx, agent)
  862. send(agent, 'first message')
  863. send(agent, 'second message')
  864. await firstFlush.promise
  865. expect(turns).toEqual([1])
  866. expect(adapter.requests).toHaveLength(1)
  867. releaseFirstFlush.resolve(undefined)
  868. await idle
  869. expect(turns).toEqual([1, 2])
  870. expect(flushes).toBe(2)
  871. expect(adapter.requests).toHaveLength(2)
  872. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first answer')
  873. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  874. })
  875. it('holds a turn-end listener send behind the closing turn checkpoint', async () => {
  876. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer')])
  877. const ctx = await harness(adapter)
  878. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  879. const firstFlush = Promise.withResolvers<undefined>()
  880. const releaseFirstFlush = Promise.withResolvers<undefined>()
  881. let flushes = 0
  882. ctx.on('session/flush', async (session) => {
  883. if (session !== agent.session) return
  884. flushes += 1
  885. if (flushes === 1) {
  886. firstFlush.resolve(undefined)
  887. await releaseFirstFlush.promise
  888. }
  889. })
  890. const turns: number[] = []
  891. const statuses: string[] = []
  892. ctx.on('agent/status', (subject, status) => {
  893. if (subject === agent) statuses.push(status)
  894. })
  895. ctx.on('session/event', (session, event) => {
  896. if (session !== agent.session) return
  897. if (event.type === 'turn/start') turns.push(event.data.turn)
  898. if (event.type === 'turn/end' && event.data.turn === 1) send(agent, 'turn-end listener message')
  899. })
  900. const idle = waitForIdle(ctx, agent)
  901. send(agent, 'first message')
  902. await firstFlush.promise
  903. expect(turns).toEqual([1])
  904. expect(adapter.requests).toHaveLength(1)
  905. releaseFirstFlush.resolve(undefined)
  906. await idle
  907. expect(turns).toEqual([1, 2])
  908. expect(statuses).toEqual(['running', 'idle'])
  909. expect(adapter.requests).toHaveLength(2)
  910. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first answer')
  911. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('turn-end listener message')
  912. })
  913. it('keeps a reentrant agent/inbox/enqueue send as the next independent turn', async () => {
  914. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  915. const ctx = await harness(adapter)
  916. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  917. let nested = false
  918. ctx.on('agent/inbox/enqueue', (subject) => {
  919. if (subject !== agent || nested) return
  920. nested = true
  921. send(agent, 'queued listener message')
  922. })
  923. const idle = waitForIdle(ctx, agent)
  924. send(agent, 'outer message')
  925. await idle
  926. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  927. const messages = agent.session.events
  928. .filter(event => event.type === 'user/message')
  929. .map(event => event.data.content)
  930. expect(turns).toHaveLength(2)
  931. expect(messages).toEqual([
  932. [{ type: 'text', text: 'outer message' }],
  933. [{ type: 'text', text: 'queued listener message' }],
  934. ])
  935. })
  936. it('preserves independent turn sources across an adjacent microtask send', async () => {
  937. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  938. const ctx = await harness(adapter)
  939. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  940. const idle = waitForIdle(ctx, agent)
  941. agent.followup([{ type: 'text', text: 'user message' }])
  942. await Promise.resolve()
  943. agent.followup(
  944. [{ type: 'text', text: 'plugin message' }],
  945. { source: { kind: 'plugin', plugin: 'test' } },
  946. )
  947. await idle
  948. const triggers = agent.session.events
  949. .filter(event => event.type === 'turn/start')
  950. .map(event => event.data.trigger)
  951. const sources = agent.session.events
  952. .filter(event => event.type === 'user/message')
  953. .map(event => event.data.source)
  954. expect(triggers).toEqual([
  955. { kind: 'message', source: { kind: 'user' } },
  956. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  957. ])
  958. expect(sources).toEqual([
  959. { kind: 'user' },
  960. { kind: 'plugin', plugin: 'test' },
  961. ])
  962. })
  963. it('keeps a session-listener send after dequeue in the following turn', async () => {
  964. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  965. const ctx = await harness(adapter)
  966. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  967. const turns: number[] = []
  968. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  969. // queue two messages while idle — first starts turn 1 immediately;
  970. // queue the second during turn 1 when the first assistant chunk streams
  971. let queued = false
  972. ctx.on('session/event', (_s, event) => {
  973. if (event.type === 'assistant/chunk' && !queued) {
  974. queued = true
  975. send(agent, 'second message')
  976. }
  977. })
  978. send(agent, 'first message')
  979. await waitForIdle(ctx, agent)
  980. expect(turns).toEqual([1, 2])
  981. expect(adapter.requests).toHaveLength(2)
  982. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  983. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  984. })
  985. it('keeps a model-adapter callback send in the following turn', async () => {
  986. const agentRef: { current?: Agent } = {}
  987. const adapter = new MockAdapter([
  988. () => {
  989. const agent = agentRef.current
  990. if (agent === undefined) throw new Error('model callback ran before agent setup')
  991. send(agent, 'model callback message')
  992. return textResponse('first')
  993. },
  994. textResponse('second'),
  995. ])
  996. const ctx = await harness(adapter)
  997. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  998. agentRef.current = agent
  999. const idle = waitForIdle(ctx, agent)
  1000. send(agent, 'outer message')
  1001. await idle
  1002. const messages = agent.session.events
  1003. .filter(event => event.type === 'user/message')
  1004. .map(event => event.data.content)
  1005. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  1006. expect(messages).toEqual([
  1007. [{ type: 'text', text: 'outer message' }],
  1008. [{ type: 'text', text: 'model callback message' }],
  1009. ])
  1010. })
  1011. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  1012. const adapter = new MockAdapter([textResponse('ok')])
  1013. const ctx = await harness(adapter)
  1014. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1015. let flushed = 0
  1016. let flushedBeforeIdle = false
  1017. ctx.on('session/flush', async (session) => {
  1018. await new Promise(r => setTimeout(r, 10))
  1019. flushed++
  1020. flushedBeforeIdle = agent.status !== 'idle'
  1021. void session
  1022. })
  1023. send(agent, 'hi')
  1024. await waitForIdle(ctx, agent)
  1025. expect(flushed).toBe(1)
  1026. expect(flushedBeforeIdle).toBe(true)
  1027. })
  1028. it('errors from the model surface as agent/error and end the turn', async () => {
  1029. const adapter = new MockAdapter([]) // script exhausted → throws
  1030. const ctx = await harness(adapter)
  1031. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1032. const errors: Error[] = []
  1033. const reasons: TurnEndReason[] = []
  1034. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  1035. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1036. send(agent, 'hi')
  1037. await waitForIdle(ctx, agent)
  1038. expect(errors).toHaveLength(1)
  1039. expect(errors[0]!.message).toContain('script exhausted')
  1040. expect(reasons[0]).toMatchObject({ kind: 'error' })
  1041. // The durable failure lives entirely on turn/end.reason (with the failing
  1042. // step), not a standalone error event.
  1043. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  1044. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  1045. })
  1046. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  1047. const adapter = new MockAdapter(['hang'])
  1048. const ctx = await harness(adapter)
  1049. let agent!: Agent
  1050. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1051. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1052. }, { inject: ['agentLoop'] }))
  1053. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1054. send(agent, 'go')
  1055. await new Promise(r => setTimeout(r, 30))
  1056. expect(agent.status).toBe('running')
  1057. await fiber.dispose()
  1058. await driverDone(agent)
  1059. expect(agent.status).toBe('disposed')
  1060. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1061. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  1062. })
  1063. it('creates agents from config on startup', async () => {
  1064. const adapter = new MockAdapter([textResponse('from config')])
  1065. const ctx = new Context()
  1066. await ctx.plugin(LlmService)
  1067. await ctx.plugin(SessionStore)
  1068. await ctx.plugin(SystemPrompt)
  1069. await ctx.plugin(ToolRegistry)
  1070. await ctx.plugin(AgentRegistry)
  1071. await ctx.plugin(AgentLoop, {
  1072. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  1073. })
  1074. ctx.llm.registerAdapter(['mock'], adapter)
  1075. const agent = ctx.agents.list()[0]!
  1076. expect(agent).toBeDefined()
  1077. expect(agent.id).toBe(agent.session.id)
  1078. expect(agent.id).toMatch(/^config-agent-session-/)
  1079. expect(agent.options.model).toBe('mock')
  1080. // the agent is alive: send triggers a turn
  1081. send(agent, 'hi')
  1082. await waitForIdle(ctx, agent)
  1083. expect(adapter.requests).toHaveLength(1)
  1084. })
  1085. it('attaches config agent cwd to the fresh session header', async () => {
  1086. const ctx = new Context()
  1087. await ctx.plugin(LlmService)
  1088. await ctx.plugin(SessionStore)
  1089. await ctx.plugin(SystemPrompt)
  1090. await ctx.plugin(ToolRegistry)
  1091. await ctx.plugin(AgentRegistry)
  1092. await ctx.plugin(AgentLoop, {
  1093. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1094. })
  1095. const agent = ctx.agents.list()[0]!
  1096. expect(agent.session.header.cwd).toBe('/work/project')
  1097. })
  1098. it('replays a session log into an identical derived history', async () => {
  1099. const adapter = new MockAdapter([
  1100. toolCallResponse('c1', 'echo', { text: 'x' }),
  1101. textResponse('done'),
  1102. ])
  1103. const ctx = await harness(adapter)
  1104. ctx.tools.register(defineContentToolFixture({
  1105. name: 'echo',
  1106. description: '',
  1107. parameters: { text: { type: 'string' } },
  1108. async execute(args) {
  1109. return [{ type: 'text', text: String(args.text) }]
  1110. },
  1111. }))
  1112. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1113. send(agent, 'run')
  1114. await waitForIdle(ctx, agent)
  1115. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1116. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1117. // event-by-event identity of types
  1118. expect(replayed.events.map(e => e.type)).toEqual(
  1119. agent.session.events.map(e => e.type))
  1120. })
  1121. })