loop.spec.ts 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  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, { 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")',
  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().some(event => event.type === 'system/message')).toBe(false)
  557. })
  558. it('materializes changed runtime context at the history tail without rewriting the system header', async () => {
  559. const adapter = new MockAdapter([
  560. textResponse('one'),
  561. textResponse('two'),
  562. textResponse('three'),
  563. textResponse('four'),
  564. textResponse('five'),
  565. ])
  566. const ctx = await harness(adapter)
  567. let mode = 'read-only'
  568. const dispose = ctx.systemPrompt.context({ name: 'policy', order: 0, text: () => `Mode: ${mode}.` })
  569. const agent = await ctx.agentLoop.create(SessionId('a-runtime-context'), { provider: 'mock', model: 'mock' })
  570. const contextEvents = () => agent.session.snapshotEvents().flatMap(event =>
  571. event.type === 'user/message'
  572. && event.data.source.kind === 'plugin'
  573. && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
  574. ? [event]
  575. : [])
  576. send(agent, 'first')
  577. await waitForIdle(ctx, agent)
  578. expect(contextEvents()).toHaveLength(1)
  579. expect(contextEvents()[0]?.data.content).toEqual([{
  580. type: 'text',
  581. text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nMode: read-only.',
  582. }])
  583. send(agent, 'unchanged')
  584. await waitForIdle(ctx, agent)
  585. expect(contextEvents()).toHaveLength(1)
  586. mode = 'danger-full-access'
  587. send(agent, 'changed')
  588. await waitForIdle(ctx, agent)
  589. expect(contextEvents()).toHaveLength(2)
  590. const changedBlock = contextEvents()[1]?.data.content[0]
  591. expect(changedBlock?.type).toBe('text')
  592. if (changedBlock?.type !== 'text') throw new Error('changed runtime context is not text')
  593. expect(changedBlock.text).toContain('danger-full-access')
  594. dispose()
  595. send(agent, 'cleared')
  596. await waitForIdle(ctx, agent)
  597. expect(contextEvents()).toHaveLength(3)
  598. expect(contextEvents()[2]?.data.content).toEqual([{
  599. type: 'text',
  600. text: 'Current runtime context: none. Earlier runtime-context snapshots no longer apply.',
  601. }])
  602. send(agent, 'still clear')
  603. await waitForIdle(ctx, agent)
  604. expect(contextEvents()).toHaveLength(3)
  605. expect(adapter.requests.map(systemOf)).toEqual(Array(5).fill(systemOf(adapter.requests[0])))
  606. expect(agent.session.snapshotEvents().filter(event => event.type === 'system/message')).toHaveLength(1)
  607. expect(agent.session.snapshotEvents().flatMap(event =>
  608. event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial'])
  609. })
  610. it('re-emits unchanged runtime context when a surface replacement removed the retained snapshot', async () => {
  611. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  612. const ctx = await harness(adapter)
  613. ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
  614. const agent = await ctx.agentLoop.create(SessionId('a-runtime-context-compacted'), { provider: 'mock', model: 'mock' })
  615. send(agent, 'first')
  616. await waitForIdle(ctx, agent)
  617. const contextEvent = agent.session.snapshotEvents().find(event =>
  618. event.type === 'user/message'
  619. && event.data.source.kind === 'plugin'
  620. && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt')
  621. if (contextEvent?.type !== 'user/message') throw new Error('first turn did not materialize runtime context')
  622. agent.session.append('user/message', createUserMessage({
  623. content: [{ type: 'text', text: 'compacted summary' }],
  624. source: { kind: 'plugin', plugin: 'test-compaction' },
  625. }), {
  626. surfaceOp: { op: 'replace', start: contextEvent.seq, end: contextEvent.seq },
  627. sourceEventSeqs: [contextEvent.seq],
  628. })
  629. send(agent, 'after compaction')
  630. await waitForIdle(ctx, agent)
  631. const runtimeContexts = agent.session.snapshotEvents().flatMap(event =>
  632. event.type === 'user/message'
  633. && event.data.source.kind === 'plugin'
  634. && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
  635. ? [event]
  636. : [])
  637. expect(runtimeContexts).toHaveLength(2)
  638. expect(adapter.requests[1]?.messages.some(message =>
  639. message.source.kind === 'plugin'
  640. && message.source.plugin === '@deepseek-ai/dsh-system-prompt')).toBe(true)
  641. })
  642. it('clears compacted runtime context after the active set becomes empty', async () => {
  643. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  644. const ctx = await harness(adapter)
  645. const dispose = ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
  646. const agent = await ctx.agentLoop.create(SessionId('a-runtime-context-compacted-clear'), { provider: 'mock', model: 'mock' })
  647. send(agent, 'first')
  648. await waitForIdle(ctx, agent)
  649. const contextEvent = agent.session.snapshotEvents().find(event =>
  650. event.type === 'user/message'
  651. && event.data.source.kind === 'plugin'
  652. && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt')
  653. if (contextEvent?.type !== 'user/message') throw new Error('first turn did not materialize runtime context')
  654. agent.session.append('user/message', createUserMessage({
  655. content: [{ type: 'text', text: 'summary retaining old mode: read-only' }],
  656. source: { kind: 'plugin', plugin: 'test-compaction' },
  657. }), {
  658. surfaceOp: { op: 'replace', start: contextEvent.seq, end: contextEvent.seq },
  659. sourceEventSeqs: [contextEvent.seq],
  660. })
  661. dispose()
  662. send(agent, 'after compaction')
  663. await waitForIdle(ctx, agent)
  664. const clearing = adapter.requests[1]?.messages.find(message =>
  665. message.role === 'user'
  666. && message.source.kind === 'plugin'
  667. && message.source.plugin === '@deepseek-ai/dsh-system-prompt')
  668. expect(clearing?.content).toEqual([{
  669. type: 'text',
  670. text: 'Current runtime context: none. Earlier runtime-context snapshots no longer apply.',
  671. }])
  672. })
  673. it('does not clear runtime context after an unrelated replacement', async () => {
  674. const adapter = new MockAdapter([textResponse('ok')])
  675. const ctx = await harness(adapter)
  676. const agent = await ctx.agentLoop.create(SessionId('a-runtime-context-unrelated-compaction'), { provider: 'mock', model: 'mock' })
  677. const original = agent.session.append('user/message', createUserMessage({
  678. content: [{ type: 'text', text: 'old context' }],
  679. source: { kind: 'plugin', plugin: 'test-context' },
  680. }), { surfaceOp: 'append' })
  681. agent.session.append('user/message', createUserMessage({
  682. content: [{ type: 'text', text: 'compacted summary' }],
  683. source: { kind: 'plugin', plugin: 'test-compaction' },
  684. }), {
  685. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  686. sourceEventSeqs: [original.seq],
  687. })
  688. send(agent, 'after compaction')
  689. await waitForIdle(ctx, agent)
  690. expect(adapter.requests[0]?.messages.some(message =>
  691. message.role === 'user'
  692. && message.source.kind === 'plugin'
  693. && message.source.plugin === '@deepseek-ai/dsh-system-prompt')).toBe(false)
  694. })
  695. it('replaces a malformed retained runtime-context message with the current complete snapshot', async () => {
  696. const adapter = new MockAdapter([textResponse('ok')])
  697. const ctx = await harness(adapter)
  698. ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
  699. const agent = await ctx.agentLoop.create(SessionId('a-runtime-context-malformed'), { provider: 'mock', model: 'mock' })
  700. agent.session.append('user/message', createUserMessage({
  701. content: [{ type: 'text', text: 'broken' }, { type: 'text', text: 'snapshot' }],
  702. source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' },
  703. }), { surfaceOp: 'append' })
  704. send(agent, 'repair context')
  705. await waitForIdle(ctx, agent)
  706. const runtimeContexts = agent.session.snapshotEvents().flatMap(event =>
  707. event.type === 'user/message'
  708. && event.data.source.kind === 'plugin'
  709. && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
  710. ? [event]
  711. : [])
  712. expect(runtimeContexts).toHaveLength(2)
  713. expect(runtimeContexts[1]?.data.content).toEqual([{
  714. type: 'text',
  715. text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nMode: read-only.',
  716. }])
  717. })
  718. it('records exact replay chunks inside the durable assistant message', async () => {
  719. const adapter = new MockAdapter([textResponse('abc')])
  720. const ctx = await harness(adapter)
  721. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  722. send(agent, 'hi')
  723. await waitForIdle(ctx, agent)
  724. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  725. const chunks = message?.type === 'assistant/message' ? expandAssistantStream(message.data.stream) : []
  726. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  727. expect(chunks).toHaveLength(7)
  728. const deltaText = chunks
  729. .map(member => member.chunk)
  730. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  731. .map(c => c.text)
  732. .join('')
  733. expect(deltaText).toBe('abc')
  734. })
  735. it('injects steering between steps and continues the turn', async () => {
  736. const adapter = new MockAdapter([
  737. toolCallResponse('c1', 'slow', {}),
  738. textResponse('addressed the steering'),
  739. ])
  740. const ctx = await harness(adapter)
  741. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  742. ctx.tools.register(defineContentToolFixture({
  743. name: 'slow',
  744. description: '',
  745. parameters: {},
  746. async execute() {
  747. // steer while the turn is running (during tool execution)
  748. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'change of plans' }], source: { kind: 'user' } }))
  749. return [{ type: 'text', text: 'tool done' }]
  750. },
  751. }))
  752. send(agent, 'start')
  753. await waitForIdle(ctx, agent)
  754. const steering = agent.session.snapshotEvents().find(e =>
  755. e.type === 'user/message' && JSON.stringify(e.data.content).includes('change of plans'))
  756. expect(steering).toBeDefined()
  757. // The entered batch is appended after the second step opens and before its
  758. // request derives history.
  759. const steeringSeq = steering!.seq
  760. const secondStepStart = agent.session.snapshotEvents().filter(e => e.type === 'step/start')[1]
  761. expect(secondStepStart).toBeDefined()
  762. expect(steeringSeq).toBeGreaterThan(secondStepStart!.seq)
  763. // the second model request saw the steering content
  764. const secondRequest = adapter.requests[1]
  765. const flat = JSON.stringify(secondRequest!.messages)
  766. expect(flat).toContain('change of plans')
  767. })
  768. it('starts idle steering synchronously and enters later steering at the next step', async () => {
  769. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  770. const ctx = await harness(adapter)
  771. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  772. const idle = waitForIdle(ctx, agent)
  773. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'first idle steer' }], source: { kind: 'user' } }))
  774. expect(agent.status).toBe('running')
  775. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  776. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'second idle steer' }], source: { kind: 'user' } }))
  777. await idle
  778. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  779. expect(agent.session.snapshotEvents()
  780. .filter(event => event.type === 'user/message')
  781. .map(event => event.data.content)).toEqual([
  782. [{ type: 'text', text: 'first idle steer' }],
  783. [{ type: 'text', text: 'second idle steer' }],
  784. ])
  785. expect(adapter.requests).toHaveLength(2)
  786. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('first idle steer')
  787. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('second idle steer')
  788. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('second idle steer')
  789. })
  790. it('stops after a throwing pre-step listener and retains later steering until a wakeup', async () => {
  791. const adapter = new MockAdapter([textResponse('recovered')])
  792. const ctx = await harness(adapter)
  793. const agent = await ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
  794. let fail = true
  795. ctx.on('agent/pre-step', ({ agent: subject }, next) => {
  796. if (subject !== agent || !fail) return next()
  797. fail = false
  798. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } }))
  799. throw new Error('pre-step failed')
  800. })
  801. send(agent, 'prompt')
  802. await waitForIdle(ctx, agent)
  803. expect(adapter.requests).toHaveLength(0)
  804. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  805. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(1)
  806. expect(agent.inbox.nextStep).toHaveLength(1)
  807. send(agent, 'resume')
  808. await waitForIdle(ctx, agent)
  809. expect(adapter.requests).toHaveLength(1)
  810. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(2)
  811. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  812. })
  813. it('inject() while idle durably stages context without opening a turn', async () => {
  814. const adapter = new MockAdapter([textResponse('ok')])
  815. const ctx = await harness(adapter)
  816. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  817. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
  818. expect(agent.status).toBe('idle')
  819. expect(adapter.requests).toHaveLength(0)
  820. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(0)
  821. expect(agent.session.snapshotEvents().at(-1)).toMatchObject({
  822. type: 'agent/inbox/spliced',
  823. data: {
  824. target: 'next-step',
  825. inserted: [{
  826. role: 'user',
  827. content: [{ type: 'text', text: 'file changed: a.ts' }],
  828. source: { kind: 'plugin', plugin: 'watcher' },
  829. }],
  830. },
  831. })
  832. send(agent, 'go')
  833. await waitForIdle(ctx, agent)
  834. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  835. const flat = JSON.stringify(adapter.requests[0]!.messages)
  836. expect(flat).toContain('file changed: a.ts')
  837. expect(flat).not.toContain('<context source=')
  838. })
  839. it('inject() persists structured context content verbatim with durable source', async () => {
  840. const adapter = new MockAdapter([textResponse('ok')])
  841. const ctx = await harness(adapter)
  842. const agent = await ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  843. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  844. agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'agent-instructions' } }))
  845. send(agent, 'go')
  846. await waitForIdle(ctx, agent)
  847. const contextEvent = agent.session.snapshotEvents().find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  848. expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
  849. .toEqual({ kind: 'plugin', plugin: 'agent-instructions' })
  850. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  851. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  852. expect(requestText).not.toContain('<context source=')
  853. })
  854. it('defers inject() during tool execution until after the tool result', async () => {
  855. const adapter = new MockAdapter([
  856. toolCallResponse('c1', 'noticer', {}, 'calling'),
  857. textResponse('done'),
  858. ])
  859. const ctx = await harness(adapter)
  860. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  861. let visibleDuringTool = false
  862. ctx.tools.register(defineContentToolFixture({
  863. name: 'noticer',
  864. description: 'injects a notice',
  865. parameters: {},
  866. async execute() {
  867. await Promise.resolve()
  868. const first = { type: 'text' as const, text: 'mid-turn notice' }
  869. agent.inject(createUserMessage({ content: [first], source: { kind: 'plugin', plugin: 'x' } }))
  870. first.text = 'mutated after inject'
  871. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } }))
  872. visibleDuringTool = agent.session.snapshotEvents().some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  873. return [{ type: 'text', text: 'ok' }]
  874. },
  875. }))
  876. send(agent, 'go')
  877. await waitForIdle(ctx, agent)
  878. expect(visibleDuringTool).toBe(false)
  879. // The injection stays in the open turn, but its user-role context cannot
  880. // split the assistant tool call from the provider's tool-result message.
  881. const turnStarts = agent.session.snapshotEvents().filter(e => e.type === 'turn/start')
  882. expect(turnStarts).toHaveLength(1)
  883. const result = agent.session.snapshotEvents().find(e => e.type === 'tool/result')!
  884. const contexts = agent.session.snapshotEvents().filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  885. expect(contexts).toHaveLength(2)
  886. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  887. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  888. .toEqual([
  889. { type: 'text', text: 'mid-turn notice' },
  890. { type: 'text', text: 'second notice' },
  891. ])
  892. const secondRequest = adapter.requests[1]!.messages
  893. const resultIndex = secondRequest.findIndex(message =>
  894. message.content.some(block => block.type === 'tool-result'))
  895. const contextIndexes = secondRequest.flatMap((message, index) =>
  896. message.content.some(block => block.type === 'text'
  897. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  898. ? [index]
  899. : [])
  900. expect(resultIndex).toBeGreaterThanOrEqual(0)
  901. expect(contextIndexes).toHaveLength(2)
  902. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  903. })
  904. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  905. const adapter = new MockAdapter([
  906. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  907. textResponse('done'),
  908. ])
  909. const ctx = await harness(adapter)
  910. const agent = await ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  911. ctx.tools.register(defineContentToolFixture({
  912. name: 'invalid-injector',
  913. description: 'attempts an invalid context injection',
  914. parameters: {},
  915. async execute() {
  916. expect(() => {
  917. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never }))
  918. }).toThrow('agent context must be losslessly JSON-serializable')
  919. return [{ type: 'text', text: 'rejected invalid context' }]
  920. },
  921. }))
  922. send(agent, 'go')
  923. await waitForIdle(ctx, agent)
  924. expect(agent.session.snapshotEvents().some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  925. })
  926. it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
  927. const adapter = new MockAdapter([
  928. textResponse('step 1'),
  929. textResponse('step 2'),
  930. textResponse('step 3'),
  931. ])
  932. const ctx = await harness(adapter)
  933. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  934. let steps = 0
  935. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  936. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  937. if (steps < 3) {
  938. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } }))
  939. }
  940. })
  941. send(agent, 'go')
  942. await waitForIdle(ctx, agent)
  943. expect(steps).toBe(3)
  944. expect(adapter.requests).toHaveLength(3)
  945. })
  946. it('a tool can conclude the turn despite owing a follow-up request', async () => {
  947. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  948. const ctx = await harness(adapter)
  949. ctx.tools.register(defineContentToolFixture({
  950. name: 'echo',
  951. description: '',
  952. parameters: { text: { type: 'string' } },
  953. async execute(args, exec) {
  954. exec.concludeTurn()
  955. return [{ type: 'text', text: String(args.text) }]
  956. },
  957. }))
  958. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  959. send(agent, 'go')
  960. await waitForIdle(ctx, agent)
  961. // only one model call despite the tool call requesting a follow-up
  962. expect(adapter.requests).toHaveLength(1)
  963. // The tool still executes and durably records its result.
  964. expect(agent.session.snapshotEvents().some(e => e.type === 'tool/result')).toBe(true)
  965. })
  966. it('continues for steering that arrived during a concluding tool step', async () => {
  967. const adapter = new MockAdapter([
  968. toolCallResponse('c1', 'finalize', {}),
  969. textResponse('next turn reply'),
  970. ])
  971. const ctx = await harness(adapter)
  972. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  973. ctx.tools.register(defineContentToolFixture({
  974. name: 'finalize',
  975. description: '',
  976. parameters: {},
  977. async execute(_args, exec) {
  978. // Steering lands while the concluding tool is still executing.
  979. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } }))
  980. exec.concludeTurn()
  981. return [{ type: 'text', text: 'final' }]
  982. },
  983. }))
  984. send(agent, 'go')
  985. await waitForIdle(ctx, agent)
  986. expect(adapter.requests).toHaveLength(2)
  987. const events = agent.session.snapshotEvents().map(event => event.type)
  988. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  989. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('late steering')
  990. const texts = adapter.requests[1]!.messages
  991. .flatMap(message => message.content)
  992. .filter(block => block.type === 'text')
  993. .map(block => block.text)
  994. expect(texts).toContain('late steering')
  995. })
  996. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  997. const adapter = new MockAdapter([textResponse('ok')])
  998. const ctx = await harness(adapter)
  999. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1000. ctx.on('agent/request', async (_payload, next) => {
  1001. const config = await next()
  1002. // The seed is frozen — config is not a mutable per-call knob; a switch
  1003. // is proposed by returning a replacement, and the loop logs it.
  1004. expect(Object.isFrozen(config)).toBe(true)
  1005. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  1006. return { ...config, model: 'other-model' }
  1007. })
  1008. send(agent, 'hi')
  1009. await waitForIdle(ctx, agent)
  1010. expect(adapter.requests[0]!.model).toBe('other-model')
  1011. // The header event records what the request ACTUALLY used — the switch is
  1012. // a reconstructable fact, not silent drift.
  1013. const headerEvent = agent.session.snapshotEvents().find(e => e.type === 'request/header')
  1014. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  1015. })
  1016. it('agent/pre-step fires once per proposed step before the step is opened', async () => {
  1017. const adapter = new MockAdapter([
  1018. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  1019. textResponse('done'),
  1020. ])
  1021. const ctx = await harness(adapter)
  1022. ctx.tools.register(defineContentToolFixture({
  1023. name: 'echo', description: 'echo', parameters: {},
  1024. async execute() { return [{ type: 'text', text: 'echoed' }] },
  1025. }))
  1026. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1027. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  1028. ctx.on('agent/pre-step', ({ agent: subject, turn, step, signal }, next) => {
  1029. if (subject === agent) fires.push({ turn, step, signal })
  1030. return next()
  1031. })
  1032. send(agent, 'go')
  1033. await waitForIdle(ctx, agent)
  1034. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  1035. { turn: 1, step: 1 },
  1036. { turn: 1, step: 2 },
  1037. ])
  1038. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  1039. })
  1040. it('agent/pre-step fires before its step boundary opens and before the request', async () => {
  1041. const adapter = new MockAdapter([textResponse('ok')])
  1042. const ctx = await harness(adapter)
  1043. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1044. let boundaryOpen = true
  1045. ctx.on('agent/pre-step', ({ agent: subject }, next) => {
  1046. if (subject === agent) boundaryOpen = subject.session.snapshotEvents().at(-1)?.type === 'step/start'
  1047. return next()
  1048. })
  1049. send(agent, 'go')
  1050. await waitForIdle(ctx, agent)
  1051. expect(boundaryOpen).toBe(false)
  1052. expect(adapter.requests).toHaveLength(1)
  1053. })
  1054. it('a throwing agent/pre-step listener fails the proposal, not the loop', async () => {
  1055. const adapter = new MockAdapter([textResponse('second turn ok')])
  1056. const ctx = await harness(adapter)
  1057. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1058. let throwOnce = true
  1059. ctx.on('agent/pre-step', (_payload, next) => {
  1060. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  1061. return next()
  1062. })
  1063. const errors: Error[] = []
  1064. ctx.on('agent/error', ({ error }) => {
  1065. if (error instanceof Error) errors.push(error)
  1066. })
  1067. send(agent, 'first')
  1068. await waitForIdle(ctx, agent)
  1069. // The first proposal failed inside a balanced turn without calling the model.
  1070. expect(errors.map(error => error.message)).toEqual(['boom in pre-step'])
  1071. expect(adapter.requests.length).toBe(0)
  1072. expect(agent.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(true)
  1073. expect(agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(true)
  1074. // The loop survived: a second prompt runs a normal completed turn.
  1075. send(agent, 'second')
  1076. await waitForIdle(ctx, agent)
  1077. expect(adapter.requests.length).toBe(1)
  1078. const lastTurnEnd = agent.session.snapshotEvents().findLast(e => e.type === 'turn/end')
  1079. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  1080. })
  1081. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  1082. const adapter = new MockAdapter(['hang'])
  1083. const ctx = await harness(adapter)
  1084. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1085. const reasons: TurnEndReason[] = []
  1086. const frames: AssistantStreamFrame[] = []
  1087. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1088. ctx.on('agent/assistant-stream', ({ frame }) => { frames.push(frame) })
  1089. send(agent, 'go')
  1090. // wait until the stream is hanging, then cancel
  1091. await new Promise(r => setTimeout(r, 30))
  1092. expect(agent.status).toBe('running')
  1093. agent.cancel({ kind: 'user' })
  1094. await waitForIdle(ctx, agent)
  1095. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  1096. const chunks = frames.filter(frame => frame.type === 'chunk')
  1097. expect(frames.at(-1)).toMatchObject({
  1098. type: 'end',
  1099. index: chunks.length,
  1100. outcome: { kind: 'committed', eventType: 'assistant/message' },
  1101. })
  1102. })
  1103. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  1104. // A single step that ends with a max-tokens finish (no tool calls): the
  1105. // turn stops by default and ends max-tokens, not completed.
  1106. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  1107. const ctx = await harness(adapter)
  1108. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1109. const reasons: TurnEndReason[] = []
  1110. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1111. send(agent, 'go')
  1112. await waitForIdle(ctx, agent)
  1113. expect(adapter.requests).toHaveLength(1)
  1114. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1115. // Assert the durable row, not only the live listener.
  1116. const turnEnd = agent.session.snapshotEvents().findLast(e => e.type === 'turn/end')
  1117. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  1118. })
  1119. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  1120. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  1121. // must be FORCED to reach step 2 which finishes normally (stop).
  1122. const adapter = new MockAdapter([
  1123. maxTokensResponse('first half'),
  1124. textResponse('second half'),
  1125. ])
  1126. const ctx = await harness(adapter)
  1127. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1128. let steps = 0
  1129. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  1130. // Force exactly one continuation (step 1 → step 2), then defer to default
  1131. // (step 2 is a plain stop with no tool calls → stops).
  1132. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  1133. if (steps < 2) {
  1134. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
  1135. }
  1136. })
  1137. const reasons: TurnEndReason[] = []
  1138. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1139. send(agent, 'go')
  1140. await waitForIdle(ctx, agent)
  1141. expect(steps).toBe(2)
  1142. expect(adapter.requests).toHaveLength(2)
  1143. expect(adapter.requests[1]!.messages.slice(1)).toEqual([
  1144. {
  1145. id: expect.any(String) as unknown,
  1146. role: 'user',
  1147. content: [{ type: 'text', text: 'go' }],
  1148. source: { kind: 'user' },
  1149. },
  1150. {
  1151. id: expect.any(String) as unknown,
  1152. role: 'assistant',
  1153. content: [{ type: 'text', text: 'first half' }],
  1154. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1155. },
  1156. {
  1157. id: expect.any(String) as unknown,
  1158. role: 'user',
  1159. content: [{ type: 'text', text: 'continue after truncation' }],
  1160. source: { kind: 'plugin', plugin: 'max-tokens-test' },
  1161. },
  1162. ])
  1163. // A max-token step is sticky: the later completed step must not
  1164. // downgrade the turn outcome.
  1165. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1166. })
  1167. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  1168. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  1169. // stop. The per-turn reason must be independent — turn 2 ends completed.
  1170. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  1171. const ctx = await harness(adapter)
  1172. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1173. const reasons: TurnEndReason[] = []
  1174. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1175. send(agent, 'first')
  1176. await waitForIdle(ctx, agent)
  1177. send(agent, 'second')
  1178. await waitForIdle(ctx, agent)
  1179. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  1180. })
  1181. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  1182. const callId = ToolCallId('c1')
  1183. const adapter = new MockAdapter([[
  1184. { type: 'block-start', index: 0, blockType: 'tool-call' },
  1185. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  1186. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  1187. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  1188. { type: 'finish', reason: { kind: 'max-tokens' } },
  1189. ]])
  1190. const ctx = await harness(adapter)
  1191. let executions = 0
  1192. ctx.tools.register(defineContentToolFixture({
  1193. name: 'echo',
  1194. description: '',
  1195. parameters: { text: { type: 'string' } },
  1196. async execute() {
  1197. executions += 1
  1198. return [{ type: 'text', text: 'should not run' }]
  1199. },
  1200. }))
  1201. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1202. const reasons: TurnEndReason[] = []
  1203. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1204. send(agent, 'go')
  1205. await waitForIdle(ctx, agent)
  1206. expect(executions).toBe(0)
  1207. expect(agent.session.snapshotEvents().some(e => e.type === 'tool/call')).toBe(false)
  1208. expect(agent.session.deriveMessages().slice(1)).toEqual([{
  1209. id: expect.any(String) as unknown,
  1210. role: 'user',
  1211. content: [{ type: 'text', text: 'go' }],
  1212. source: { kind: 'user' },
  1213. }])
  1214. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1215. // Empty content still needs an assistant/message to carry usage; derivation
  1216. // skips that host so it does not create a spurious assistant turn.
  1217. const assistantMessage = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  1218. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toMatchObject({
  1219. turn: 1,
  1220. step: 1,
  1221. message: {
  1222. id: expect.any(String) as unknown,
  1223. role: 'assistant',
  1224. content: [],
  1225. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1226. },
  1227. usage: { inputTokens: 10, outputTokens: 5 },
  1228. })
  1229. })
  1230. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  1231. // The truncated tool call is dropped from durable content, while the
  1232. // successful provider call still needs an exact replay anchor.
  1233. const callId = ToolCallId('c1')
  1234. const adapter = new MockAdapter([[
  1235. { type: 'block-start', index: 0, blockType: 'tool-call' },
  1236. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  1237. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  1238. { type: 'finish', reason: { kind: 'max-tokens' } },
  1239. ]])
  1240. const ctx = await harness(adapter)
  1241. ctx.tools.register(defineContentToolFixture({
  1242. name: 'echo',
  1243. description: '',
  1244. parameters: { text: { type: 'string' } },
  1245. async execute() { return [{ type: 'text', text: 'should not run' }] },
  1246. }))
  1247. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1248. const reasons: TurnEndReason[] = []
  1249. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1250. send(agent, 'go')
  1251. await waitForIdle(ctx, agent)
  1252. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1253. const assistant = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')!
  1254. expect(assistant.type === 'assistant/message' && assistant.data).toMatchObject({
  1255. turn: 1,
  1256. step: 1,
  1257. message: {
  1258. id: expect.any(String) as unknown,
  1259. role: 'assistant',
  1260. content: [],
  1261. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1262. },
  1263. })
  1264. expect(assistant.sourceEventSeqs).toBeUndefined()
  1265. expect(assistant.type === 'assistant/message' ? assistant.data.stream.length : 0).toBeGreaterThan(0)
  1266. expect(agent.session.deriveMessages().slice(1)).toEqual([{
  1267. id: expect.any(String) as unknown,
  1268. role: 'user',
  1269. content: [{ type: 'text', text: 'go' }],
  1270. source: { kind: 'user' },
  1271. }])
  1272. })
  1273. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  1274. // A clean content-less call stays absent from derived messages but remains
  1275. // a durable successful-call boundary for replay consumers.
  1276. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  1277. const ctx = await harness(adapter)
  1278. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1279. const reasons: TurnEndReason[] = []
  1280. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1281. send(agent, 'go')
  1282. await waitForIdle(ctx, agent)
  1283. expect(reasons).toEqual([{ kind: 'completed' }])
  1284. const assistant = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')!
  1285. expect(assistant.type === 'assistant/message' && assistant.data).toMatchObject({
  1286. turn: 1,
  1287. step: 1,
  1288. message: {
  1289. id: expect.any(String) as unknown,
  1290. role: 'assistant',
  1291. content: [],
  1292. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1293. },
  1294. })
  1295. expect(assistant.sourceEventSeqs).toBeUndefined()
  1296. expect(assistant.type === 'assistant/message' ? assistant.data.stream.length : 0).toBe(1)
  1297. expect(agent.session.deriveMessages().slice(1)).toEqual([{
  1298. id: expect.any(String) as unknown,
  1299. role: 'user',
  1300. content: [{ type: 'text', text: 'go' }],
  1301. source: { kind: 'user' },
  1302. }])
  1303. })
  1304. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  1305. const callId = ToolCallId('c1')
  1306. const adapter = new MockAdapter([[
  1307. { type: 'block-start', index: 0, blockType: 'text' },
  1308. { type: 'text-delta', index: 0, text: 'partial text' },
  1309. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  1310. { type: 'block-start', index: 1, blockType: 'tool-call' },
  1311. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  1312. {
  1313. type: 'finish',
  1314. reason: { kind: 'max-tokens' },
  1315. replayState: { response: { responseId: 'resp-1' }, blocks: ['text-meta', 'tool-meta'] },
  1316. },
  1317. ], textResponse('continued')])
  1318. const ctx = await harness(adapter)
  1319. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1320. send(agent, 'go')
  1321. await waitForIdle(ctx, agent)
  1322. send(agent, 'continue')
  1323. await waitForIdle(ctx, agent)
  1324. expect(agent.session.snapshotEvents().some(e => e.type === 'tool/call')).toBe(false)
  1325. // The follow-up request replays the truncated message with its replay
  1326. // metadata pruned in step with the dropped tool call.
  1327. expect(adapter.requests[1]?.messages[2]?.source).toEqual({
  1328. kind: 'model',
  1329. provider: 'mock',
  1330. model: 'mock',
  1331. replayState: { response: { responseId: 'resp-1' }, blocks: ['text-meta'] },
  1332. })
  1333. expect(agent.session.deriveMessages().slice(1)).toEqual([
  1334. {
  1335. id: expect.any(String) as unknown,
  1336. role: 'user',
  1337. content: [{ type: 'text', text: 'go' }],
  1338. source: { kind: 'user' },
  1339. },
  1340. {
  1341. id: expect.any(String) as unknown,
  1342. role: 'assistant',
  1343. content: [{ type: 'text', text: 'partial text' }],
  1344. source: {
  1345. kind: 'model',
  1346. provider: 'mock',
  1347. model: 'mock',
  1348. replayState: { response: { responseId: 'resp-1' }, blocks: ['text-meta'] },
  1349. },
  1350. },
  1351. {
  1352. id: expect.any(String) as unknown,
  1353. role: 'user',
  1354. content: [{ type: 'text', text: 'continue' }],
  1355. source: { kind: 'user' },
  1356. },
  1357. {
  1358. id: expect.any(String) as unknown,
  1359. role: 'assistant',
  1360. content: [{ type: 'text', text: 'continued' }],
  1361. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1362. },
  1363. ])
  1364. })
  1365. it('contains a step/end observer failure without changing continuation', async () => {
  1366. const adapter = new MockAdapter([
  1367. toolCallResponse('c1', 'echo', { text: 'x' }),
  1368. textResponse('continued after tool call'),
  1369. ])
  1370. const ctx = await harness(adapter)
  1371. ctx.tools.register(defineContentToolFixture({
  1372. name: 'echo',
  1373. description: '',
  1374. parameters: { text: { type: 'string' } },
  1375. async execute(args) {
  1376. return [{ type: 'text', text: String(args.text) }]
  1377. },
  1378. }))
  1379. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1380. let threw = false
  1381. // Post-commit session observers cannot control the loop. The tool call still
  1382. // drives the second model request, and the turn completes normally.
  1383. ctx.on('session/event', (_session, event) => {
  1384. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  1385. })
  1386. send(agent, 'go')
  1387. await waitForIdle(ctx, agent)
  1388. expect(adapter.requests).toHaveLength(2)
  1389. const turnEnd = agent.session.snapshotEvents().findLast(e => e.type === 'turn/end')
  1390. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  1391. })
  1392. it('contains a reentrant send attempted during durable inbox publication', async () => {
  1393. const adapter = new MockAdapter([textResponse('first')])
  1394. const ctx = await harness(adapter)
  1395. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1396. let nested = false
  1397. ctx.on('session/event', (session, event) => {
  1398. if (session !== agent.session || event.type !== 'agent/inbox/spliced'
  1399. || event.data.inserted.length === 0 || nested) return
  1400. nested = true
  1401. send(agent, 'queued listener message')
  1402. })
  1403. const idle = waitForIdle(ctx, agent)
  1404. send(agent, 'outer message')
  1405. await idle
  1406. const turns = agent.session.snapshotEvents().filter(event => event.type === 'turn/start')
  1407. const messages = agent.session.snapshotEvents()
  1408. .filter(event => event.type === 'user/message')
  1409. .map(event => event.data.content)
  1410. expect(turns).toHaveLength(1)
  1411. expect(messages).toEqual([[{ type: 'text', text: 'outer message' }]])
  1412. })
  1413. it('preserves independent turn sources across an adjacent microtask send', async () => {
  1414. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1415. const ctx = await harness(adapter)
  1416. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1417. const idle = waitForIdle(ctx, agent)
  1418. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
  1419. await Promise.resolve()
  1420. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
  1421. await idle
  1422. const turns = agent.session.snapshotEvents().filter(event => event.type === 'turn/start')
  1423. const sources = agent.session.snapshotEvents()
  1424. .filter(event => event.type === 'user/message')
  1425. .map(event => event.data.source)
  1426. expect(turns).toHaveLength(2)
  1427. expect(sources).toEqual([
  1428. { kind: 'user' },
  1429. { kind: 'plugin', plugin: 'test' },
  1430. ])
  1431. })
  1432. it('keeps a session-listener send after dequeue in the following turn', async () => {
  1433. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1434. const ctx = await harness(adapter)
  1435. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1436. const turns: number[] = []
  1437. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  1438. // Queue the second from the first turn's durable Assistant settlement.
  1439. let queued = false
  1440. ctx.on('session/event', (_s, event) => {
  1441. if (event.type === 'assistant/message' && !queued) {
  1442. queued = true
  1443. queueMicrotask(() => { send(agent, 'second message') })
  1444. }
  1445. })
  1446. send(agent, 'first message')
  1447. await waitForIdle(ctx, agent)
  1448. expect(turns).toEqual([1, 2])
  1449. expect(adapter.requests).toHaveLength(2)
  1450. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  1451. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  1452. })
  1453. it('keeps a model-adapter callback send in the following turn', async () => {
  1454. const agentRef: { current?: Agent } = {}
  1455. const adapter = new MockAdapter([
  1456. () => {
  1457. const agent = agentRef.current
  1458. if (agent === undefined) throw new Error('model callback ran before agent setup')
  1459. send(agent, 'model callback message')
  1460. return textResponse('first')
  1461. },
  1462. textResponse('second'),
  1463. ])
  1464. const ctx = await harness(adapter)
  1465. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1466. agentRef.current = agent
  1467. const idle = waitForIdle(ctx, agent)
  1468. send(agent, 'outer message')
  1469. await idle
  1470. const messages = agent.session.snapshotEvents()
  1471. .filter(event => event.type === 'user/message')
  1472. .map(event => event.data.content)
  1473. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(2)
  1474. expect(messages).toEqual([
  1475. [{ type: 'text', text: 'outer message' }],
  1476. [{ type: 'text', text: 'model callback message' }],
  1477. ])
  1478. })
  1479. it('records normalized model errors on the turn boundary', async () => {
  1480. const adapter = new MockAdapter([]) // script exhausted → throws
  1481. const ctx = await harness(adapter)
  1482. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1483. const errors: unknown[] = []
  1484. const reasons: TurnEndReason[] = []
  1485. ctx.on('agent/error', ({ error }) => {
  1486. errors.push(error)
  1487. })
  1488. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1489. send(agent, 'hi')
  1490. await waitForIdle(ctx, agent)
  1491. expect(errors).toHaveLength(1)
  1492. expect(errors[0]).toBeInstanceOf(LlmError)
  1493. expect((errors[0] as LlmError).failure).toEqual({
  1494. message: 'MockAdapter: script exhausted',
  1495. code: 'UNKNOWN',
  1496. })
  1497. expect(reasons[0]).toMatchObject({ kind: 'error' })
  1498. // The durable failure and live relay describe the same failed turn.
  1499. const turnEnd = agent.session.snapshotEvents().find(e => e.type === 'turn/end')
  1500. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error' })
  1501. })
  1502. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  1503. const adapter = new MockAdapter(['hang'])
  1504. const ctx = await harness(adapter)
  1505. let agent!: Agent
  1506. const fiber = await ctx.plugin(Object.assign(async (inner: Context) => {
  1507. agent = await inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1508. }, { inject: ['agentLoop'] }))
  1509. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1510. send(agent, 'go')
  1511. await new Promise(r => setTimeout(r, 30))
  1512. expect(agent.status).toBe('running')
  1513. await fiber.dispose()
  1514. await driverDone(agent)
  1515. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1516. })
  1517. it('creates agents from config on startup', async () => {
  1518. const effort = ReasoningEffortId('high')
  1519. const adapter = new MockAdapter([textResponse('from config')], {
  1520. efforts: [{ id: effort, name: 'High' }],
  1521. defaultEffort: effort,
  1522. })
  1523. const ctx = new Context()
  1524. await ctx.plugin(LlmRuntime)
  1525. await ctx.plugin(SessionStore)
  1526. await ctx.plugin(SessionProjectionRegistry)
  1527. await ctx.plugin(SystemPrompt)
  1528. await ctx.plugin(ToolRuntime)
  1529. await ctx.plugin(AgentRegistry)
  1530. await ctx.plugin(AgentLoop, {
  1531. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', reasoningEffort: effort }],
  1532. })
  1533. ctx.llm.registerAdapter(['mock'], adapter)
  1534. const agent = ctx.agents.list()[0]!
  1535. expect(agent).toBeDefined()
  1536. expect(agent.id).toBe(agent.session.id)
  1537. expect(agent.id).toMatch(/^config-agent-session-/)
  1538. expect(agent.options.model).toBe('mock')
  1539. // the agent is alive: send triggers a turn
  1540. send(agent, 'hi')
  1541. await waitForIdle(ctx, agent)
  1542. expect(adapter.requests).toHaveLength(1)
  1543. expect(adapter.requests[0]?.reasoningEffort).toBe(effort)
  1544. const header = agent.session.snapshotEvents().find(event => event.type === 'request/header')
  1545. expect(header?.type === 'request/header' && header.data.header.config.reasoningEffort).toBe(effort)
  1546. })
  1547. it('attaches config agent cwd to the fresh session header', async () => {
  1548. const ctx = new Context()
  1549. await ctx.plugin(LlmRuntime)
  1550. await ctx.plugin(SessionStore)
  1551. await ctx.plugin(SessionProjectionRegistry)
  1552. await ctx.plugin(SystemPrompt)
  1553. await ctx.plugin(ToolRuntime)
  1554. await ctx.plugin(AgentRegistry)
  1555. await ctx.plugin(AgentLoop, {
  1556. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1557. })
  1558. const agent = ctx.agents.list()[0]!
  1559. expect(agent.session.header.cwd).toBe('/work/project')
  1560. })
  1561. it('replays a session log into an identical derived history', async () => {
  1562. const adapter = new MockAdapter([
  1563. toolCallResponse('c1', 'echo', { text: 'x' }),
  1564. textResponse('done'),
  1565. ])
  1566. const ctx = await harness(adapter)
  1567. ctx.tools.register(defineContentToolFixture({
  1568. name: 'echo',
  1569. description: '',
  1570. parameters: { text: { type: 'string' } },
  1571. async execute(args) {
  1572. return [{ type: 'text', text: String(args.text) }]
  1573. },
  1574. }))
  1575. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1576. send(agent, 'run')
  1577. await waitForIdle(ctx, agent)
  1578. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.snapshotEvents()] })
  1579. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1580. // event-by-event identity of types over the inherited prefix
  1581. expect(replayed.snapshotEvents().slice(0, agent.session.seq).map(e => e.type)).toEqual(
  1582. agent.session.snapshotEvents().map(e => e.type))
  1583. expect(replayed.snapshotEvents().at(-1)?.type).toBe('session/end-seed')
  1584. })
  1585. })