loop.spec.ts 73 KB

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