loop.spec.ts 47 KB

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