loop.spec.ts 72 KB

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