compaction-loop-repro.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { toolPairingBalancedAfter, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction'
  4. import { createUserMessage, createSystemMessage, CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, resolveRetryPolicy , createMessage } from '@deepseek-ai/dsh-llm'
  5. import type { ContentBlock, GenerateOptions, LlmResolvedModelInfo, ResolvedRetryPolicy, StreamChunk } from '@deepseek-ai/dsh-llm'
  6. import { ToolCallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  7. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  10. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  12. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  13. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  14. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  15. import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic'
  16. import TokenMeter from '@deepseek-ai/dsh-token-meter'
  17. import * as LlmRetry from '@deepseek-ai/dsh-llm-retry'
  18. import { Session, SessionId, type SessionEvent, type SurfaceEvent } from '@deepseek-ai/dsh-session'
  19. /**
  20. * CBR-001 regression through the real loop. A replacement checkpoint has a high
  21. * log seq at the surface head and carries no tool pair, so both adjacent cuts
  22. * must be safe and re-compacting that checkpoint alone must succeed. This pins
  23. * surface-position semantics rather than raw-log scanning.
  24. */
  25. class ReproCompactionEngine extends BasicCompactionEngine {
  26. override async summarize(): Promise<{ summary: ContentBlock[]; provider: string; model: string }> {
  27. return {
  28. summary: [{ type: 'text', text: 'CHECKPOINT SUMMARY' }],
  29. provider: 'mock',
  30. model: 'stub',
  31. }
  32. }
  33. }
  34. /** Each call emits one tool-call until exhausted, then a final text answer. */
  35. class StepwiseToolAdapter extends LlmAdapter {
  36. calls = 0
  37. constructor(private toolSteps: number) {
  38. super()
  39. }
  40. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  41. return Promise.resolve({
  42. provider,
  43. id: model,
  44. name: model,
  45. context: { contextWindow: 400 },
  46. })
  47. }
  48. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  49. const n = this.calls
  50. this.calls += 1
  51. if (n < this.toolSteps) {
  52. const id = ToolCallId(`c${n}`)
  53. const args = `{"i":${n}}`
  54. yield { type: 'block-start', index: 0, blockType: 'text' }
  55. yield { type: 'block-end', index: 0, block: { type: 'text', text: `step ${n}` } }
  56. yield { type: 'block-start', index: 1, blockType: 'tool-call' }
  57. yield { type: 'block-end', index: 1, block: { type: 'tool-call', id, name: 'work', arguments: args } }
  58. yield { type: 'finish', reason: { kind: 'tool-calls' } }
  59. return
  60. }
  61. yield { type: 'block-start', index: 0, blockType: 'text' }
  62. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'all done' } }
  63. yield { type: 'finish', reason: { kind: 'stop' } }
  64. }
  65. }
  66. /** First conversation request overflows, then the rebuilt retry succeeds. */
  67. class OverflowRecoveryAdapter extends LlmAdapter {
  68. readonly conversationRequests: GenerateOptions[] = []
  69. readonly summaryRequests: GenerateOptions[] = []
  70. private readonly retryPolicy = resolveRetryPolicy({
  71. mode: 'normal',
  72. maxRetries: 1,
  73. backoff: { initialDelayMs: 1, maxDelayMs: 1, jitterRatio: 0 },
  74. }, 'compaction test provider retryPolicy')
  75. constructor(
  76. private readonly delivery: 'thrown' | 'in-band',
  77. private readonly transientAfterOverflow = false,
  78. ) {
  79. super()
  80. }
  81. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  82. return Promise.resolve({
  83. provider,
  84. id: model,
  85. name: model,
  86. context: { contextWindow: 128 },
  87. })
  88. }
  89. override providerRetryPolicy(_provider: string): ResolvedRetryPolicy {
  90. return this.retryPolicy
  91. }
  92. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  93. // The cache-reusing summarizer replays the conversation prefix and marks
  94. // its call only by the compaction instruction in the trailing user message.
  95. const trailing = options.messages.at(-1)?.content
  96. .map(block => (block.type === 'text' ? block.text : ''))
  97. .join('') ?? ''
  98. if (trailing.includes('acting as a compaction engine')) {
  99. this.summaryRequests.push(options)
  100. yield { type: 'block-start', index: 0, blockType: 'text' }
  101. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'RECOVERY CHECKPOINT' } }
  102. yield { type: 'finish', reason: { kind: 'stop' } }
  103. return
  104. }
  105. this.conversationRequests.push(options)
  106. if (this.conversationRequests.length === 1) {
  107. if (this.delivery === 'thrown') {
  108. throw new LlmError('request too large for model context', CONTEXT_WINDOW_EXCEEDED_CODE)
  109. }
  110. yield {
  111. type: 'finish',
  112. reason: {
  113. kind: 'error',
  114. failure: {
  115. message: 'request too large for model context',
  116. code: CONTEXT_WINDOW_EXCEEDED_CODE,
  117. },
  118. },
  119. }
  120. return
  121. }
  122. if (this.transientAfterOverflow && this.conversationRequests.length === 2) {
  123. throw new LlmError('temporary provider outage', 'SERVER')
  124. }
  125. yield { type: 'block-start', index: 0, blockType: 'text' }
  126. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'recovered' } }
  127. yield { type: 'finish', reason: { kind: 'stop' } }
  128. }
  129. }
  130. async function mountInvariants(ctx: Context): Promise<void> {
  131. await ctx.plugin(InvariantRegistry)
  132. await ctx.plugin(SessionInvariant)
  133. await ctx.plugin(AgentInvariant)
  134. await ctx.plugin(AgentLoopInvariant)
  135. }
  136. async function harness(toolSteps: number): Promise<{ ctx: Context; compact: ReproCompactionEngine }> {
  137. const ctx = new Context()
  138. await mountAgentLoopTestDependencies(ctx)
  139. await mountInvariants(ctx)
  140. await ctx.plugin(AgentLoop, { agents: [] })
  141. await ctx.plugin(TokenMeter)
  142. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  143. ctx.tools.register(defineContentToolFixture({
  144. name: 'work',
  145. description: 'does work',
  146. parameters: { i: { type: 'number' } },
  147. async execute() {
  148. return [{ type: 'text', text: 'work result' }]
  149. },
  150. }))
  151. // Small window so several tool steps cross the threshold and compaction
  152. // fires within the runaway turn after enough history can shrink.
  153. const compact = new ReproCompactionEngine(ctx, {
  154. auto: true,
  155. thresholdRatio: 0.5,
  156. retainTokens: 50,
  157. maxTokens: 8192,
  158. compactionRetries: 1,
  159. })
  160. return { ctx, compact }
  161. }
  162. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  163. return new Promise((resolve) => {
  164. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  165. if (subject === agent && status === 'idle') {
  166. dispose()
  167. resolve()
  168. }
  169. })
  170. })
  171. }
  172. function overflowHistorySeed(): readonly SessionEvent[] {
  173. const session = Session.create(SessionId('overflow-history-seed'))
  174. for (let turn = 1; turn <= 2; turn += 1) {
  175. const sentinel = turn === 1 ? 'OLD HISTORY SENTINEL' : 'RECENT HISTORY'
  176. session.append('turn/start', {
  177. turn,
  178. })
  179. session.append('user/message', createUserMessage({
  180. content: [{ type: 'text', text: `${sentinel} ${'old context '.repeat(200)}` }],
  181. source: { kind: 'user' },
  182. }), { surfaceOp: 'append' })
  183. session.append('step/start', { turn, step: 1 })
  184. session.append('assistant/message', {
  185. stream: [],
  186. turn,
  187. step: 1,
  188. message: createMessage({
  189. role: 'assistant',
  190. content: [{ type: 'text', text: `historical response ${turn} ${'detail '.repeat(200)}` }],
  191. source: {
  192. kind: 'model',
  193. ...{ provider: 'mock', model: 'mock' },
  194. },
  195. }),
  196. }, { surfaceOp: 'append' })
  197. session.append('step/end', { turn, step: 1 })
  198. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  199. }
  200. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  201. return session.snapshotEvents()
  202. }
  203. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  204. it('uses the model actually routed by agent/request for post-step pressure', async () => {
  205. const { ctx } = await harness(8)
  206. ctx.on('agent/request', async (_payload, next) => ({
  207. ...await next(), provider: 'mock', model: 'mock',
  208. }))
  209. try {
  210. const agent = await ctx.agentLoop.create(SessionId('routed-pressure'), {
  211. provider: 'unconfigured-agent-fallback',
  212. model: 'unconfigured-agent-fallback',
  213. })
  214. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do a routed multi-step task' }], source: { kind: 'user' } }))
  215. await waitForIdle(ctx, agent)
  216. expect(agent.session.requestHeader()?.config.model).toBe('mock')
  217. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  218. expect(agent.session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  219. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  220. expect(agent.session.snapshotEvents().at(-1)).toMatchObject({
  221. type: 'turn/end',
  222. data: { reason: { kind: 'completed' } },
  223. })
  224. } finally {
  225. await ctx.fiber.dispose()
  226. }
  227. })
  228. it('runs automatic pressure between the completed tool step and the next step', async () => {
  229. const { ctx } = await harness(8)
  230. try {
  231. const agent = await ctx.agentLoop.create(SessionId('post-step-order'), { provider: 'mock', model: 'mock' })
  232. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do tool work' }], source: { kind: 'user' } }))
  233. await waitForIdle(ctx, agent)
  234. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  235. const events = agent.session.snapshotEvents()
  236. const compactStart = events.find(event => event.type === 'compaction/start')
  237. expect(compactStart).toBeDefined()
  238. const precedingResult = events.findLast(event =>
  239. event.type === 'tool/result' && event.seq < compactStart!.seq,
  240. )
  241. if (precedingResult?.type !== 'tool/result') throw new Error('expected a durable tool result before compaction')
  242. const precedingStepEnd = events.find(event =>
  243. event.type === 'step/end'
  244. && event.data.step === precedingResult.data.step
  245. && event.seq > precedingResult.seq,
  246. )
  247. const nextStepStart = events.find(event =>
  248. event.type === 'step/start'
  249. && event.data.step === precedingResult.data.step + 1
  250. && event.seq > compactStart!.seq,
  251. )
  252. expect(precedingResult.seq).toBeLessThan(compactStart!.seq)
  253. expect(precedingStepEnd!.seq).toBeLessThan(compactStart!.seq)
  254. expect(compactStart!.seq).toBeLessThan(nextStepStart!.seq)
  255. } finally {
  256. await ctx.fiber.dispose()
  257. }
  258. })
  259. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  260. const { ctx } = await harness(8)
  261. try {
  262. const agent = await ctx.agentLoop.create(SessionId('repro'), { provider: 'mock', model: 'mock' })
  263. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do a long multi-step task' }], source: { kind: 'user' } }))
  264. await waitForIdle(ctx, agent)
  265. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  266. const events = agent.session.snapshotEvents()
  267. // A compaction ran: at least one checkpoint landed on the surface.
  268. const checkpoints = events.filter(
  269. (e): e is SurfaceEvent =>
  270. e.type === 'user/message'
  271. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  272. )
  273. expect(checkpoints.length).toBeGreaterThan(0)
  274. // High log position does not make a text-only checkpoint mid-step; both
  275. // its start and end cuts are balanced in surface order.
  276. const nodes = agent.session.surface.nodes
  277. for (const cp of checkpoints) {
  278. const index = nodes.indexOf(cp.seq)
  279. if (index === -1) continue // shadowed by a later checkpoint — no longer an edge.
  280. expect(toolPairingBalancedBefore(agent.session, cp.seq),
  281. `checkpoint seq ${cp.seq} must be a balanced region START`).toBe(true)
  282. expect(toolPairingBalancedAfter(agent.session, cp.seq),
  283. `checkpoint seq ${cp.seq} must be a balanced region END`).toBe(true)
  284. }
  285. } finally {
  286. await ctx.fiber.dispose()
  287. }
  288. })
  289. })
  290. describe('token pressure after loop-admitted system prompts', () => {
  291. it.each([false, true])('counts initial and replaced prompts once with retry=%s', async (retry) => {
  292. const ctx = new Context()
  293. const requests: GenerateOptions[] = []
  294. const usage = { inputTokens: 1000, cacheReadTokens: 100, outputTokens: 10 }
  295. const adapter = new class extends StepwiseToolAdapter {
  296. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  297. requests.push(options)
  298. yield { type: 'block-start', index: 0, blockType: 'text' }
  299. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'answer' } }
  300. yield { type: 'usage', usage }
  301. yield retry && requests.length === 1
  302. ? { type: 'finish', reason: { kind: 'error', failure: { code: 'SERVER', message: 'retry me' } } }
  303. : { type: 'finish', reason: { kind: 'stop' } }
  304. }
  305. }(0)
  306. try {
  307. await mountAgentLoopTestDependencies(ctx)
  308. await ctx.plugin(AgentLoop, { agents: [] })
  309. await ctx.plugin(TokenMeter)
  310. ctx.llm.registerAdapter(['mock'], adapter)
  311. let prompt = 'initial guidance '.repeat(8)
  312. ctx.systemPrompt.section({ name: 'meter-test', order: 0, complete: true, text: () => prompt })
  313. ctx.on('agent/request', async (_payload, next) => ({ ...await next(), temperature: 0.5 }))
  314. ctx.on('agent/request-error', async ({ agent, turn, step }, next) => {
  315. const action = await next()
  316. if (action !== undefined) return action
  317. const node = agent.session.surface.nodes[0]!
  318. agent.session.append('system/message', {
  319. turn,
  320. step,
  321. message: createSystemMessage('retry guidance', '@deepseek-ai/dsh-system-prompt'),
  322. }, { surfaceOp: { op: 'replace', startSeq: node, endSeq: node }, sourceEventSeqs: [node] })
  323. return { kind: 'retry' }
  324. })
  325. const agent = await ctx.agentLoop.create(SessionId('prompt-pressure'), { provider: 'mock', model: 'mock' })
  326. // Eager replay must observe the same anchor as a fresh reader of the finished log.
  327. ctx.tokenMeter.measure(agent.session)
  328. for (const nextPrompt of [prompt, 'expanded guidance '.repeat(20), 'short', '']) {
  329. prompt = nextPrompt
  330. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'question' }], source: { kind: 'user' } }))
  331. await agent.whenIdle()
  332. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  333. expect(agent.session.snapshotEvents().at(-1)).toMatchObject({
  334. type: 'turn/end', data: { reason: { kind: 'completed' } },
  335. })
  336. const measured = ctx.tokenMeter.measure(agent.session)
  337. expect(measured.baseline).toEqual({ kind: 'usage', tokens: 1110, usage })
  338. expect(measured.surfaceDeltaTokens).toBe(0)
  339. expect(measured.totalTokens).toBe(1110)
  340. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  341. const replay = Session.create(SessionId('prompt-pressure-replay'), agent.session.snapshotEvents())
  342. expect(ctx.tokenMeter.measure(replay)).toMatchObject({
  343. baseline: measured.baseline, surfaceDeltaTokens: 0, totalTokens: 1110, nodes: measured.nodes,
  344. })
  345. }
  346. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  347. const events = agent.session.snapshotEvents()
  348. const prompts = events.filter(event => event.type === 'system/message')
  349. expect(prompts[0]?.surfaceOp).toBe('append')
  350. expect(prompts.slice(1).every(event => typeof event.surfaceOp === 'object')).toBe(true)
  351. for (const event of prompts) {
  352. expect(events.find(start => start.type === 'step/start'
  353. && start.data.turn === event.data.turn && start.data.step === event.data.step)?.seq)
  354. .toBeLessThan(event.seq)
  355. }
  356. expect(requests).toHaveLength(retry ? 5 : 4)
  357. expect(requests.every(request => request.temperature === 0.5)).toBe(true)
  358. expect(events.filter(event => event.type === 'assistant/attempt')).toHaveLength(retry ? 1 : 0)
  359. expect(events.filter(event => event.type === 'step/start')).toHaveLength(4)
  360. expect(requests[0]?.messages[0]?.content).toEqual([{ type: 'text', text: 'initial guidance '.repeat(8) }])
  361. if (retry) expect(requests[1]?.messages[0]?.content).toEqual(requests[0]?.messages[0]?.content)
  362. expect(requests.at(-1)?.messages.some(message => message.role === 'system')).toBe(false)
  363. } finally {
  364. await ctx.fiber.dispose()
  365. }
  366. })
  367. })
  368. describe('context-overflow recovery across the real loop and compaction-basic', () => {
  369. it.each(['thrown', 'in-band'] as const)(
  370. 'force-compacts a %s overflow within the retried step',
  371. async (delivery) => {
  372. const ctx = new Context()
  373. const adapter = new OverflowRecoveryAdapter(delivery)
  374. await mountAgentLoopTestDependencies(ctx)
  375. await mountInvariants(ctx)
  376. await ctx.plugin(AgentLoop, { agents: [] })
  377. await ctx.plugin(TokenMeter)
  378. ctx.llm.registerAdapter(['mock'], adapter)
  379. ctx.on('agent/request', async (_payload, next) => ({
  380. ...await next(), provider: 'mock', model: 'mock',
  381. }))
  382. await ctx.plugin(BasicCompactionEngine, {
  383. thresholdRatio: 1,
  384. retainTokens: 100,
  385. maxTokens: 64,
  386. compactionRetries: 0,
  387. maxOverflowRetries: 1,
  388. })
  389. try {
  390. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  391. sessionId: SessionId(`overflow-${delivery}`),
  392. seed: overflowHistorySeed(),
  393. agentOptions: {
  394. provider: 'unconfigured-agent-fallback',
  395. model: 'unconfigured-agent-fallback',
  396. },
  397. })
  398. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } }))
  399. await agent.whenIdle()
  400. expect(adapter.conversationRequests).toHaveLength(2)
  401. expect(adapter.summaryRequests).toHaveLength(1)
  402. const instruction = adapter.summaryRequests[0]!.messages.at(-1)?.content
  403. .map(block => (block.type === 'text' ? block.text : ''))
  404. .join('') ?? ''
  405. expect(instruction).toContain('Write concise English engineering prose.')
  406. expect(instruction).toContain('numeric values, function signatures, and syntax fragments.')
  407. expect(JSON.stringify(adapter.conversationRequests[0]!.messages)).toContain('OLD HISTORY SENTINEL')
  408. const retry = JSON.stringify(adapter.conversationRequests[1]!.messages)
  409. expect(retry).toContain('RECOVERY CHECKPOINT')
  410. expect(retry).not.toContain('OLD HISTORY SENTINEL')
  411. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  412. const events = agent.session.snapshotEvents()
  413. const stepStart = events.find(event =>
  414. event.type === 'step/start' && event.data.turn === 3 && event.data.step === 1,
  415. )!
  416. const stepEnd = events.find(event =>
  417. event.type === 'step/end' && event.data.turn === 3 && event.data.step === 1,
  418. )!
  419. const compaction = events.filter(event =>
  420. event.type === 'compaction/start'
  421. || event.type === 'compaction/summary'
  422. || event.type === 'compaction/end',
  423. )
  424. expect(compaction.map(event => event.type)).toEqual([
  425. 'compaction/start',
  426. 'compaction/summary',
  427. 'compaction/end',
  428. ])
  429. expect(compaction.every(event =>
  430. event.seq > stepStart.seq && event.seq < stepEnd.seq,
  431. )).toBe(true)
  432. expect(events.filter(event => event.type === 'turn/start').slice(-1).map(event => event.data.turn))
  433. .toEqual([3])
  434. expect(events.filter(event => event.type === 'step/start' && event.data.turn === 3))
  435. .toHaveLength(1)
  436. expect(events.at(-1)).toMatchObject({
  437. type: 'turn/end',
  438. data: { reason: { kind: 'completed' } },
  439. })
  440. } finally {
  441. await ctx.fiber.dispose()
  442. }
  443. },
  444. )
  445. it('keeps context-overflow and transient retry budgets independent in one sequence', async () => {
  446. const ctx = new Context()
  447. const adapter = new OverflowRecoveryAdapter('thrown', true)
  448. await mountAgentLoopTestDependencies(ctx)
  449. await mountInvariants(ctx)
  450. await ctx.plugin(LlmRetry)
  451. await ctx.plugin(AgentLoop, { agents: [] })
  452. await ctx.plugin(TokenMeter)
  453. ctx.llm.registerAdapter(['mock'], adapter)
  454. await ctx.plugin(BasicCompactionEngine, {
  455. thresholdRatio: 1,
  456. retainTokens: 100,
  457. maxTokens: 64,
  458. compactionRetries: 0,
  459. maxOverflowRetries: 1,
  460. })
  461. try {
  462. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  463. sessionId: SessionId('alternating-recovery'),
  464. seed: overflowHistorySeed(),
  465. agentOptions: { provider: 'mock', model: 'mock' },
  466. })
  467. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } }))
  468. await agent.whenIdle()
  469. expect(adapter.conversationRequests).toHaveLength(3)
  470. expect(adapter.summaryRequests).toHaveLength(1)
  471. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  472. expect(agent.session.snapshotEvents().filter(event => event.type === 'llm/retry').map(event => event.data))
  473. .toEqual([expect.objectContaining({ turn: 3, step: 1, retry: 1, failure: { message: 'temporary provider outage', code: 'SERVER' } })])
  474. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  475. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start').slice(-1).map(event => event.data.turn))
  476. .toEqual([3])
  477. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  478. expect(agent.session.snapshotEvents().at(-1)).toMatchObject({
  479. type: 'turn/end',
  480. data: { reason: { kind: 'completed' } },
  481. })
  482. } finally {
  483. await ctx.fiber.dispose()
  484. }
  485. })
  486. })