loop.spec.ts 64 KB

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