loop.spec.ts 57 KB

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