loop.spec.ts 75 KB

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