loop.spec.ts 64 KB

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