loop.spec.ts 49 KB

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