loop.spec.ts 46 KB

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