loop.spec.ts 59 KB

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