loop.spec.ts 78 KB

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