loop.spec.ts 69 KB

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