loop.spec.ts 70 KB

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