loop.spec.ts 58 KB

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