loop.spec.ts 66 KB

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