loop.spec.ts 53 KB

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