loop.spec.ts 62 KB

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