loop.spec.ts 63 KB

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