loop.spec.ts 53 KB

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