loop.spec.ts 50 KB

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