loop.spec.ts 61 KB

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