loop.spec.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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.message
  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(1)
  499. expect(agent.session.events.filter(event => event.type === 'turn/end')).toHaveLength(1)
  500. expect(agent.inbox.nextStep).toHaveLength(1)
  501. send(agent, 'resume')
  502. await waitForIdle(ctx, agent)
  503. expect(adapter.requests).toHaveLength(1)
  504. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  505. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  506. })
  507. it('inject() while idle durably stages context without opening a turn', async () => {
  508. const adapter = new MockAdapter([textResponse('ok')])
  509. const ctx = await harness(adapter)
  510. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  511. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
  512. expect(agent.status).toBe('idle')
  513. expect(adapter.requests).toHaveLength(0)
  514. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
  515. expect(agent.session.events.at(-1)).toMatchObject({
  516. type: 'agent/inbox/spliced',
  517. data: {
  518. target: 'next-step',
  519. inserted: [{
  520. role: 'user',
  521. content: [{ type: 'text', text: 'file changed: a.ts' }],
  522. source: { kind: 'plugin', plugin: 'watcher' },
  523. }],
  524. },
  525. })
  526. send(agent, 'go')
  527. await waitForIdle(ctx, agent)
  528. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  529. const flat = JSON.stringify(adapter.requests[0]!.messages)
  530. expect(flat).toContain('file changed: a.ts')
  531. expect(flat).not.toContain('<context source=')
  532. })
  533. it('inject() persists structured context content verbatim with durable source', async () => {
  534. const adapter = new MockAdapter([textResponse('ok')])
  535. const ctx = await harness(adapter)
  536. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  537. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  538. agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'workspace-context' } }))
  539. send(agent, 'go')
  540. await waitForIdle(ctx, agent)
  541. const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  542. expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
  543. .toEqual({ kind: 'plugin', plugin: 'workspace-context' })
  544. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  545. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  546. expect(requestText).not.toContain('<context source=')
  547. })
  548. it('defers inject() during tool execution until after the tool result', async () => {
  549. const adapter = new MockAdapter([
  550. toolCallResponse('c1', 'noticer', {}, 'calling'),
  551. textResponse('done'),
  552. ])
  553. const ctx = await harness(adapter)
  554. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  555. let visibleDuringTool = false
  556. ctx.tools.register(defineContentToolFixture({
  557. name: 'noticer',
  558. description: 'injects a notice',
  559. parameters: {},
  560. async execute() {
  561. await Promise.resolve()
  562. const first = { type: 'text' as const, text: 'mid-turn notice' }
  563. agent.inject(createUserMessage({ content: [first], source: { kind: 'plugin', plugin: 'x' } }))
  564. first.text = 'mutated after inject'
  565. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } }))
  566. visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  567. return [{ type: 'text', text: 'ok' }]
  568. },
  569. }))
  570. send(agent, 'go')
  571. await waitForIdle(ctx, agent)
  572. expect(visibleDuringTool).toBe(false)
  573. // The injection stays in the open turn, but its user-role context cannot
  574. // split the assistant tool call from the provider's tool-result message.
  575. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  576. expect(turnStarts).toHaveLength(1)
  577. const result = agent.session.events.find(e => e.type === 'tool/result')!
  578. const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  579. expect(contexts).toHaveLength(2)
  580. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  581. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  582. .toEqual([
  583. { type: 'text', text: 'mid-turn notice' },
  584. { type: 'text', text: 'second notice' },
  585. ])
  586. const secondRequest = adapter.requests[1]!.messages
  587. const resultIndex = secondRequest.findIndex(message =>
  588. message.content.some(block => block.type === 'tool-result'))
  589. const contextIndexes = secondRequest.flatMap((message, index) =>
  590. message.content.some(block => block.type === 'text'
  591. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  592. ? [index]
  593. : [])
  594. expect(resultIndex).toBeGreaterThanOrEqual(0)
  595. expect(contextIndexes).toHaveLength(2)
  596. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  597. })
  598. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  599. const adapter = new MockAdapter([
  600. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  601. textResponse('done'),
  602. ])
  603. const ctx = await harness(adapter)
  604. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  605. ctx.tools.register(defineContentToolFixture({
  606. name: 'invalid-injector',
  607. description: 'attempts an invalid context injection',
  608. parameters: {},
  609. async execute() {
  610. expect(() => {
  611. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never }))
  612. }).toThrow('agent context must be losslessly JSON-serializable')
  613. return [{ type: 'text', text: 'rejected invalid context' }]
  614. },
  615. }))
  616. send(agent, 'go')
  617. await waitForIdle(ctx, agent)
  618. expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  619. })
  620. it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
  621. const adapter = new MockAdapter([
  622. textResponse('step 1'),
  623. textResponse('step 2'),
  624. textResponse('step 3'),
  625. ])
  626. const ctx = await harness(adapter)
  627. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  628. let steps = 0
  629. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  630. ctx.on('agent/turn-stopping', (subject) => {
  631. if (steps < 3) {
  632. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } }))
  633. }
  634. })
  635. send(agent, 'go')
  636. await waitForIdle(ctx, agent)
  637. expect(steps).toBe(3)
  638. expect(adapter.requests).toHaveLength(3)
  639. })
  640. it('a tool can conclude the turn despite owing a follow-up request', async () => {
  641. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  642. const ctx = await harness(adapter)
  643. ctx.tools.register(defineContentToolFixture({
  644. name: 'echo',
  645. description: '',
  646. parameters: { text: { type: 'string' } },
  647. async execute(args, exec) {
  648. exec.concludeTurn()
  649. return [{ type: 'text', text: String(args.text) }]
  650. },
  651. }))
  652. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  653. send(agent, 'go')
  654. await waitForIdle(ctx, agent)
  655. // only one model call despite the tool call requesting a follow-up
  656. expect(adapter.requests).toHaveLength(1)
  657. // The tool still executes and durably records its result.
  658. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  659. })
  660. it('continues for steering that arrived during a concluding tool step', async () => {
  661. const adapter = new MockAdapter([
  662. toolCallResponse('c1', 'finalize', {}),
  663. textResponse('next turn reply'),
  664. ])
  665. const ctx = await harness(adapter)
  666. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  667. ctx.tools.register(defineContentToolFixture({
  668. name: 'finalize',
  669. description: '',
  670. parameters: {},
  671. async execute(_args, exec) {
  672. // Steering lands while the concluding tool is still executing.
  673. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } }))
  674. exec.concludeTurn()
  675. return [{ type: 'text', text: 'final' }]
  676. },
  677. }))
  678. send(agent, 'go')
  679. await waitForIdle(ctx, agent)
  680. expect(adapter.requests).toHaveLength(2)
  681. const events = agent.session.events.map(event => event.type)
  682. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  683. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('late steering')
  684. const texts = adapter.requests[1]!.messages
  685. .flatMap(message => message.content)
  686. .filter(block => block.type === 'text')
  687. .map(block => block.text)
  688. expect(texts).toContain('late steering')
  689. })
  690. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  691. const adapter = new MockAdapter([textResponse('ok')])
  692. const ctx = await harness(adapter)
  693. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  694. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  695. const config = await next()
  696. // The seed is frozen — config is not a mutable per-call knob; a switch
  697. // is proposed by returning a replacement, and the loop logs it.
  698. expect(Object.isFrozen(config)).toBe(true)
  699. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  700. return { ...config, model: 'other-model' }
  701. })
  702. send(agent, 'hi')
  703. await waitForIdle(ctx, agent)
  704. expect(adapter.requests[0]!.model).toBe('other-model')
  705. // The header event records what the request ACTUALLY used — the switch is
  706. // a reconstructable fact, not silent drift.
  707. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  708. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  709. })
  710. it('agent/pre-step fires once per proposed step before the step is opened', async () => {
  711. const adapter = new MockAdapter([
  712. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  713. textResponse('done'),
  714. ])
  715. const ctx = await harness(adapter)
  716. ctx.tools.register(defineContentToolFixture({
  717. name: 'echo', description: 'echo', parameters: {},
  718. async execute() { return [{ type: 'text', text: 'echoed' }] },
  719. }))
  720. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  721. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  722. ctx.on('agent/pre-step', (subject, _messages, { turn, step, signal }, next) => {
  723. if (subject === agent) fires.push({ turn, step, signal })
  724. return next()
  725. })
  726. send(agent, 'go')
  727. await waitForIdle(ctx, agent)
  728. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  729. { turn: 1, step: 1 },
  730. { turn: 1, step: 2 },
  731. ])
  732. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  733. })
  734. it('agent/pre-step fires before its step boundary opens and before the request', async () => {
  735. const adapter = new MockAdapter([textResponse('ok')])
  736. const ctx = await harness(adapter)
  737. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  738. let boundaryOpen = true
  739. ctx.on('agent/pre-step', (subject, _messages, _context, next) => {
  740. if (subject === agent) boundaryOpen = subject.session.events.at(-1)?.type === 'step/start'
  741. return next()
  742. })
  743. send(agent, 'go')
  744. await waitForIdle(ctx, agent)
  745. expect(boundaryOpen).toBe(false)
  746. expect(adapter.requests).toHaveLength(1)
  747. })
  748. it('a throwing agent/pre-step listener fails the proposal, not the loop', async () => {
  749. const adapter = new MockAdapter([textResponse('second turn ok')])
  750. const ctx = await harness(adapter)
  751. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  752. let throwOnce = true
  753. ctx.on('agent/pre-step', (_agent, _messages, _context, next) => {
  754. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  755. return next()
  756. })
  757. const errors: Error[] = []
  758. ctx.on('agent/error', (_a, _t, _s, error) => {
  759. if (error instanceof Error) errors.push(error)
  760. })
  761. send(agent, 'first')
  762. await waitForIdle(ctx, agent)
  763. // The first proposal failed inside a balanced turn without calling the model.
  764. expect(errors.map(error => error.message)).toEqual(['boom in pre-step'])
  765. expect(adapter.requests.length).toBe(0)
  766. expect(agent.session.events.some(event => event.type === 'turn/start')).toBe(true)
  767. expect(agent.session.events.some(event => event.type === 'turn/end')).toBe(true)
  768. // The loop survived: a second prompt runs a normal completed turn.
  769. send(agent, 'second')
  770. await waitForIdle(ctx, agent)
  771. expect(adapter.requests.length).toBe(1)
  772. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  773. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  774. })
  775. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  776. const adapter = new MockAdapter(['hang'])
  777. const ctx = await harness(adapter)
  778. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  779. const reasons: TurnEndReason[] = []
  780. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  781. send(agent, 'go')
  782. // wait until the stream is hanging, then cancel
  783. await new Promise(r => setTimeout(r, 30))
  784. expect(agent.status).toBe('running')
  785. agent.cancel({ kind: 'user' })
  786. await waitForIdle(ctx, agent)
  787. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  788. })
  789. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  790. // A single step that ends with a max-tokens finish (no tool calls): the
  791. // turn stops by default and ends max-tokens, not completed.
  792. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  793. const ctx = await harness(adapter)
  794. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  795. const reasons: TurnEndReason[] = []
  796. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  797. send(agent, 'go')
  798. await waitForIdle(ctx, agent)
  799. expect(adapter.requests).toHaveLength(1)
  800. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  801. // Assert the durable row, not only the live listener.
  802. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  803. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  804. })
  805. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  806. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  807. // must be FORCED to reach step 2 which finishes normally (stop).
  808. const adapter = new MockAdapter([
  809. maxTokensResponse('first half'),
  810. textResponse('second half'),
  811. ])
  812. const ctx = await harness(adapter)
  813. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  814. let steps = 0
  815. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  816. // Force exactly one continuation (step 1 → step 2), then defer to default
  817. // (step 2 is a plain stop with no tool calls → stops).
  818. ctx.on('agent/turn-stopping', (subject) => {
  819. if (steps < 2) {
  820. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
  821. }
  822. })
  823. const reasons: TurnEndReason[] = []
  824. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  825. send(agent, 'go')
  826. await waitForIdle(ctx, agent)
  827. expect(steps).toBe(2)
  828. expect(adapter.requests).toHaveLength(2)
  829. expect(adapter.requests[1]!.messages).toEqual([
  830. {
  831. id: expect.any(String) as unknown,
  832. role: 'user',
  833. content: [{ type: 'text', text: 'go' }],
  834. source: { kind: 'user' },
  835. },
  836. {
  837. id: expect.any(String) as unknown,
  838. role: 'assistant',
  839. content: [{ type: 'text', text: 'first half' }],
  840. source: { kind: 'model', provider: 'mock', model: 'mock' },
  841. },
  842. {
  843. id: expect.any(String) as unknown,
  844. role: 'user',
  845. content: [{ type: 'text', text: 'continue after truncation' }],
  846. source: { kind: 'plugin', plugin: 'max-tokens-test' },
  847. },
  848. ])
  849. // A max-token step is sticky: the later completed step must not
  850. // downgrade the turn outcome.
  851. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  852. })
  853. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  854. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  855. // stop. The per-turn reason must be independent — turn 2 ends completed.
  856. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  857. const ctx = await harness(adapter)
  858. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  859. const reasons: TurnEndReason[] = []
  860. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  861. send(agent, 'first')
  862. await waitForIdle(ctx, agent)
  863. send(agent, 'second')
  864. await waitForIdle(ctx, agent)
  865. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  866. })
  867. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  868. const callId = CallId('c1')
  869. const adapter = new MockAdapter([[
  870. { type: 'block-start', index: 0, blockType: 'tool-call' },
  871. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  872. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  873. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  874. { type: 'finish', reason: { kind: 'max-tokens' } },
  875. ]])
  876. const ctx = await harness(adapter)
  877. let executions = 0
  878. ctx.tools.register(defineContentToolFixture({
  879. name: 'echo',
  880. description: '',
  881. parameters: { text: { type: 'string' } },
  882. async execute() {
  883. executions += 1
  884. return [{ type: 'text', text: 'should not run' }]
  885. },
  886. }))
  887. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  888. const reasons: TurnEndReason[] = []
  889. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  890. send(agent, 'go')
  891. await waitForIdle(ctx, agent)
  892. expect(executions).toBe(0)
  893. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  894. expect(agent.session.deriveMessages()).toEqual([{
  895. id: expect.any(String) as unknown,
  896. role: 'user',
  897. content: [{ type: 'text', text: 'go' }],
  898. source: { kind: 'user' },
  899. }])
  900. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  901. // Empty content still needs an assistant/message to carry usage; derivation
  902. // skips that host so it does not create a spurious assistant turn.
  903. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  904. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  905. turn: 1,
  906. step: 1,
  907. message: {
  908. id: expect.any(String) as unknown,
  909. role: 'assistant',
  910. content: [],
  911. source: { kind: 'model', provider: 'mock', model: 'mock' },
  912. },
  913. usage: { inputTokens: 10, outputTokens: 5 },
  914. })
  915. })
  916. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  917. // The truncated tool call is dropped from durable content, while the
  918. // successful provider call still needs an exact replay anchor.
  919. const callId = CallId('c1')
  920. const adapter = new MockAdapter([[
  921. { type: 'block-start', index: 0, blockType: 'tool-call' },
  922. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  923. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  924. { type: 'finish', reason: { kind: 'max-tokens' } },
  925. ]])
  926. const ctx = await harness(adapter)
  927. ctx.tools.register(defineContentToolFixture({
  928. name: 'echo',
  929. description: '',
  930. parameters: { text: { type: 'string' } },
  931. async execute() { return [{ type: 'text', text: 'should not run' }] },
  932. }))
  933. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  934. const reasons: TurnEndReason[] = []
  935. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  936. send(agent, 'go')
  937. await waitForIdle(ctx, agent)
  938. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  939. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  940. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  941. turn: 1,
  942. step: 1,
  943. message: {
  944. id: expect.any(String) as unknown,
  945. role: 'assistant',
  946. content: [],
  947. source: { kind: 'model', provider: 'mock', model: 'mock' },
  948. },
  949. })
  950. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  951. expect(agent.session.deriveMessages()).toEqual([{
  952. id: expect.any(String) as unknown,
  953. role: 'user',
  954. content: [{ type: 'text', text: 'go' }],
  955. source: { kind: 'user' },
  956. }])
  957. })
  958. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  959. // A clean content-less call stays absent from derived messages but remains
  960. // a durable successful-call boundary for replay consumers.
  961. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  962. const ctx = await harness(adapter)
  963. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  964. const reasons: TurnEndReason[] = []
  965. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  966. send(agent, 'go')
  967. await waitForIdle(ctx, agent)
  968. expect(reasons).toEqual([{ kind: 'completed' }])
  969. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  970. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  971. turn: 1,
  972. step: 1,
  973. message: {
  974. id: expect.any(String) as unknown,
  975. role: 'assistant',
  976. content: [],
  977. source: { kind: 'model', provider: 'mock', model: 'mock' },
  978. },
  979. })
  980. expect(assistant.sourceEventSeqs?.length).toBe(1)
  981. expect(agent.session.deriveMessages()).toEqual([{
  982. id: expect.any(String) as unknown,
  983. role: 'user',
  984. content: [{ type: 'text', text: 'go' }],
  985. source: { kind: 'user' },
  986. }])
  987. })
  988. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  989. const callId = CallId('c1')
  990. const adapter = new MockAdapter([[
  991. { type: 'block-start', index: 0, blockType: 'text' },
  992. { type: 'text-delta', index: 0, text: 'partial text' },
  993. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  994. { type: 'block-start', index: 1, blockType: 'tool-call' },
  995. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  996. { type: 'finish', reason: { kind: 'max-tokens' } },
  997. ]])
  998. const ctx = await harness(adapter)
  999. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1000. send(agent, 'go')
  1001. await waitForIdle(ctx, agent)
  1002. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  1003. expect(agent.session.deriveMessages()).toEqual([
  1004. {
  1005. id: expect.any(String) as unknown,
  1006. role: 'user',
  1007. content: [{ type: 'text', text: 'go' }],
  1008. source: { kind: 'user' },
  1009. },
  1010. {
  1011. id: expect.any(String) as unknown,
  1012. role: 'assistant',
  1013. content: [{ type: 'text', text: 'partial text' }],
  1014. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1015. },
  1016. ])
  1017. })
  1018. it('contains a step/end observer failure without changing continuation', async () => {
  1019. const adapter = new MockAdapter([
  1020. toolCallResponse('c1', 'echo', { text: 'x' }),
  1021. textResponse('continued after tool call'),
  1022. ])
  1023. const ctx = await harness(adapter)
  1024. ctx.tools.register(defineContentToolFixture({
  1025. name: 'echo',
  1026. description: '',
  1027. parameters: { text: { type: 'string' } },
  1028. async execute(args) {
  1029. return [{ type: 'text', text: String(args.text) }]
  1030. },
  1031. }))
  1032. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1033. let threw = false
  1034. // Post-commit session observers cannot control the loop. The tool call still
  1035. // drives the second model request, and the turn completes normally.
  1036. ctx.on('session/event', (_session, event) => {
  1037. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  1038. })
  1039. send(agent, 'go')
  1040. await waitForIdle(ctx, agent)
  1041. expect(adapter.requests).toHaveLength(2)
  1042. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  1043. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  1044. })
  1045. it('contains a reentrant send attempted during durable inbox publication', async () => {
  1046. const adapter = new MockAdapter([textResponse('first')])
  1047. const ctx = await harness(adapter)
  1048. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1049. let nested = false
  1050. ctx.on('session/event', (session, event) => {
  1051. if (session !== agent.session || event.type !== 'agent/inbox/spliced'
  1052. || event.data.inserted.length === 0 || nested) return
  1053. nested = true
  1054. send(agent, 'queued listener message')
  1055. })
  1056. const idle = waitForIdle(ctx, agent)
  1057. send(agent, 'outer message')
  1058. await idle
  1059. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  1060. const messages = agent.session.events
  1061. .filter(event => event.type === 'user/message')
  1062. .map(event => event.data.content)
  1063. expect(turns).toHaveLength(1)
  1064. expect(messages).toEqual([[{ type: 'text', text: 'outer message' }]])
  1065. })
  1066. it('preserves independent turn sources across an adjacent microtask send', async () => {
  1067. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1068. const ctx = await harness(adapter)
  1069. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1070. const idle = waitForIdle(ctx, agent)
  1071. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
  1072. await Promise.resolve()
  1073. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
  1074. await idle
  1075. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  1076. const sources = agent.session.events
  1077. .filter(event => event.type === 'user/message')
  1078. .map(event => event.data.source)
  1079. expect(turns).toHaveLength(2)
  1080. expect(sources).toEqual([
  1081. { kind: 'user' },
  1082. { kind: 'plugin', plugin: 'test' },
  1083. ])
  1084. })
  1085. it('keeps a session-listener send after dequeue in the following turn', async () => {
  1086. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1087. const ctx = await harness(adapter)
  1088. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1089. const turns: number[] = []
  1090. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  1091. // queue two messages while idle — first starts turn 1 immediately;
  1092. // queue the second during turn 1 when the first assistant chunk streams
  1093. let queued = false
  1094. ctx.on('session/event', (_s, event) => {
  1095. if (event.type === 'assistant/chunk' && !queued) {
  1096. queued = true
  1097. queueMicrotask(() => { send(agent, 'second message') })
  1098. }
  1099. })
  1100. send(agent, 'first message')
  1101. await waitForIdle(ctx, agent)
  1102. expect(turns).toEqual([1, 2])
  1103. expect(adapter.requests).toHaveLength(2)
  1104. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  1105. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  1106. })
  1107. it('keeps a model-adapter callback send in the following turn', async () => {
  1108. const agentRef: { current?: Agent } = {}
  1109. const adapter = new MockAdapter([
  1110. () => {
  1111. const agent = agentRef.current
  1112. if (agent === undefined) throw new Error('model callback ran before agent setup')
  1113. send(agent, 'model callback message')
  1114. return textResponse('first')
  1115. },
  1116. textResponse('second'),
  1117. ])
  1118. const ctx = await harness(adapter)
  1119. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1120. agentRef.current = agent
  1121. const idle = waitForIdle(ctx, agent)
  1122. send(agent, 'outer message')
  1123. await idle
  1124. const messages = agent.session.events
  1125. .filter(event => event.type === 'user/message')
  1126. .map(event => event.data.content)
  1127. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  1128. expect(messages).toEqual([
  1129. [{ type: 'text', text: 'outer message' }],
  1130. [{ type: 'text', text: 'model callback message' }],
  1131. ])
  1132. })
  1133. it('records normalized model errors on the turn boundary', async () => {
  1134. const adapter = new MockAdapter([]) // script exhausted → throws
  1135. const ctx = await harness(adapter)
  1136. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1137. const errors: unknown[] = []
  1138. const reasons: TurnEndReason[] = []
  1139. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  1140. errors.push(error)
  1141. })
  1142. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1143. send(agent, 'hi')
  1144. await waitForIdle(ctx, agent)
  1145. expect(errors).toHaveLength(1)
  1146. expect(errors[0]).toBeInstanceOf(LlmError)
  1147. expect((errors[0] as LlmError).failure).toEqual({
  1148. message: 'MockAdapter: script exhausted',
  1149. code: 'UNKNOWN',
  1150. })
  1151. expect(reasons[0]).toMatchObject({ kind: 'error' })
  1152. // The durable failure and live relay describe the same failed turn.
  1153. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  1154. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error' })
  1155. })
  1156. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  1157. const adapter = new MockAdapter(['hang'])
  1158. const ctx = await harness(adapter)
  1159. let agent!: Agent
  1160. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1161. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1162. }, { inject: ['agentLoop'] }))
  1163. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1164. send(agent, 'go')
  1165. await new Promise(r => setTimeout(r, 30))
  1166. expect(agent.status).toBe('running')
  1167. await fiber.dispose()
  1168. await driverDone(agent)
  1169. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1170. })
  1171. it('creates agents from config on startup', async () => {
  1172. const adapter = new MockAdapter([textResponse('from config')])
  1173. const ctx = new Context()
  1174. await ctx.plugin(LlmService)
  1175. await ctx.plugin(SessionStore)
  1176. await ctx.plugin(SystemPrompt)
  1177. await ctx.plugin(ToolRegistry)
  1178. await ctx.plugin(AgentRegistry)
  1179. await ctx.plugin(AgentLoop, {
  1180. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  1181. })
  1182. ctx.llm.registerAdapter(['mock'], adapter)
  1183. const agent = ctx.agents.list()[0]!
  1184. expect(agent).toBeDefined()
  1185. expect(agent.id).toBe(agent.session.id)
  1186. expect(agent.id).toMatch(/^config-agent-session-/)
  1187. expect(agent.options.model).toBe('mock')
  1188. // the agent is alive: send triggers a turn
  1189. send(agent, 'hi')
  1190. await waitForIdle(ctx, agent)
  1191. expect(adapter.requests).toHaveLength(1)
  1192. })
  1193. it('attaches config agent cwd to the fresh session header', async () => {
  1194. const ctx = new Context()
  1195. await ctx.plugin(LlmService)
  1196. await ctx.plugin(SessionStore)
  1197. await ctx.plugin(SystemPrompt)
  1198. await ctx.plugin(ToolRegistry)
  1199. await ctx.plugin(AgentRegistry)
  1200. await ctx.plugin(AgentLoop, {
  1201. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1202. })
  1203. const agent = ctx.agents.list()[0]!
  1204. expect(agent.session.header.cwd).toBe('/work/project')
  1205. })
  1206. it('replays a session log into an identical derived history', async () => {
  1207. const adapter = new MockAdapter([
  1208. toolCallResponse('c1', 'echo', { text: 'x' }),
  1209. textResponse('done'),
  1210. ])
  1211. const ctx = await harness(adapter)
  1212. ctx.tools.register(defineContentToolFixture({
  1213. name: 'echo',
  1214. description: '',
  1215. parameters: { text: { type: 'string' } },
  1216. async execute(args) {
  1217. return [{ type: 'text', text: String(args.text) }]
  1218. },
  1219. }))
  1220. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1221. send(agent, 'run')
  1222. await waitForIdle(ctx, agent)
  1223. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1224. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1225. // event-by-event identity of types over the inherited prefix
  1226. expect(replayed.events.slice(0, agent.session.seq).map(e => e.type)).toEqual(
  1227. agent.session.events.map(e => e.type))
  1228. expect(replayed.events.at(-1)?.type).toBe('session/end-seed')
  1229. })
  1230. })