loop.spec.ts 64 KB

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