loop.spec.ts 49 KB

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