loop.spec.ts 63 KB

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