compaction-basic.spec.ts 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167
  1. import { describe, expect, expectTypeOf, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { AttachmentId } from '@deepseek-ai/dsh-attachment'
  4. import BasicCompactionEngine from '@deepseek-ai/dsh-compaction-basic'
  5. import type { BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic'
  6. import { selectCompactableRange } from '@deepseek-ai/dsh-compaction-basic/src/region.ts'
  7. import { frameSummary } from '@deepseek-ai/dsh-compaction-basic/src/summarizer.ts'
  8. import type { SummarizationInput, SummaryResult } from '@deepseek-ai/dsh-compaction-basic/src/summarizer.ts'
  9. import { CompactionId, toolPairingBalancedAfter, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction'
  10. import {
  11. resolveCompactSpec,
  12. resolveConfig,
  13. resolveTargetPolicy,
  14. } from '@deepseek-ai/dsh-compaction-basic/src/config.ts'
  15. import type { CompactionResult } from '@deepseek-ai/dsh-compaction'
  16. import LlmRuntime, { createUserMessage, ToolCallId, CONTEXT_WINDOW_EXCEEDED_CODE, createSystemMessage, createToolResultMessage, LlmAdapter , createMessage } from '@deepseek-ai/dsh-llm'
  17. import type {
  18. ContentBlock,
  19. GenerateOptions,
  20. LlmFailure,
  21. LlmResolvedModelInfo,
  22. Message,
  23. StreamChunk,
  24. TokenUsage,
  25. } from '@deepseek-ai/dsh-llm'
  26. import SessionStore, { Session, SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
  27. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  28. import TokenMeter from '@deepseek-ai/dsh-token-meter'
  29. import { agentEvents, type Agent, type RequestErrorAction } from '@deepseek-ai/dsh-agent'
  30. import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner'
  31. const SIGNAL = new AbortController().signal
  32. const MODEL = 'test-model'
  33. class ContextAdapter extends LlmAdapter {
  34. constructor(private readonly contextWindow: number) {
  35. super()
  36. }
  37. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  38. return Promise.resolve({
  39. provider,
  40. id: model,
  41. name: model,
  42. context: { contextWindow: this.contextWindow },
  43. })
  44. }
  45. override async * stream(): AsyncIterable<StreamChunk> {
  46. yield { type: 'finish', reason: { kind: 'stop' } }
  47. }
  48. }
  49. class RoutedContextAdapter extends LlmAdapter {
  50. constructor(private readonly windows: Readonly<Record<string, number>>) {
  51. super()
  52. }
  53. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  54. const contextWindow = this.windows[provider]
  55. return Promise.resolve({
  56. provider,
  57. id: model,
  58. name: model,
  59. ...contextWindow === undefined ? {} : { context: { contextWindow } },
  60. })
  61. }
  62. override async * stream(): AsyncIterable<StreamChunk> {
  63. yield { type: 'finish', reason: { kind: 'stop' } }
  64. }
  65. }
  66. function createContext(contextWindow = 1_000): Context {
  67. const ctx = new Context()
  68. void new LlmRuntime(ctx)
  69. // The registry is a required injection of TokenMeter (its three
  70. // projection units register in the constructor); mount it synchronously.
  71. new SessionProjectionRegistry(ctx)
  72. void new TokenMeter(ctx)
  73. ctx.llm.registerAdapter([MODEL, 'actual', 'unlisted-provider'], new ContextAdapter(contextWindow))
  74. return ctx
  75. }
  76. function agent(session: Session, model?: string): Agent {
  77. return {
  78. session,
  79. options: model === undefined ? {} : { provider: model, model },
  80. } as Agent
  81. }
  82. /** Flatten every text fragment the summarizer received, recursing tool-result blocks. */
  83. function summarizedText(input: SummarizationInput): string {
  84. const collect = (blocks: readonly ContentBlock[]): string =>
  85. blocks.map(block =>
  86. block.type === 'text' ? block.text
  87. : block.type === 'tool-result' ? collect(block.content)
  88. : '').join('\n')
  89. return input.messages.map(message => collect(message.content)).join('\n')
  90. }
  91. /** A minimal replayed prefix carrying one user message of the given text. */
  92. function promptInput(text: string): SummarizationInput {
  93. return { messages: [createUserMessage({
  94. content: [{ type: 'text', text }],
  95. source: { kind: 'plugin', plugin: 'test' },
  96. })] }
  97. }
  98. const SYSTEM_PROMPT_PLUGIN = '@deepseek-ai/dsh-system-prompt'
  99. /**
  100. * Closed two-message turns followed by one open turn for durable compaction events.
  101. * A `system` text puts a `system/message` at surface node 0 before turn 1's user message.
  102. */
  103. function conversation(turns = 4, text = 'fixture '.repeat(40).trim(), system?: string): Session {
  104. const session = Session.create(SessionId(`conversation-${turns}`))
  105. for (let turn = 1; turn <= turns; turn += 1) {
  106. session.append('turn/start', { turn })
  107. if (turn === 1 && system !== undefined) {
  108. session.append('system/message', {
  109. turn,
  110. step: 1,
  111. message: createSystemMessage(system, SYSTEM_PROMPT_PLUGIN),
  112. }, { surfaceOp: 'append' })
  113. }
  114. session.append('user/message', createUserMessage({
  115. content: [{ type: 'text', text: `${text} user ${turn}` }],
  116. source: { kind: 'user' },
  117. }), { surfaceOp: 'append' })
  118. session.append('step/start', { turn, step: 1 })
  119. if (turn === 1) {
  120. session.append('request/header', {
  121. header: { config: { provider: MODEL, model: MODEL } },
  122. reason: 'initial',
  123. })
  124. }
  125. session.append('assistant/message', {
  126. stream: [],
  127. turn,
  128. step: 1,
  129. message: createMessage({
  130. role: 'assistant',
  131. content: [{ type: 'text', text: `${text} assistant ${turn}` }],
  132. source: {
  133. kind: 'model',
  134. ...{ provider: MODEL, model: MODEL },
  135. },
  136. }),
  137. }, { surfaceOp: 'append' })
  138. session.append('step/end', { turn, step: 1 })
  139. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  140. }
  141. session.append('turn/start', {
  142. turn: turns + 1,
  143. })
  144. return session
  145. }
  146. function toolConversation(): Session {
  147. const session = Session.create(SessionId('tools'))
  148. for (let turn = 1; turn <= 3; turn += 1) {
  149. const callId = ToolCallId(`call-${turn}`)
  150. session.append('turn/start', { turn })
  151. session.append('user/message', createUserMessage({
  152. content: [{ type: 'text', text: `request ${turn} `.repeat(300) }],
  153. source: { kind: 'user' },
  154. }), { surfaceOp: 'append' })
  155. session.append('step/start', { turn, step: 1 })
  156. if (turn === 1) {
  157. session.append('request/header', {
  158. header: { config: { provider: MODEL, model: MODEL } },
  159. reason: 'initial',
  160. })
  161. }
  162. session.append('assistant/message', {
  163. stream: [],
  164. turn,
  165. step: 1,
  166. message: createMessage({
  167. role: 'assistant',
  168. content: [
  169. { type: 'text', text: `calling ${turn} `.repeat(300) },
  170. { type: 'tool-call', id: callId, name: 'read', arguments: '{}' },
  171. ],
  172. source: {
  173. kind: 'model',
  174. ...{ provider: MODEL, model: MODEL },
  175. },
  176. }),
  177. }, { surfaceOp: 'append' })
  178. session.append('tool/call', { turn, step: 1, callId, name: 'read', arguments: '{}' })
  179. session.append('tool/result', {
  180. turn,
  181. step: 1,
  182. message: createToolResultMessage({
  183. callId,
  184. content: [{ type: 'text', text: `result ${turn} `.repeat(300) }],
  185. isError: false,
  186. }),
  187. }, { surfaceOp: 'append' })
  188. session.append('step/end', { turn, step: 1 })
  189. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  190. }
  191. session.append('turn/start', { turn: 4 })
  192. return session
  193. }
  194. /** One closed routed tool step followed by an open turn for rewrite events. */
  195. function oversizedToolResult(chars = 3_000, withCompactablePrompt = false): Session {
  196. const session = Session.create(SessionId(`oversized-tool-${chars}`))
  197. const callId = ToolCallId('oversized')
  198. session.append('turn/start', { turn: 1 })
  199. if (withCompactablePrompt) {
  200. session.append('user/message', createUserMessage({
  201. content: [{ type: 'text', text: 'older history '.repeat(200) }],
  202. source: { kind: 'user' },
  203. }), { surfaceOp: 'append' })
  204. }
  205. session.append('step/start', { turn: 1, step: 1 })
  206. session.append('request/header', {
  207. header: { config: { provider: MODEL, model: MODEL } },
  208. reason: 'initial',
  209. })
  210. session.append('assistant/message', {
  211. stream: [],
  212. turn: 1,
  213. step: 1,
  214. message: createMessage({
  215. role: 'assistant',
  216. content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
  217. source: {
  218. kind: 'model',
  219. ...{ provider: MODEL, model: MODEL },
  220. },
  221. }),
  222. }, { surfaceOp: 'append' })
  223. session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
  224. session.append('tool/result', {
  225. turn: 1,
  226. step: 1,
  227. message: createToolResultMessage({
  228. callId,
  229. content: [{ type: 'text', text: 'X'.repeat(chars) }],
  230. isError: false,
  231. }),
  232. meta: { presentation: 'preserved' },
  233. }, { surfaceOp: 'append' })
  234. session.append('step/end', { turn: 1, step: 1 })
  235. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  236. session.append('turn/start', { turn: 2 })
  237. return session
  238. }
  239. class TestCompactionEngine extends BasicCompactionEngine {
  240. summary: ContentBlock[] = [{ type: 'text', text: 'small checkpoint' }]
  241. rawOutput: ContentBlock[] | undefined
  242. usage: TokenUsage | undefined
  243. summaryProvider = 'summary-provider'
  244. summaryModel = 'summary-model'
  245. error: unknown
  246. mutateDuringSummary: (() => void) | undefined
  247. calls: Array<{ input: SummarizationInput; signal: AbortSignal | undefined }> = []
  248. override async summarize(
  249. input: SummarizationInput,
  250. _agent: Agent,
  251. signal?: AbortSignal,
  252. ): Promise<{
  253. summary: ContentBlock[]
  254. rawOutput?: ContentBlock[]
  255. provider: string
  256. model: string
  257. maxTokens?: number
  258. usage?: TokenUsage
  259. }> {
  260. this.calls.push({ input, signal })
  261. this.mutateDuringSummary?.()
  262. if (this.error !== undefined) throw this.error
  263. return {
  264. summary: this.summary,
  265. ...this.rawOutput === undefined ? {} : { rawOutput: this.rawOutput },
  266. provider: this.summaryProvider,
  267. model: this.summaryModel,
  268. maxTokens: 123,
  269. ...this.usage === undefined ? {} : { usage: this.usage },
  270. }
  271. }
  272. }
  273. function service(
  274. config: BasicCompactionConfig = { auto: false },
  275. ctx = createContext(),
  276. ): TestCompactionEngine {
  277. return new TestCompactionEngine(ctx, config)
  278. }
  279. async function compactIfNeeded(
  280. compact: BasicCompactionEngine,
  281. session: Session,
  282. trigger: 'pressure' | 'context-overflow' = 'pressure',
  283. model: string | undefined = MODEL,
  284. ): Promise<CompactionResult | null> {
  285. return compact.compactIfNeeded(agent(session, model), trigger, SIGNAL)
  286. }
  287. describe('compact configuration and defaults', () => {
  288. it('uses low-friction service-wide defaults', () => {
  289. const resolved = resolveConfig({})
  290. expect(resolved).toEqual({
  291. thresholdRatio: 0.8,
  292. retainRatio: 0.16,
  293. summarizationProvider: '',
  294. summarizationModel: '',
  295. maxTokens: 8192,
  296. compactionRetries: 1,
  297. maxOverflowRetries: 1,
  298. modelPolicies: [],
  299. auto: true,
  300. })
  301. expect(Object.isFrozen(resolved)).toBe(true)
  302. })
  303. it('resolves threshold and retention overrides independently', () => {
  304. const thresholdOnly = resolveConfig({
  305. thresholdRatio: 0.5,
  306. })
  307. expect(thresholdOnly).toMatchObject({
  308. thresholdRatio: 0.5,
  309. retainRatio: 0.16,
  310. })
  311. const retentionOnly = resolveConfig({
  312. retainTokens: 70,
  313. })
  314. expect(retentionOnly).toMatchObject({
  315. thresholdRatio: 0.8,
  316. retainTokens: 70,
  317. })
  318. expect(retentionOnly).not.toHaveProperty('retainRatio')
  319. })
  320. it('merges exact provider/model policy overrides and scales ratios per model', () => {
  321. const config = resolveConfig({
  322. thresholdRatio: 0.8,
  323. retainRatio: 0.1,
  324. modelPolicies: [{
  325. provider: 'small-provider',
  326. model: 'shared-id',
  327. thresholdRatio: 0.5,
  328. retainTokens: 120,
  329. }],
  330. })
  331. const small = resolveTargetPolicy(config, {
  332. provider: 'small-provider',
  333. model: 'shared-id',
  334. })
  335. const otherProvider = resolveTargetPolicy(config, {
  336. provider: 'large-provider',
  337. model: 'shared-id',
  338. })
  339. expect(resolveCompactSpec(small, 1_000)).toMatchObject({
  340. thresholdTokens: 500,
  341. retainTokens: 120,
  342. })
  343. expect(resolveCompactSpec(otherProvider, 2_000)).toMatchObject({
  344. thresholdTokens: 1_600,
  345. retainTokens: 200,
  346. })
  347. const ratioOverride = resolveTargetPolicy(resolveConfig({
  348. retainTokens: 200,
  349. modelPolicies: [{
  350. provider: 'ratio-provider',
  351. model: 'ratio-model',
  352. thresholdRatio: 0.6,
  353. retainRatio: 0.2,
  354. summarizationProvider: 'summary-provider',
  355. summarizationModel: 'summary-model',
  356. maxTokens: 512,
  357. compactionRetries: 2,
  358. maxOverflowRetries: 3,
  359. }],
  360. }), { provider: 'ratio-provider', model: 'ratio-model' })
  361. expect(resolveCompactSpec(ratioOverride, 2_000)).toMatchObject({
  362. thresholdTokens: 1_200,
  363. retainTokens: 400,
  364. summarizationProvider: 'summary-provider',
  365. summarizationModel: 'summary-model',
  366. maxTokens: 512,
  367. compactionRetries: 2,
  368. maxOverflowRetries: 3,
  369. })
  370. })
  371. it('inherits, clears, and replaces the summarization target as a pair', () => {
  372. const config = resolveConfig({
  373. summarizationProvider: 'default-provider',
  374. summarizationModel: 'default-model',
  375. modelPolicies: [
  376. { provider: 'inherit-provider', model: MODEL },
  377. {
  378. provider: 'clear-provider',
  379. model: MODEL,
  380. summarizationProvider: '',
  381. summarizationModel: '',
  382. },
  383. {
  384. provider: 'replace-provider',
  385. model: MODEL,
  386. summarizationProvider: 'replacement-provider',
  387. summarizationModel: 'replacement-model',
  388. },
  389. ],
  390. })
  391. expect(resolveTargetPolicy(config, { provider: 'inherit-provider', model: MODEL }))
  392. .toMatchObject({
  393. summarizationProvider: 'default-provider',
  394. summarizationModel: 'default-model',
  395. })
  396. expect(resolveTargetPolicy(config, { provider: 'clear-provider', model: MODEL }))
  397. .toMatchObject({ summarizationProvider: '', summarizationModel: '' })
  398. expect(resolveTargetPolicy(config, { provider: 'replace-provider', model: MODEL }))
  399. .toMatchObject({
  400. summarizationProvider: 'replacement-provider',
  401. summarizationModel: 'replacement-model',
  402. })
  403. })
  404. it('validates common values and pressure-policy invariants', () => {
  405. const bad = [
  406. [{ maxTokens: 0 }, /maxTokens/],
  407. [{ compactionRetries: -1 }, /compactionRetries/],
  408. [{ maxOverflowRetries: -1 }, /maxOverflowRetries/],
  409. [{ auto: 'yes' }, /auto must be a boolean/],
  410. [{ summarizationProvider: 1 }, /summarizationProvider must be a string/],
  411. [{ summarizationModel: 1 }, /summarizationModel must be a string/],
  412. [{ summarizationProvider: MODEL }, /must be set together/],
  413. [{ summarizationModel: MODEL }, /must be set together/],
  414. [{ summarizationProvider: '' }, /must be set together/],
  415. [{ summarizationModel: '' }, /must be set together/],
  416. [{ thresholdRatio: 0 }, /number in \(0, 1\]/],
  417. [{ thresholdRatio: 1.1 }, /number in \(0, 1\]/],
  418. [{ retainRatio: 0.9 }, /retainRatio \(0.9\) must be less than the resolved thresholdRatio \(0.8\)/],
  419. [{ thresholdRatio: 0.1 }, /retainRatio \(0.16\) must be less than the resolved thresholdRatio \(0.1\)/],
  420. [{ retainTokens: -1 }, /non-negative integer/],
  421. [{ retainRatio: 0.2, retainTokens: 100 }, /mutually exclusive/],
  422. [{ modelPolicies: {} }, /modelPolicies must be an array/],
  423. [{ modelPolicies: [1] }, /modelPolicies\[0\] must be an object/],
  424. [{ modelPolicies: [null] }, /modelPolicies\[0\] must be an object/],
  425. [{ modelPolicies: [[]] }, /modelPolicies\[0\] must be an object/],
  426. [{ modelPolicies: [{ provider: 1, model: MODEL }] }, /provider must be a non-empty string/],
  427. [{ modelPolicies: [{ provider: '', model: MODEL }] }, /provider must be a non-empty string/],
  428. [{ modelPolicies: [{ provider: MODEL, model: 1 }] }, /model must be a non-empty string/],
  429. [{ modelPolicies: [{ provider: MODEL, model: '' }] }, /model must be a non-empty string/],
  430. [{ modelPolicies: [{ provider: MODEL, model: MODEL, summarizationProvider: 1 }] }, /summarizationProvider must be a string/],
  431. [{
  432. summarizationProvider: 'default-provider',
  433. summarizationModel: 'default-model',
  434. modelPolicies: [{ provider: MODEL, model: MODEL, summarizationModel: '' }],
  435. }, /modelPolicies\[0\].*must be set together/],
  436. [{
  437. summarizationProvider: 'default-provider',
  438. summarizationModel: 'default-model',
  439. modelPolicies: [{ provider: MODEL, model: MODEL, summarizationProvider: '' }],
  440. }, /modelPolicies\[0\].*must be set together/],
  441. [{ modelPolicies: [{ provider: MODEL, model: MODEL, retainRatio: 0.2, retainTokens: 100 }] }, /mutually exclusive/],
  442. [
  443. { modelPolicies: [{ provider: MODEL, model: MODEL, thresholdRatio: 0.1 }] },
  444. /modelPolicies\[0\]: retainRatio \(0.16\).*thresholdRatio \(0.1\)/,
  445. ],
  446. [
  447. { modelPolicies: [{ provider: MODEL, model: MODEL, retainRatio: 0.9 }] },
  448. /modelPolicies\[0\]: retainRatio \(0.9\).*thresholdRatio \(0.8\)/,
  449. ],
  450. [{ modelPolicies: [{ provider: MODEL, model: MODEL }, { provider: MODEL, model: MODEL }] }, /duplicate model policy/],
  451. [{ models: { [MODEL]: { retainTokens: 10 } } }, /BasicCompactionConfig: unknown key "models"/],
  452. [{ thresholdRato: 0.5 }, /BasicCompactionConfig: unknown key "thresholdRato"/],
  453. ] as Array<[unknown, RegExp]>
  454. for (const [config, pattern] of bad) {
  455. expect(() => resolveConfig(config as BasicCompactionConfig)).toThrow(pattern)
  456. }
  457. const invalidPressure = resolveTargetPolicy(resolveConfig({
  458. thresholdRatio: 0.5,
  459. retainTokens: 500,
  460. }), { provider: MODEL, model: MODEL })
  461. expect(() => resolveCompactSpec(invalidPressure, 1_000)).toThrow(/less than threshold/)
  462. expect(() => resolveCompactSpec(invalidPressure, 1.5)).toThrow(/positive integer/)
  463. expect(() => resolveCompactSpec(invalidPressure, 0)).toThrow(/positive integer/)
  464. })
  465. })
  466. describe('pressure measurement and retention', () => {
  467. const compactConfig: BasicCompactionConfig = {
  468. auto: false,
  469. thresholdRatio: 0.5,
  470. retainTokens: 180,
  471. }
  472. it('skips when no durable routed model exists instead of using AgentOptions fallback', async () => {
  473. const compact = service(compactConfig)
  474. const session = Session.create(SessionId('headerless'))
  475. session.append('turn/start', { turn: 1 })
  476. await expect(compact.compactIfNeeded(agent(session, MODEL), 'pressure', SIGNAL))
  477. .resolves.toBeNull()
  478. expect(compact.calls).toHaveLength(0)
  479. })
  480. it('meters an unlisted model when its provider adapter supplies context metadata', async () => {
  481. const compact = service(compactConfig)
  482. const session = conversation()
  483. session.append('request/header', {
  484. header: { config: { provider: 'unlisted-provider', model: 'unlisted-model' } },
  485. reason: 'resume',
  486. })
  487. await expect(compactIfNeeded(compact, session))
  488. .resolves.not.toBeNull()
  489. })
  490. it('forwards turn cancellation to proactive model metadata resolution', async () => {
  491. const ctx = createContext()
  492. const resolveModelInfo = vi.spyOn(ctx.llm, 'resolveModelInfo')
  493. const compact = service(compactConfig, ctx)
  494. const session = conversation()
  495. const signal = new AbortController().signal
  496. await expect(compact.compactIfNeeded(agent(session, MODEL), 'pressure', signal))
  497. .resolves.not.toBeNull()
  498. expect(resolveModelInfo).toHaveBeenCalledWith(MODEL, MODEL, signal)
  499. })
  500. it('re-resolves capacity after a same-model-id provider switch in one session', async () => {
  501. const ctx = new Context()
  502. void new LlmRuntime(ctx)
  503. new SessionProjectionRegistry(ctx)
  504. void new TokenMeter(ctx)
  505. ctx.llm.registerAdapter(['large', 'small'], new RoutedContextAdapter({
  506. large: 10_000,
  507. small: 1_000,
  508. }))
  509. const compact = service({
  510. auto: false,
  511. thresholdRatio: 0.5,
  512. retainRatio: 0.1,
  513. }, ctx)
  514. const session = conversation(4)
  515. session.append('request/header', {
  516. header: { config: { provider: 'large', model: 'shared-id' } },
  517. reason: 'resume',
  518. })
  519. await expect(compactIfNeeded(compact, session)).resolves.toBeNull()
  520. session.append('request/header', {
  521. header: { config: { provider: 'small', model: 'shared-id' } },
  522. reason: 'change',
  523. })
  524. await expect(compactIfNeeded(compact, session)).resolves.not.toBeNull()
  525. })
  526. it('requires capacity only for proactive pressure, not provider-confirmed overflow', async () => {
  527. const ctx = new Context()
  528. void new LlmRuntime(ctx)
  529. new SessionProjectionRegistry(ctx)
  530. void new TokenMeter(ctx)
  531. ctx.llm.registerAdapter(['unknown-context'], new ContextAdapter(1_000))
  532. vi.spyOn(ctx.llm, 'resolveModelInfo').mockImplementation((provider, model) => Promise.resolve({
  533. provider,
  534. id: model,
  535. name: model,
  536. }))
  537. const compact = service(compactConfig, ctx)
  538. const session = conversation(4)
  539. session.append('request/header', {
  540. header: { config: { provider: 'unknown-context', model: 'model' } },
  541. reason: 'resume',
  542. })
  543. await expect(compactIfNeeded(compact, session, 'pressure'))
  544. .rejects.toThrow(/no context capacity for unknown-context\/model/)
  545. await expect(compactIfNeeded(compact, session, 'context-overflow'))
  546. .resolves.not.toBeNull()
  547. })
  548. it('declines forced overflow when the whole surface is one indivisible tool pair', async () => {
  549. const compact = service(compactConfig)
  550. const session = Session.create(SessionId('single-tool-pair'))
  551. const callId = ToolCallId('single-call')
  552. session.append('turn/start', { turn: 1 })
  553. session.append('step/start', { turn: 1, step: 1 })
  554. session.append('request/header', {
  555. header: { config: { provider: MODEL, model: MODEL } },
  556. reason: 'initial',
  557. })
  558. session.append('assistant/message', {
  559. stream: [],
  560. turn: 1,
  561. step: 1,
  562. message: createMessage({
  563. role: 'assistant',
  564. content: [{ type: 'tool-call', id: callId, name: 'read', arguments: '{}' }],
  565. source: {
  566. kind: 'model',
  567. ...{ provider: MODEL, model: MODEL },
  568. },
  569. }),
  570. }, { surfaceOp: 'append' })
  571. session.append('tool/call', { turn: 1, step: 1, callId, name: 'read', arguments: '{}' })
  572. session.append('tool/result', {
  573. turn: 1,
  574. step: 1,
  575. message: createToolResultMessage({
  576. callId,
  577. content: [{ type: 'text', text: 'result' }],
  578. isError: false,
  579. }),
  580. }, { surfaceOp: 'append' })
  581. session.append('step/end', { turn: 1, step: 1 })
  582. const generation = session.surface.replaceGeneration
  583. await expect(compactIfNeeded(compact, session, 'context-overflow')).resolves.toBeNull()
  584. expect(session.surface.replaceGeneration).toBe(generation)
  585. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  586. expect(session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  587. })
  588. it('does nothing below threshold and compacts a priced head above threshold', async () => {
  589. const compact = service(compactConfig)
  590. expect(await compactIfNeeded(compact, conversation(2))).toBeNull()
  591. const session = conversation(4)
  592. const head = session.surface.nodes[0]!
  593. const result = await compactIfNeeded(compact, session)
  594. expect(result).not.toBeNull()
  595. expect(result?.shadowedSeqs[0]).toBe(head)
  596. expect(result?.shadowedSeqs.length).toBeGreaterThan(2)
  597. expect(session.surface.nodes.length).toBeLessThan(8)
  598. })
  599. it('starts the range after a system head and keeps that node at surface position 0', async () => {
  600. const ctx = createContext()
  601. const compact = service(compactConfig, ctx)
  602. const session = conversation(4, undefined, 'SYSTEM HEAD')
  603. const [head, firstUser] = session.surface.nodes
  604. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  605. expect(session.eventAt(head!)?.type).toBe('system/message')
  606. const range = selectCompactableRange(session, ctx.tokenMeter.measure(session), compactConfig.retainTokens!)
  607. expect(range?.start).toBe(firstUser)
  608. const result = await compactIfNeeded(compact, session)
  609. expect(result).not.toBeNull()
  610. expect(result?.shadowedSeqs).not.toContain(head)
  611. expect(result?.shadowedSeqs[0]).toBe(firstUser)
  612. expect(session.surface.nodes[0]).toBe(head)
  613. expect(session.deriveMessages()[0]).toMatchObject({
  614. role: 'system',
  615. content: [{ type: 'text', text: 'SYSTEM HEAD' }],
  616. })
  617. expect(compact.calls[0]!.input.messages[0]).toEqual(session.deriveMessages()[0])
  618. expect(compact.calls[0]!.input.messages.filter(message => message.role === 'system')).toHaveLength(1)
  619. })
  620. it('declines when only the system head precedes the retained tail', () => {
  621. const ctx = createContext()
  622. const session = conversation(1, undefined, 'SYSTEM HEAD')
  623. const priced = ctx.tokenMeter.measure(session)
  624. const [, user, assistant] = priced.nodes
  625. expect(priced.nodes).toHaveLength(3)
  626. expect(selectCompactableRange(session, priced, user!.tokens + assistant!.tokens)).toBeNull()
  627. })
  628. it('counts the durable routed request envelope without putting it on the surface', async () => {
  629. const compact = service({
  630. auto: false,
  631. thresholdRatio: 0.9,
  632. retainTokens: 50,
  633. })
  634. const session = conversation(2, 'x'.repeat(600))
  635. expect(await compactIfNeeded(compact, session)).toBeNull()
  636. session.append('request/header', {
  637. header: {
  638. config: { provider: MODEL, model: MODEL },
  639. tools: [{ name: 'bulk', description: 's'.repeat(2_000), parameters: { type: 'object' } }],
  640. },
  641. reason: 'resume',
  642. })
  643. const result = await compactIfNeeded(compact, session)
  644. expect(result).not.toBeNull()
  645. })
  646. it('uses the latest logged request envelope without an AgentOptions override', async () => {
  647. const ctx = createContext()
  648. const compact = service({
  649. auto: false,
  650. thresholdRatio: 0.5,
  651. retainTokens: 180,
  652. }, ctx)
  653. const session = conversation(4)
  654. session.append('request/header', {
  655. header: { config: { provider: 'actual', model: 'actual' } },
  656. reason: 'initial',
  657. })
  658. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  659. const result = await compactIfNeeded(compact, session, 'pressure', 'fallback')
  660. expect(result).not.toBeNull()
  661. expect(session.requestHeader()?.config.model).toBe('actual')
  662. expect(measure.mock.calls[0]).toEqual([session])
  663. })
  664. it('declines when envelope pressure is high but the surface has no compactable range', async () => {
  665. const compact = service(compactConfig)
  666. const bulkTools = [{ name: 'bulk', description: 'x'.repeat(100_000), parameters: { type: 'object' } }]
  667. const empty = Session.create(SessionId('empty'))
  668. empty.append('turn/start', { turn: 1 })
  669. empty.append('request/header', {
  670. header: { config: { provider: MODEL, model: MODEL }, tools: bulkTools },
  671. reason: 'initial',
  672. })
  673. expect(await compactIfNeeded(compact, empty)).toBeNull()
  674. const retained = conversation(1)
  675. retained.append('request/header', {
  676. header: { config: { provider: MODEL, model: MODEL }, tools: bulkTools },
  677. reason: 'resume',
  678. })
  679. expect(await compactIfNeeded(compact, retained)).toBeNull()
  680. })
  681. it('uses one unified measurement for each pressure-and-retention decision', async () => {
  682. const ctx = createContext()
  683. const compact = service(compactConfig, ctx)
  684. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  685. const stop = new Error('stop after first decision')
  686. vi.spyOn(compact, 'compactRegion').mockRejectedValueOnce(stop)
  687. await expect(compactIfNeeded(compact, conversation(4))).rejects.toBe(stop)
  688. expect(measure).toHaveBeenCalledTimes(1)
  689. })
  690. it('bounds retries when a shrinking checkpoint remains above threshold', async () => {
  691. const compact = service({
  692. auto: false,
  693. compactionRetries: 0,
  694. thresholdRatio: 0.3,
  695. retainTokens: 180,
  696. })
  697. compact.summary = Array.from({ length: 7 }, (_, index) => ({
  698. type: 'text',
  699. text: `summary ${index}`,
  700. }))
  701. await expect(compactIfNeeded(compact, conversation(4)))
  702. .rejects.toThrow(/still above threshold after 1 compaction attempts/)
  703. })
  704. it('rounds a retention cut head-ward to preserve tool-call/result pairing', async () => {
  705. const compact = service({
  706. auto: false,
  707. thresholdRatio: 0.8,
  708. retainTokens: 80,
  709. }, createContext(4_000))
  710. const session = toolConversation()
  711. const result = await compactIfNeeded(compact, session)
  712. expect(result).not.toBeNull()
  713. const messages = session.deriveMessages()
  714. const calls = new Set<string>()
  715. for (const message of messages) {
  716. for (const block of message.content) {
  717. if (block.type === 'tool-call') calls.add(block.id)
  718. if (block.type === 'tool-result') expect(calls.has(block.toolCallId)).toBe(true)
  719. }
  720. }
  721. })
  722. it('rejects a priced surface that is not the current positional surface', () => {
  723. const ctx = createContext()
  724. const session = conversation(2)
  725. const priced = ctx.tokenMeter.measure(session)
  726. expect(() => selectCompactableRange(session, {
  727. ...priced,
  728. nodes: priced.nodes.slice(1),
  729. }, 1)).toThrow(/does not match/)
  730. })
  731. it('declines when rounding a cut would consume the only tool pair', () => {
  732. const ctx = createContext()
  733. const session = Session.create(SessionId('one-tool-pair'))
  734. const callId = ToolCallId('only')
  735. session.append('turn/start', { turn: 1 })
  736. session.append('step/start', { turn: 1, step: 1 })
  737. session.append('assistant/message', {
  738. stream: [],
  739. turn: 1,
  740. step: 1,
  741. message: createMessage({
  742. role: 'assistant',
  743. content: [{ type: 'tool-call', id: callId, name: 'read', arguments: '{}' }],
  744. source: {
  745. kind: 'model',
  746. ...{ provider: MODEL, model: MODEL },
  747. },
  748. }),
  749. }, { surfaceOp: 'append' })
  750. session.append('tool/call', { turn: 1, step: 1, callId, name: 'read', arguments: '{}' })
  751. session.append('tool/result', {
  752. turn: 1,
  753. step: 1,
  754. message: createToolResultMessage({
  755. callId,
  756. content: [{ type: 'text', text: 'result' }],
  757. isError: false,
  758. }),
  759. }, { surfaceOp: 'append' })
  760. session.append('step/end', { turn: 1, step: 1 })
  761. const priced = ctx.tokenMeter.measure(session)
  762. expect(selectCompactableRange(session, priced, 1)).toBeNull()
  763. })
  764. })
  765. describe('optional model-free tool-result pruning', () => {
  766. const pruneConfig = { thresholdChars: 100, headChars: 20, tailChars: 10 }
  767. it('does not prune a below-pressure session opportunistically', async () => {
  768. const ctx = createContext(10_000)
  769. const prune = new ToolResultPruner(ctx, pruneConfig)
  770. const compact = new TestCompactionEngine(ctx, {
  771. auto: false,
  772. thresholdRatio: 0.8,
  773. retainTokens: 100,
  774. })
  775. const session = oversizedToolResult()
  776. const pruneSession = vi.spyOn(prune, 'pruneSession')
  777. expect(await compactIfNeeded(compact, session)).toBeNull()
  778. expect(pruneSession).not.toHaveBeenCalled()
  779. expect(compact.calls).toHaveLength(0)
  780. expect(session.surface.replaceGeneration).toBe(0)
  781. })
  782. it('skips LLM summarization when pruning alone clears pressure', async () => {
  783. const ctx = createContext(1_000)
  784. void new ToolResultPruner(ctx, pruneConfig)
  785. const compact = new TestCompactionEngine(ctx, {
  786. auto: false,
  787. thresholdRatio: 0.5,
  788. retainTokens: 50,
  789. })
  790. const session = oversizedToolResult()
  791. expect(ctx.tokenMeter.measure(session).totalTokens).toBeGreaterThanOrEqual(500)
  792. expect(await compactIfNeeded(compact, session)).toBeNull()
  793. expect(ctx.tokenMeter.measure(session).totalTokens).toBeLessThan(500)
  794. expect(compact.calls).toHaveLength(0)
  795. expect(session.surface.replaceGeneration).toBe(1)
  796. })
  797. it('summarizes the pruned surface when pruning is insufficient', async () => {
  798. const ctx = createContext(2_000)
  799. void new ToolResultPruner(ctx, pruneConfig)
  800. const compact = new TestCompactionEngine(ctx, {
  801. auto: false,
  802. thresholdRatio: 0.5,
  803. retainTokens: 50,
  804. })
  805. const session = toolConversation()
  806. expect(await compactIfNeeded(compact, session)).not.toBeNull()
  807. expect(compact.calls).toHaveLength(1)
  808. expect(summarizedText(compact.calls[0]!.input)).toContain('tool result middle pruned')
  809. expect(summarizedText(compact.calls[0]!.input)).not.toContain('result 1 '.repeat(300))
  810. })
  811. it('retains the original compaction-basic behavior without the optional plugin', async () => {
  812. const ctx = createContext(2_000)
  813. const compact = new TestCompactionEngine(ctx, {
  814. auto: false,
  815. thresholdRatio: 0.5,
  816. retainTokens: 50,
  817. })
  818. const session = oversizedToolResult(3_000, true)
  819. expect(await compactIfNeeded(compact, session)).not.toBeNull()
  820. expect(compact.calls).toHaveLength(1)
  821. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  822. const original = session.snapshotEvents().find(event => event.type === 'tool/result')
  823. expect(original?.type === 'tool/result' && original.data.message.content[0].content[0])
  824. .toEqual({ type: 'text', text: 'X'.repeat(3_000) })
  825. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  826. expect(session.snapshotEvents().filter(event =>
  827. event.type === 'tool/result' && event.surfaceOp !== 'append')).toHaveLength(0)
  828. })
  829. })
  830. describe('compaction region transaction', () => {
  831. it('lands a framed, replayable checkpoint with exact source seqs and token price', async () => {
  832. const compact = service()
  833. compact.rawOutput = [
  834. { type: 'reasoning', text: 'private compact thought' },
  835. ...compact.summary,
  836. ]
  837. compact.usage = { inputTokens: 40, outputTokens: 5 }
  838. const session = conversation(3)
  839. const before = [...session.surface.nodes]
  840. const result = await compact.compactRegion(
  841. before[0]!,
  842. before[3]!,
  843. agent(session, MODEL),
  844. SIGNAL,
  845. )
  846. expect(result.shadowedSeqs).toEqual(before.slice(0, 4))
  847. expect(result.shadowedTokenCount).toBeGreaterThan(0)
  848. expect(compact.calls[0]).toMatchObject({ signal: SIGNAL })
  849. expect(summarizedText(compact.calls[0]!.input)).toContain('fixture user 1')
  850. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  851. const summary = session.snapshotEvents().findLast(event => event.type === 'compaction/summary')
  852. expect(summary?.data).toMatchObject({
  853. shadowedSeqs: result.shadowedSeqs,
  854. shadowedTokenCount: result.shadowedTokenCount,
  855. provider: 'summary-provider',
  856. model: 'summary-model',
  857. maxTokens: 123,
  858. rawOutput: compact.rawOutput,
  859. usage: compact.usage,
  860. })
  861. expect(summary?.data).not.toHaveProperty('llmStreamCall')
  862. const head = session.deriveMessages()[0]!
  863. expect(head.content[0]?.type).toBe('text')
  864. expect(head.content[0]?.type === 'text' ? head.content[0].text : '').toContain('<compacted-summary>')
  865. expect(head.content.at(-1)).toEqual({ type: 'text', text: '</compacted-summary>' })
  866. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  867. const replay = Session.create(SessionId('replay'), session.snapshotEvents())
  868. expect(replay.deriveMessages()).toEqual(session.deriveMessages())
  869. })
  870. it('replays the system head and latest routed tools so the summarizer reuses the cache', async () => {
  871. const compact = service()
  872. const session = conversation(3, undefined, 'CONVERSATION SYSTEM')
  873. const tools = [{ name: 'do_thing', description: 'd', parameters: { type: 'object' } }]
  874. session.append('request/header', {
  875. header: { config: { provider: MODEL, model: MODEL }, tools },
  876. reason: 'resume',
  877. })
  878. const nodes = session.surface.nodes
  879. const prefix = session.deriveMessages().slice(0, 3)
  880. await compact.compactRegion(nodes[1]!, nodes[2]!, agent(session, MODEL), SIGNAL)
  881. const { input } = compact.calls[0]!
  882. expect(input).toEqual({ messages: prefix, tools })
  883. })
  884. it('omits the summarizer system prompt for an empty system head or a system-less surface', async () => {
  885. const compact = service()
  886. const emptyHead = conversation(3, undefined, '')
  887. const emptyNodes = emptyHead.surface.nodes
  888. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  889. expect(emptyHead.eventAt(emptyNodes[0]!)?.type).toBe('system/message')
  890. await compact.compactRegion(emptyNodes[1]!, emptyNodes[2]!, agent(emptyHead, MODEL), SIGNAL)
  891. expect(compact.calls[0]!.input.messages[0]).toMatchObject({ role: 'user' })
  892. expect(compact.calls[0]!.input.messages.some(message => message.role === 'system')).toBe(false)
  893. expect(emptyHead.surface.nodes[0]).toBe(emptyNodes[0])
  894. const headless = conversation(3)
  895. const nodes = headless.surface.nodes
  896. await compact.compactRegion(nodes[0]!, nodes[1]!, agent(headless, MODEL), SIGNAL)
  897. expect(compact.calls[1]!.input.messages.some(message => message.role === 'system')).toBe(false)
  898. expect(compact.calls[1]!.input.messages[0]).toMatchObject({ role: 'user' })
  899. })
  900. it('surfaces the session rejection of a range that covers the system head', async () => {
  901. const compact = service()
  902. const session = conversation(3, undefined, 'PROTECTED SYSTEM')
  903. const nodes = [...session.surface.nodes]
  904. await expect(compact.compactRegion(nodes[0]!, nodes[3]!, agent(session, MODEL), SIGNAL))
  905. .rejects.toThrow(/node 0 holds the system prompt/)
  906. expect(session.surface.nodes).toEqual(nodes)
  907. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  908. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  909. expect(end?.type === 'compaction/end' && end.data.error).toBeDefined()
  910. })
  911. it.each([
  912. ['start missing', 9_001, undefined, /start seq 9001 not found/],
  913. ['end missing', undefined, 9_002, /end seq 9002 not found/],
  914. ])('rejects %s', async (_label, startOverride, endOverride, pattern) => {
  915. const compact = service()
  916. const session = conversation(2)
  917. const nodes = session.surface.nodes
  918. await expect(compact.compactRegion(
  919. startOverride === undefined ? nodes[0]! : SessionSeq(startOverride),
  920. endOverride === undefined ? nodes[1]! : SessionSeq(endOverride),
  921. agent(session, MODEL),
  922. )).rejects.toThrow(pattern)
  923. })
  924. it('rejects reversed and tool-unbalanced positional boundaries', async () => {
  925. const compact = service()
  926. const plain = conversation(2)
  927. const nodes = plain.surface.nodes
  928. await expect(compact.compactRegion(
  929. nodes[2]!,
  930. nodes[1]!,
  931. agent(plain, MODEL),
  932. )).rejects.toThrow(/is after end/)
  933. const tools = toolConversation()
  934. const toolNodes = tools.surface.nodes
  935. await expect(compact.compactRegion(
  936. toolNodes[2]!,
  937. toolNodes[4]!,
  938. agent(tools, MODEL),
  939. )).rejects.toThrow(/start seq .* not a balanced boundary/)
  940. await expect(compact.compactRegion(
  941. toolNodes[0]!,
  942. toolNodes[1]!,
  943. agent(tools, MODEL),
  944. )).rejects.toThrow(/end seq .* not a balanced boundary/)
  945. })
  946. it('requires an open turn and an idle compaction bracket', async () => {
  947. const compact = service()
  948. const closed = conversation(1)
  949. closed.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  950. const nodes = closed.surface.nodes
  951. await expect(compact.compactRegion(
  952. nodes[0]!,
  953. nodes[1]!,
  954. agent(closed, MODEL),
  955. )).rejects.toThrow(/no open turn/)
  956. const locked = conversation(1)
  957. locked.append('compaction/start', {
  958. compactionId: CompactionId('locked-compaction'),
  959. turn: 2,
  960. })
  961. const lockedNodes = locked.surface.nodes
  962. await expect(compact.compactRegion(
  963. lockedNodes[0]!,
  964. lockedNodes[1]!,
  965. agent(locked, MODEL),
  966. )).rejects.toThrow(/already in progress/)
  967. })
  968. it('rejects a session with no turn boundary at all', async () => {
  969. const compact = service()
  970. const session = Session.create(SessionId('turnless'))
  971. session.append('user/message', createUserMessage({
  972. content: [{ type: 'text', text: 'orphan' }],
  973. source: { kind: 'user' },
  974. }), { surfaceOp: 'append' })
  975. const node = session.surface.nodes[0]!
  976. await expect(compact.compactRegion(
  977. node,
  978. node,
  979. agent(session, MODEL),
  980. )).rejects.toThrow(/no open turn/)
  981. })
  982. it('rejects a meter snapshot that changed before summarization began', async () => {
  983. const ctx = createContext()
  984. const meter = ctx.tokenMeter
  985. const original = meter.measure.bind(meter)
  986. vi.spyOn(meter, 'measure').mockImplementationOnce((session) => {
  987. const measurement = original(session)
  988. return { ...measurement, nodes: measurement.nodes.slice(1) }
  989. })
  990. const compact = service({ auto: false }, ctx)
  991. const session = conversation(2)
  992. const nodes = session.surface.nodes
  993. await expect(compact.compactRegion(
  994. nodes[0]!,
  995. nodes[2]!,
  996. agent(session, MODEL),
  997. )).rejects.toThrow(/selected surface changed/)
  998. })
  999. it('records summarizer failures without mutating the surface', async () => {
  1000. const compact = service()
  1001. compact.error = new Error('summary unavailable')
  1002. const session = conversation(2)
  1003. const before = session.surface.nodes
  1004. await expect(compact.compactRegion(
  1005. before[0]!,
  1006. before[2]!,
  1007. agent(session, MODEL),
  1008. )).rejects.toThrow('summary unavailable')
  1009. expect(session.surface.nodes).toEqual(before)
  1010. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1011. expect(session.snapshotEvents().findLast(event => event.type === 'compaction/end')?.data)
  1012. .toMatchObject({ error: 'summary unavailable' })
  1013. })
  1014. it('stringifies non-Error failures in the durable end bracket', async () => {
  1015. const compact = service()
  1016. compact.error = 'plain failure'
  1017. const session = conversation(2)
  1018. const nodes = session.surface.nodes
  1019. await expect(compact.compactRegion(
  1020. nodes[0]!,
  1021. nodes[2]!,
  1022. agent(session, MODEL),
  1023. )).rejects.toBe('plain failure')
  1024. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1025. expect(session.snapshotEvents().findLast(event => event.type === 'compaction/end')?.data)
  1026. .toMatchObject({ error: 'plain failure' })
  1027. })
  1028. it('tolerates concurrent log-only appends while the selected surface is stable', async () => {
  1029. const compact = service()
  1030. const session = conversation(2)
  1031. compact.mutateDuringSummary = () => {
  1032. session.append('request/header', {
  1033. header: { config: { provider: MODEL, model: MODEL } },
  1034. reason: 'change',
  1035. })
  1036. }
  1037. const nodes = session.surface.nodes
  1038. await expect(compact.compactRegion(
  1039. nodes[0]!,
  1040. nodes[2]!,
  1041. agent(session, MODEL),
  1042. )).resolves.toMatchObject({ shadowedSeqs: nodes.slice(0, 3) })
  1043. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1044. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  1045. })
  1046. it('rejects concurrent surface appends before committing the replacement', async () => {
  1047. const compact = service()
  1048. const session = conversation(2)
  1049. compact.mutateDuringSummary = () => {
  1050. session.append('user/message', createUserMessage({
  1051. content: [{ type: 'text', text: 'concurrent surface mutation' }],
  1052. source: { kind: 'plugin', plugin: 'test' },
  1053. }), { surfaceOp: 'append' })
  1054. }
  1055. const nodes = session.surface.nodes
  1056. await expect(compact.compactRegion(
  1057. nodes[0]!,
  1058. nodes[2]!,
  1059. agent(session, MODEL),
  1060. )).rejects.toThrow(/session surface changed/)
  1061. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1062. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  1063. })
  1064. it('rejects a non-shrinking framed summary under the conversation meter', async () => {
  1065. const compact = service()
  1066. compact.summary = Array.from({ length: 100 }, (_, index) => ({
  1067. type: 'text',
  1068. text: `verbose ${index}`,
  1069. }))
  1070. const session = conversation(2)
  1071. const nodes = session.surface.nodes
  1072. await expect(compact.compactRegion(
  1073. nodes[0]!,
  1074. nodes[2]!,
  1075. agent(session, MODEL),
  1076. )).rejects.toThrow(/summary is not smaller/)
  1077. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1078. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  1079. })
  1080. it('lets a model-independent custom summarizer compact without a conversation model', async () => {
  1081. const compact = service()
  1082. const session = Session.create(SessionId('model-less-region'))
  1083. session.append('turn/start', { turn: 1 })
  1084. session.append('user/message', createUserMessage({
  1085. content: [{ type: 'text', text: 'history '.repeat(100) }],
  1086. source: { kind: 'user' },
  1087. }), { surfaceOp: 'append' })
  1088. session.append('step/start', { turn: 1, step: 1 })
  1089. session.append('assistant/message', {
  1090. stream: [],
  1091. turn: 1,
  1092. step: 1,
  1093. message: createMessage({
  1094. role: 'assistant',
  1095. content: [{ type: 'text', text: 'answer '.repeat(100) }],
  1096. source: {
  1097. kind: 'model',
  1098. ...{ provider: 'historical', model: 'historical' },
  1099. },
  1100. }),
  1101. }, { surfaceOp: 'append' })
  1102. session.append('step/end', { turn: 1, step: 1 })
  1103. const nodes = session.surface.nodes
  1104. await expect(compact.compactRegion(
  1105. nodes[0]!,
  1106. nodes[1]!,
  1107. agent(session),
  1108. )).resolves.toMatchObject({ shadowedSeqs: [nodes[0]!, nodes[1]!] })
  1109. })
  1110. })
  1111. class ScriptedAdapter extends LlmAdapter {
  1112. lastOptions: GenerateOptions | undefined
  1113. usage: TokenUsage | undefined
  1114. constructor(
  1115. private readonly blocks: readonly ContentBlock[],
  1116. private readonly finish: (StreamChunk & { type: 'finish' })['reason'] = { kind: 'stop' },
  1117. ) {
  1118. super()
  1119. }
  1120. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  1121. this.lastOptions = options
  1122. for (const [index, block] of this.blocks.entries()) {
  1123. yield { type: 'block-start', index, blockType: block.type }
  1124. if (block.type === 'text') {
  1125. yield { type: 'text-delta', index, text: block.text }
  1126. } else if (block.type === 'reasoning') {
  1127. yield { type: 'reasoning-delta', index, text: block.text }
  1128. } else {
  1129. yield { type: 'block-end', index, block }
  1130. }
  1131. }
  1132. if (this.usage !== undefined) yield { type: 'usage', usage: this.usage }
  1133. yield { type: 'finish', reason: this.finish }
  1134. }
  1135. }
  1136. class ExposedCompactionEngine extends BasicCompactionEngine {
  1137. runSummarize(
  1138. input: SummarizationInput,
  1139. owner: Agent,
  1140. signal?: AbortSignal,
  1141. ): Promise<{
  1142. summary: ContentBlock[]
  1143. rawOutput?: ContentBlock[]
  1144. provider: string
  1145. model: string
  1146. maxTokens?: number
  1147. usage?: TokenUsage
  1148. }> {
  1149. return this.summarize(input, owner, signal)
  1150. }
  1151. }
  1152. async function summarizerHarness(
  1153. blocks: readonly ContentBlock[],
  1154. finish?: (StreamChunk & { type: 'finish' })['reason'],
  1155. model = MODEL,
  1156. config: BasicCompactionConfig = { auto: false },
  1157. ): Promise<{ ctx: Context; adapter: ScriptedAdapter; compact: ExposedCompactionEngine }> {
  1158. const ctx = new Context()
  1159. await ctx.plugin(LlmRuntime)
  1160. await ctx.plugin(SessionProjectionRegistry)
  1161. void new TokenMeter(ctx)
  1162. const adapter = new ScriptedAdapter(blocks, finish)
  1163. ctx.llm.registerAdapter([model], adapter)
  1164. const compact = new ExposedCompactionEngine(ctx, config)
  1165. return { ctx, adapter, compact }
  1166. }
  1167. describe('default one-shot summarizer', () => {
  1168. it.each([undefined, '', 'SYSTEM HEAD\n精确前缀\n'])('preserves the routed prefix through region summarization with system %j', async (system) => {
  1169. const { adapter, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }])
  1170. const session = conversation(3, undefined, system)
  1171. const tools = [{ name: 'do_thing', description: 'd', parameters: { type: 'object' } }]
  1172. session.append('request/header', {
  1173. header: { config: { provider: MODEL, model: MODEL }, tools },
  1174. reason: 'resume',
  1175. })
  1176. const nodes = [...session.surface.nodes]
  1177. const start = system === undefined ? 0 : 1
  1178. const prefix = session.deriveMessages().slice(0, system ? 3 : 2)
  1179. const result = await compact.compactRegion(nodes[start]!, nodes[start + 1]!, agent(session, MODEL), SIGNAL)
  1180. expect(adapter.lastOptions).not.toHaveProperty('system')
  1181. expect(adapter.lastOptions?.tools).toEqual(tools)
  1182. expect(adapter.lastOptions?.messages.slice(0, -1)).toEqual(prefix)
  1183. expect(adapter.lastOptions?.messages.at(-1)).toMatchObject({ role: 'user' })
  1184. expect(result.shadowedSeqs).toEqual(nodes.slice(start, start + 2))
  1185. if (system !== undefined) expect(session.surface.nodes[0]).toBe(nodes[0])
  1186. })
  1187. it('requires complete raw output when a subclass marks one local LLM stream call', () => {
  1188. expectTypeOf<{
  1189. summary: ContentBlock[]
  1190. llmStreamCall: true
  1191. provider: string
  1192. model: string
  1193. }>().not.toExtend<SummaryResult>()
  1194. })
  1195. it('uses configured model/default cap, forwards cancellation, and keeps only safe text', async () => {
  1196. const { adapter, compact } = await summarizerHarness([
  1197. { type: 'reasoning', text: 'private' },
  1198. { type: 'text', text: 'public summary' },
  1199. { type: 'tool-call', id: ToolCallId('unexpected'), name: 'x', arguments: '{}' },
  1200. ], undefined, MODEL, {
  1201. auto: false,
  1202. summarizationProvider: MODEL,
  1203. summarizationModel: MODEL,
  1204. maxTokens: 321,
  1205. })
  1206. const session = conversation(1)
  1207. adapter.usage = { inputTokens: 12, outputTokens: 3 }
  1208. const output = await compact.runSummarize(promptInput('transcript'), agent(session, 'fallback'), SIGNAL)
  1209. expect(output).toEqual({
  1210. summary: [{ type: 'text', text: 'public summary' }],
  1211. rawOutput: [
  1212. { type: 'reasoning', text: 'private' },
  1213. { type: 'text', text: 'public summary' },
  1214. { type: 'tool-call', id: ToolCallId('unexpected'), name: 'x', arguments: '{}' },
  1215. ],
  1216. llmStreamCall: true,
  1217. provider: MODEL,
  1218. model: MODEL,
  1219. maxTokens: 321,
  1220. usage: adapter.usage,
  1221. })
  1222. expect(adapter.lastOptions).toMatchObject({
  1223. provider: MODEL,
  1224. model: MODEL,
  1225. maxTokens: 321,
  1226. signal: SIGNAL,
  1227. sessionId: session.id,
  1228. purpose: 'compaction',
  1229. })
  1230. const instruction = adapter.lastOptions?.messages.at(-1)?.content[0]
  1231. expect(instruction?.type === 'text' ? instruction.text : '').toContain('## Primary Request and Intent')
  1232. })
  1233. it('replays the conversation prefix and appends the instruction as the final message', async () => {
  1234. const { adapter, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }])
  1235. const tools = [{ name: 'do_thing', description: 'd', parameters: { type: 'object' } }]
  1236. const prefix: Message = createUserMessage({
  1237. content: [
  1238. { type: 'text', text: 'earlier turn' },
  1239. {
  1240. type: 'image',
  1241. attachment: {
  1242. attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`),
  1243. mediaType: 'image/png',
  1244. bytes: 1,
  1245. width: 1,
  1246. height: 1,
  1247. },
  1248. },
  1249. ],
  1250. source: { kind: 'plugin', plugin: 'test' },
  1251. })
  1252. const system = createSystemMessage('REPLAYED SYSTEM', SYSTEM_PROMPT_PLUGIN)
  1253. await compact.runSummarize({
  1254. tools,
  1255. messages: [system, prefix],
  1256. }, agent(conversation(1), MODEL))
  1257. expect(adapter.lastOptions).not.toHaveProperty('system')
  1258. expect(adapter.lastOptions?.tools).toEqual(tools)
  1259. const messages = adapter.lastOptions?.messages ?? []
  1260. expect(messages.slice(0, -1)).toEqual([system, prefix])
  1261. const last = messages.at(-1)?.content[0]
  1262. const lastText = last?.type === 'text' ? last.text : ''
  1263. expect(lastText).toContain('Write concise English engineering prose.')
  1264. expect(lastText).toContain('numeric values, function signatures, and syntax fragments.')
  1265. expect(lastText).toContain('## Primary Request and Intent')
  1266. })
  1267. it('applies the routed model policy without changing the replayed prefix', async () => {
  1268. const { ctx, compact } = await summarizerHarness(
  1269. [{ type: 'text', text: 'unused default summary' }],
  1270. undefined,
  1271. MODEL,
  1272. {
  1273. auto: false,
  1274. maxTokens: 111,
  1275. modelPolicies: [{
  1276. provider: MODEL,
  1277. model: MODEL,
  1278. summarizationProvider: 'policy-summary',
  1279. summarizationModel: 'policy-summary',
  1280. maxTokens: 222,
  1281. }],
  1282. },
  1283. )
  1284. const policyAdapter = new ScriptedAdapter([{ type: 'text', text: 'policy summary' }])
  1285. ctx.llm.registerAdapter(['policy-summary'], policyAdapter)
  1286. const prefix: Message = createUserMessage({
  1287. content: [{ type: 'text', text: 'warm prefix' }],
  1288. source: { kind: 'plugin', plugin: 'test' },
  1289. })
  1290. const system = createSystemMessage('WARM SYSTEM', SYSTEM_PROMPT_PLUGIN)
  1291. const output = await compact.runSummarize({
  1292. messages: [system, prefix],
  1293. }, agent(conversation(1), 'fallback'))
  1294. expect(output).toMatchObject({
  1295. provider: 'policy-summary',
  1296. model: 'policy-summary',
  1297. maxTokens: 222,
  1298. })
  1299. expect(policyAdapter.lastOptions).toMatchObject({
  1300. provider: 'policy-summary',
  1301. model: 'policy-summary',
  1302. maxTokens: 222,
  1303. })
  1304. expect(policyAdapter.lastOptions).not.toHaveProperty('system')
  1305. expect(policyAdapter.lastOptions?.messages.slice(0, -1)).toEqual([system, prefix])
  1306. })
  1307. it('resolves the latest routed provider/model before the AgentOptions pair', async () => {
  1308. const { adapter, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }], undefined, 'routed')
  1309. const session = conversation(1)
  1310. session.append('request/header', {
  1311. header: { config: { provider: 'routed', model: 'routed' } },
  1312. reason: 'initial',
  1313. })
  1314. const output = await compact.runSummarize(promptInput('history'), agent(session, 'fallback'))
  1315. expect(output.provider).toBe('routed')
  1316. expect(output.model).toBe('routed')
  1317. expect(adapter.lastOptions?.provider).toBe('routed')
  1318. expect(adapter.lastOptions?.model).toBe('routed')
  1319. })
  1320. it('records the model actually dispatched after one-shot stream routing', async () => {
  1321. const { ctx, compact } = await summarizerHarness([{ type: 'text', text: 'unused' }])
  1322. const routedAdapter = new ScriptedAdapter([{ type: 'text', text: 'routed summary' }])
  1323. ctx.llm.registerAdapter(['routed-summary-provider'], routedAdapter)
  1324. ctx.on('llm/stream', (options, next) => {
  1325. options.provider = 'routed-summary-provider'
  1326. options.model = 'routed-summary-model'
  1327. return next()
  1328. })
  1329. const session = conversation(3, 'large history '.repeat(500))
  1330. const nodes = session.surface.nodes
  1331. await compact.compactRegion(nodes[0]!, nodes[3]!, agent(session, MODEL), SIGNAL)
  1332. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1333. expect(session.snapshotEvents().findLast(event => event.type === 'compaction/summary')?.data).toMatchObject({
  1334. summary: [{ type: 'text', text: 'routed summary' }],
  1335. llmStreamCall: true,
  1336. provider: 'routed-summary-provider',
  1337. model: 'routed-summary-model',
  1338. })
  1339. expect(routedAdapter.lastOptions?.provider).toBe('routed-summary-provider')
  1340. expect(routedAdapter.lastOptions?.model).toBe('routed-summary-model')
  1341. })
  1342. it('fails clearly when no complete summarization target can be resolved', async () => {
  1343. const ctx = new Context()
  1344. await ctx.plugin(LlmRuntime)
  1345. await ctx.plugin(SessionProjectionRegistry)
  1346. void new TokenMeter(ctx)
  1347. const compact = new ExposedCompactionEngine(ctx, { auto: false })
  1348. await expect(compact.runSummarize(promptInput('history'), agent(Session.create(SessionId('model-less')))))
  1349. .rejects.toThrow(/no provider\/model available for summarization/)
  1350. })
  1351. it('uses a complete AgentOptions target when no durable route exists', async () => {
  1352. const { adapter, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }])
  1353. const session = Session.create(SessionId('headerless-summary'))
  1354. await expect(compact.runSummarize(promptInput('history'), agent(session, MODEL))).resolves.toMatchObject({
  1355. provider: MODEL,
  1356. model: MODEL,
  1357. })
  1358. expect(adapter.lastOptions).toMatchObject({ provider: MODEL, model: MODEL })
  1359. })
  1360. it.each([
  1361. { provider: '', model: MODEL },
  1362. { provider: MODEL },
  1363. { provider: MODEL, model: '' },
  1364. ])('rejects incomplete AgentOptions target %#', async (options) => {
  1365. const { compact } = await summarizerHarness([{ type: 'text', text: 'unused' }])
  1366. const owner = {
  1367. session: Session.create(SessionId(`incomplete-${String(options.model)}`)),
  1368. options,
  1369. } as Agent
  1370. await expect(compact.runSummarize(promptInput('history'), owner))
  1371. .rejects.toThrow(/no provider\/model available for summarization/)
  1372. })
  1373. it.each([
  1374. [{ kind: 'error', failure: { message: 'provider failed', code: 'PROVIDER' } }, 'PROVIDER', /provider failed/],
  1375. [{ kind: 'error', failure: { message: 'opaque', code: 'UNKNOWN' } }, 'UNKNOWN', /opaque/],
  1376. [{ kind: 'aborted', failure: { message: 'summarization aborted', code: 'ABORTED' } }, 'ABORTED', /aborted/],
  1377. [{ kind: 'max-tokens' }, 'MAX_TOKENS', /token cap/],
  1378. ] as Array<[(StreamChunk & { type: 'finish' })['reason'], string | undefined, RegExp]>) (
  1379. 'rejects terminal finish %#',
  1380. async (finish, code, pattern) => {
  1381. const { compact } = await summarizerHarness([], finish)
  1382. let thrown: unknown
  1383. try {
  1384. await compact.runSummarize(promptInput('history'), agent(conversation(1), MODEL))
  1385. } catch (error: unknown) {
  1386. thrown = error
  1387. }
  1388. expect(thrown).toBeInstanceOf(Error)
  1389. expect((thrown as Error).message).toMatch(pattern)
  1390. expect((thrown as Error & { code?: string }).code).toBe(code)
  1391. },
  1392. )
  1393. it('rejects empty or reasoning-only successful output', async () => {
  1394. const { compact } = await summarizerHarness([{ type: 'reasoning', text: 'private' }])
  1395. await expect(compact.runSummarize(promptInput('history'), agent(conversation(1), MODEL)))
  1396. .rejects.toThrow(/no text summary content/)
  1397. })
  1398. it('rejects image summary output instead of silently dropping it', async () => {
  1399. const { compact } = await summarizerHarness([
  1400. {
  1401. type: 'image',
  1402. attachment: {
  1403. attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`),
  1404. mediaType: 'image/png',
  1405. bytes: 1,
  1406. width: 1,
  1407. height: 1,
  1408. },
  1409. },
  1410. { type: 'text', text: 'partial summary' },
  1411. ])
  1412. await expect(compact.runSummarize(promptInput('history'), agent(conversation(1), MODEL)))
  1413. .rejects.toMatchObject({ code: 'UNSUPPORTED_CONTENT' })
  1414. })
  1415. it('rejects image summary output nested in a tool result', async () => {
  1416. const { compact } = await summarizerHarness([{
  1417. type: 'tool-result',
  1418. toolCallId: ToolCallId('summary-tool'),
  1419. content: [{
  1420. type: 'image',
  1421. attachment: {
  1422. attachmentId: AttachmentId(`sha256:${'c'.repeat(64)}`),
  1423. mediaType: 'image/png',
  1424. bytes: 1,
  1425. width: 1,
  1426. height: 1,
  1427. },
  1428. }],
  1429. }])
  1430. await expect(compact.runSummarize(promptInput('history'), agent(conversation(1), MODEL)))
  1431. .rejects.toMatchObject({ code: 'UNSUPPORTED_CONTENT' })
  1432. })
  1433. })
  1434. describe('automatic listener and loader composition', () => {
  1435. function preStep(ctx: Context, owner: Agent, signal = SIGNAL) {
  1436. return agentEvents(ctx, owner).waterfall(
  1437. 'agent/pre-step', { messages: [], turn: 1, step: 1, signal },
  1438. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  1439. )
  1440. }
  1441. function recover(
  1442. ctx: Context,
  1443. owner: Agent,
  1444. error: Error & { code?: string },
  1445. signal = SIGNAL,
  1446. next: () => Promise<RequestErrorAction> = () => Promise.resolve(undefined),
  1447. ): Promise<boolean> {
  1448. const failure: LlmFailure = { message: error.message, code: error.code ?? 'UNKNOWN' }
  1449. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1450. const turn = owner.session.snapshotEvents().findLast(event => event.type === 'turn/start')?.data.turn ?? 1
  1451. return agentEvents(ctx, owner).waterfall(
  1452. 'agent/request-error',
  1453. { turn, step: 1, provider: 'test', failure, retryPolicy: undefined, signal },
  1454. next,
  1455. ).then(action => action?.kind === 'retry')
  1456. }
  1457. function overflow(message = 'provider overflow'): Error & { code: string } {
  1458. return Object.assign(new Error(message), { code: CONTEXT_WINDOW_EXCEEDED_CODE })
  1459. }
  1460. it('compacts before a step above threshold using the durable routed model and remains idle below it', async () => {
  1461. const ctx = createContext()
  1462. const compact = new TestCompactionEngine(ctx, {
  1463. thresholdRatio: 0.5,
  1464. retainTokens: 180,
  1465. })
  1466. const pressured = conversation(4)
  1467. await preStep(ctx, agent(pressured, 'unconfigured-agent-fallback'))
  1468. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1469. expect(pressured.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  1470. const small = conversation(1)
  1471. await preStep(ctx, agent(small, MODEL))
  1472. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1473. expect(small.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  1474. expect(compact.calls).toHaveLength(1)
  1475. })
  1476. it('skips pre-step pressure when the step signal is already aborted', async () => {
  1477. const ctx = createContext()
  1478. const compact = new TestCompactionEngine(ctx, {
  1479. thresholdRatio: 0.5,
  1480. retainTokens: 180,
  1481. })
  1482. const pressured = conversation(4)
  1483. const compactIfNeeded = vi.spyOn(compact, 'compactIfNeeded')
  1484. await expect(preStep(ctx, agent(pressured, MODEL), AbortSignal.abort('step aborted')))
  1485. .resolves.toEqual({ kind: 'enter', messages: [] })
  1486. expect(compactIfNeeded).not.toHaveBeenCalled()
  1487. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1488. expect(pressured.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  1489. })
  1490. it('warns and continues after operational failures, including non-Errors', async () => {
  1491. const ctx = createContext()
  1492. const warnings: string[] = []
  1493. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1494. const compact = new TestCompactionEngine(ctx, {
  1495. thresholdRatio: 0.5,
  1496. retainTokens: 180,
  1497. })
  1498. compact.error = 'temporary failure'
  1499. const session = conversation(4)
  1500. await expect(preStep(ctx, agent(session, MODEL))).resolves.toEqual({ kind: 'enter', messages: [] })
  1501. expect(warnings).toContainEqual(expect.stringContaining('temporary failure'))
  1502. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1503. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  1504. })
  1505. it('warns once per routed target when proactive pressure has no context metadata', async () => {
  1506. const ctx = createContext()
  1507. const warnings: string[] = []
  1508. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1509. vi.spyOn(ctx.llm, 'resolveModelInfo').mockImplementation((provider, model) => Promise.resolve({
  1510. provider,
  1511. id: model,
  1512. name: model,
  1513. }))
  1514. void new TestCompactionEngine(ctx, {
  1515. thresholdRatio: 0.5,
  1516. retainTokens: 180,
  1517. })
  1518. const session = conversation(4)
  1519. await preStep(ctx, agent(session, MODEL))
  1520. await preStep(ctx, agent(session, MODEL))
  1521. expect(warnings).toEqual([
  1522. expect.stringContaining(`no context capacity for ${MODEL}/${MODEL}`),
  1523. ])
  1524. })
  1525. it('warns once per routed target when absolute retention exceeds its resolved threshold', async () => {
  1526. const ctx = createContext()
  1527. const warnings: string[] = []
  1528. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1529. void new TestCompactionEngine(ctx, {
  1530. thresholdRatio: 0.5,
  1531. retainTokens: 500,
  1532. })
  1533. const session = conversation(4)
  1534. await preStep(ctx, agent(session, MODEL))
  1535. await preStep(ctx, agent(session, MODEL))
  1536. expect(warnings).toEqual([
  1537. expect.stringContaining('retainTokens (500) must be less than threshold tokens 500'),
  1538. ])
  1539. })
  1540. it('force-compacts below normal pressure for canonical overflow and retries only after replacement', async () => {
  1541. const ctx = createContext(10_000)
  1542. void new TestCompactionEngine(ctx, {
  1543. thresholdRatio: 1,
  1544. retainTokens: 900,
  1545. })
  1546. const session = conversation(3)
  1547. const beforeGeneration = session.surface.replaceGeneration
  1548. const retainedSeq = session.surface.nodes.at(-1)!
  1549. const threshold = 10_000
  1550. expect(ctx.tokenMeter.measure(session).totalTokens).toBeLessThan(threshold)
  1551. const decision = await recover(ctx, agent(session, 'unconfigured-agent-fallback'), overflow())
  1552. expect(decision).toBe(true)
  1553. expect(session.surface.replaceGeneration).toBe(beforeGeneration + 1)
  1554. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1555. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  1556. expect(session.surface.nodes).toContain(retainedSeq)
  1557. })
  1558. it('authorizes overflow retry when pruning alone advances an indivisible surface', async () => {
  1559. const ctx = createContext(10_000)
  1560. void new ToolResultPruner(ctx, {
  1561. thresholdChars: 100,
  1562. headChars: 20,
  1563. tailChars: 10,
  1564. })
  1565. const compact = new TestCompactionEngine(ctx, {
  1566. thresholdRatio: 1,
  1567. retainTokens: 900,
  1568. })
  1569. const session = oversizedToolResult()
  1570. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(true)
  1571. expect(session.surface.replaceGeneration).toBe(1)
  1572. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1573. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  1574. expect(compact.calls).toHaveLength(0)
  1575. })
  1576. it('continues overflow recovery with summarization on the pruned surface', async () => {
  1577. const ctx = createContext(10_000)
  1578. void new ToolResultPruner(ctx, {
  1579. thresholdChars: 100,
  1580. headChars: 20,
  1581. tailChars: 10,
  1582. })
  1583. const compact = new TestCompactionEngine(ctx, {
  1584. thresholdRatio: 1,
  1585. retainTokens: 900,
  1586. })
  1587. const session = toolConversation()
  1588. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(true)
  1589. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1590. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  1591. expect(compact.calls).toHaveLength(1)
  1592. expect(summarizedText(compact.calls[0]!.input)).toContain('tool result middle pruned')
  1593. })
  1594. it('retries from a durable prune when later overflow summarization throws', async () => {
  1595. const ctx = createContext(10_000)
  1596. const warnings: string[] = []
  1597. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1598. void new ToolResultPruner(ctx, {
  1599. thresholdChars: 100,
  1600. headChars: 20,
  1601. tailChars: 10,
  1602. })
  1603. const compact = new TestCompactionEngine(ctx, {
  1604. thresholdRatio: 1,
  1605. retainTokens: 900,
  1606. })
  1607. compact.error = new Error('summary unavailable after prune')
  1608. const session = oversizedToolResult(3_000, true)
  1609. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(true)
  1610. expect(session.surface.replaceGeneration).toBe(1)
  1611. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1612. expect(session.snapshotEvents().filter(event => event.type === 'tool/result')).toHaveLength(2)
  1613. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1614. expect(session.snapshotEvents().findLast(event => event.type === 'compaction/end')?.data)
  1615. .toMatchObject({ error: 'summary unavailable after prune' })
  1616. expect(warnings).toContainEqual(expect.stringContaining('retrying from the replacement surface'))
  1617. })
  1618. it('lets cancellation win when summary throws after a durable prune', async () => {
  1619. const ctx = createContext(10_000)
  1620. const controller = new AbortController()
  1621. void new ToolResultPruner(ctx, {
  1622. thresholdChars: 100,
  1623. headChars: 20,
  1624. tailChars: 10,
  1625. })
  1626. const compact = new TestCompactionEngine(ctx, {
  1627. thresholdRatio: 1,
  1628. retainTokens: 900,
  1629. })
  1630. compact.mutateDuringSummary = () => { controller.abort('cancelled during summary') }
  1631. compact.error = new Error('summary cancelled after prune')
  1632. const session = oversizedToolResult(3_000, true)
  1633. expect(await recover(ctx, agent(session, MODEL), overflow(), controller.signal)).toBe(false)
  1634. expect(session.surface.replaceGeneration).toBe(1)
  1635. })
  1636. it('preserves the newest whole tool-call/result pair during forced overflow compaction', async () => {
  1637. const ctx = createContext()
  1638. void new TestCompactionEngine(ctx, {
  1639. thresholdRatio: 1,
  1640. retainTokens: 90,
  1641. })
  1642. const session = toolConversation()
  1643. const newestAssistant = session.surface.nodes.at(-2)!
  1644. const newestResult = session.surface.nodes.at(-1)!
  1645. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(true)
  1646. const currentAssistant = session.surface.nodes.find(node => node === newestAssistant)
  1647. const currentResult = session.surface.nodes.find(node => node === newestResult)
  1648. expect(currentAssistant).toBeDefined()
  1649. expect(currentResult).toBeDefined()
  1650. expect(toolPairingBalancedBefore(session, currentAssistant!)).toBe(true)
  1651. expect(toolPairingBalancedAfter(session, currentResult!)).toBe(true)
  1652. })
  1653. it('does not retry when a backend reports success without replacing the surface', async () => {
  1654. const ctx = createContext()
  1655. const compact = new TestCompactionEngine(ctx)
  1656. const session = conversation(2)
  1657. const fakeResult: CompactionResult = {
  1658. compactionId: CompactionId('fake-compaction'),
  1659. startSeq: SessionSeq(1),
  1660. summarySeq: SessionSeq(2),
  1661. endSeq: SessionSeq(3),
  1662. summary: [{ type: 'text', text: 'fake' }],
  1663. shadowedRange: { start: SessionSeq(1), end: SessionSeq(2) },
  1664. shadowedSeqs: [SessionSeq(1), SessionSeq(2)],
  1665. shadowedTokenCount: 10,
  1666. }
  1667. vi.spyOn(compact, 'compactIfNeeded').mockResolvedValue(fakeResult)
  1668. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(false)
  1669. expect(session.surface.replaceGeneration).toBe(0)
  1670. })
  1671. it('delegates downstream exactly once when no replacement is available', async () => {
  1672. const ctx = createContext()
  1673. const compact = new TestCompactionEngine(ctx)
  1674. vi.spyOn(compact, 'compactIfNeeded').mockResolvedValue(null)
  1675. const downstream = new Error('downstream recovery failed')
  1676. let calls = 0
  1677. await expect(recover(
  1678. ctx,
  1679. agent(conversation(2), MODEL),
  1680. overflow(),
  1681. SIGNAL,
  1682. () => {
  1683. calls += 1
  1684. return Promise.reject(downstream)
  1685. },
  1686. )).rejects.toBe(downstream)
  1687. expect(calls).toBe(1)
  1688. })
  1689. it('preserves the original provider error when recovery throws', async () => {
  1690. const ctx = createContext()
  1691. const warnings: string[] = []
  1692. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1693. const compact = new TestCompactionEngine(ctx)
  1694. compact.error = new Error('summary unavailable')
  1695. const original = overflow('original provider overflow')
  1696. expect(await recover(ctx, agent(conversation(3), MODEL), original)).toBe(false)
  1697. expect(original).toMatchObject({
  1698. message: 'original provider overflow',
  1699. code: CONTEXT_WINDOW_EXCEEDED_CODE,
  1700. })
  1701. expect(warnings).toContainEqual(expect.stringContaining('preserving the original request error'))
  1702. })
  1703. it('delegates once when overflow recovery throws a non-Error value', async () => {
  1704. const ctx = createContext()
  1705. const warnings: string[] = []
  1706. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  1707. const compact = new TestCompactionEngine(ctx)
  1708. compact.error = 'non-error recovery failure'
  1709. const session = conversation(3)
  1710. const generation = session.surface.replaceGeneration
  1711. const original = overflow('original provider failure')
  1712. let delegations = 0
  1713. const decision = await recover(ctx, agent(session, MODEL), original, SIGNAL, () => {
  1714. delegations += 1
  1715. return Promise.resolve(undefined)
  1716. })
  1717. expect(decision).toBe(false)
  1718. expect(delegations).toBe(1)
  1719. expect(session.surface.replaceGeneration).toBe(generation)
  1720. expect(original).toMatchObject({
  1721. message: 'original provider failure',
  1722. code: CONTEXT_WINDOW_EXCEEDED_CODE,
  1723. })
  1724. expect(warnings).toContainEqual(expect.stringContaining('non-error recovery failure'))
  1725. })
  1726. it('recovers an overflow for an unlisted routed model', async () => {
  1727. const ctx = createContext()
  1728. void new TestCompactionEngine(ctx)
  1729. const session = conversation(2)
  1730. session.append('request/header', {
  1731. header: { config: { provider: 'unknown-routed-provider', model: 'unknown-routed-model' } },
  1732. reason: 'resume',
  1733. })
  1734. expect(await recover(ctx, agent(session, MODEL), overflow('unlisted-model overflow')))
  1735. .toBe(true)
  1736. })
  1737. it('delegates canonical overflow when no durable routed target exists', async () => {
  1738. const ctx = createContext()
  1739. void new TestCompactionEngine(ctx)
  1740. const session = Session.create(SessionId('headerless-overflow'))
  1741. session.append('turn/start', {
  1742. turn: 1,
  1743. })
  1744. await expect(recover(ctx, agent(session, MODEL), overflow())).resolves.toBe(false)
  1745. })
  1746. it('honors retry caps and ignores non-context failures', async () => {
  1747. const ctx = createContext()
  1748. const compact = new TestCompactionEngine(ctx, { maxOverflowRetries: 1 })
  1749. const compactSpy = vi.spyOn(compact, 'compactIfNeeded')
  1750. const owner = agent(conversation(3), MODEL)
  1751. expect(await recover(ctx, owner, Object.assign(new Error('rate limit'), { code: 'RATE_LIMIT' })))
  1752. .toBe(false)
  1753. expect(await recover(ctx, owner, overflow())).toBe(true)
  1754. compactSpy.mockClear()
  1755. expect(await recover(ctx, owner, overflow())).toBe(false)
  1756. expect(compactSpy).not.toHaveBeenCalled()
  1757. })
  1758. it('applies the routed model override to the overflow retry cap', async () => {
  1759. const ctx = createContext()
  1760. const compact = new TestCompactionEngine(ctx, {
  1761. maxOverflowRetries: 2,
  1762. modelPolicies: [{
  1763. provider: MODEL,
  1764. model: MODEL,
  1765. maxOverflowRetries: 1,
  1766. }],
  1767. })
  1768. const compactSpy = vi.spyOn(compact, 'compactIfNeeded')
  1769. const owner = agent(conversation(3), MODEL)
  1770. expect(await recover(ctx, owner, overflow())).toBe(true)
  1771. compactSpy.mockClear()
  1772. expect(await recover(ctx, owner, overflow())).toBe(false)
  1773. expect(compactSpy).not.toHaveBeenCalled()
  1774. })
  1775. it('does not retry when cancellation lands during an awaited compaction', async () => {
  1776. const ctx = createContext()
  1777. const compact = new TestCompactionEngine(ctx)
  1778. const controller = new AbortController()
  1779. compact.mutateDuringSummary = () => { controller.abort('cancelled during summary') }
  1780. const session = conversation(3)
  1781. const generation = session.surface.replaceGeneration
  1782. expect(await recover(ctx, agent(session, MODEL), overflow(), controller.signal)).toBe(false)
  1783. expect(session.surface.replaceGeneration).toBe(generation + 1)
  1784. })
  1785. it('maxOverflowRetries:0 disables recovery without disabling post-step pressure', async () => {
  1786. const ctx = createContext()
  1787. void new TestCompactionEngine(ctx, {
  1788. maxOverflowRetries: 0,
  1789. thresholdRatio: 0.5,
  1790. retainTokens: 180,
  1791. })
  1792. const session = conversation(4)
  1793. await preStep(ctx, agent(session, MODEL))
  1794. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1795. const summaries = session.snapshotEvents().filter(event => event.type === 'compaction/summary').length
  1796. expect(summaries).toBe(1)
  1797. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(false)
  1798. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1799. expect(session.snapshotEvents().filter(event => event.type === 'compaction/summary')).toHaveLength(summaries)
  1800. })
  1801. it('auto:false installs neither automatic listener', async () => {
  1802. const ctx = createContext()
  1803. void new TestCompactionEngine(ctx, {
  1804. auto: false,
  1805. thresholdRatio: 0.5,
  1806. retainTokens: 180,
  1807. })
  1808. const session = conversation(4)
  1809. await preStep(ctx, agent(session, MODEL))
  1810. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1811. expect(session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  1812. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(false)
  1813. })
  1814. it('loads and disposes the real zero-config service stack', async () => {
  1815. const ctx = new Context()
  1816. await ctx.plugin(LlmRuntime)
  1817. await ctx.plugin(SessionStore)
  1818. await ctx.plugin(SessionProjectionRegistry)
  1819. const meterFiber = await ctx.plugin(TokenMeter)
  1820. const compactFiber = await ctx.plugin(BasicCompactionEngine, { auto: false })
  1821. expect(ctx.get('compaction')).toBeInstanceOf(BasicCompactionEngine)
  1822. await compactFiber.dispose()
  1823. expect(ctx.get('compaction')).toBeUndefined()
  1824. await meterFiber.dispose()
  1825. expect(ctx.get('tokenMeter')).toBeUndefined()
  1826. })
  1827. it('removes its automatic listener with the plugin fiber', async () => {
  1828. const ctx = new Context()
  1829. await ctx.plugin(LlmRuntime)
  1830. await ctx.plugin(SessionProjectionRegistry)
  1831. await ctx.plugin(TokenMeter)
  1832. const fiber = await ctx.plugin(TestCompactionEngine, {
  1833. thresholdRatio: 0.5,
  1834. retainTokens: 180,
  1835. })
  1836. await fiber.dispose()
  1837. const session = conversation(4)
  1838. await preStep(ctx, agent(session, MODEL))
  1839. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1840. expect(session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  1841. expect(await recover(ctx, agent(session, MODEL), overflow())).toBe(false)
  1842. })
  1843. })
  1844. describe('route-priced image pressure', () => {
  1845. const IMAGE_VISUAL_TOKENS = 300
  1846. const IMAGE_HANDLE_TEXT = 'request preview'
  1847. class PricedContextAdapter extends ContextAdapter {
  1848. override imageRequestPricing(): { priceImages: (images: readonly unknown[]) => Array<{ visualTokens: number; text: string }> } {
  1849. return {
  1850. priceImages: images => images.map(() => ({
  1851. visualTokens: IMAGE_VISUAL_TOKENS,
  1852. text: IMAGE_HANDLE_TEXT,
  1853. })),
  1854. }
  1855. }
  1856. }
  1857. function pricedContext(contextWindow = 1_000): Context {
  1858. const ctx = new Context()
  1859. void new LlmRuntime(ctx)
  1860. new SessionProjectionRegistry(ctx)
  1861. void new TokenMeter(ctx)
  1862. ctx.llm.registerAdapter([MODEL], new PricedContextAdapter(contextWindow))
  1863. return ctx
  1864. }
  1865. /** Closed short-text turns whose user messages each carry one image. */
  1866. function imageConversation(turns = 4): Session {
  1867. const session = Session.create(SessionId(`image-dense-${turns}`))
  1868. for (let turn = 1; turn <= turns; turn += 1) {
  1869. session.append('turn/start', { turn })
  1870. session.append('user/message', createUserMessage({
  1871. content: [
  1872. { type: 'text', text: `image turn ${turn}` },
  1873. {
  1874. type: 'image',
  1875. attachment: {
  1876. attachmentId: AttachmentId(`sha256:${String(turn).repeat(8)}`),
  1877. mediaType: 'image/png',
  1878. bytes: 2048,
  1879. width: 800,
  1880. height: 800,
  1881. name: `shot-${turn}`,
  1882. },
  1883. },
  1884. ],
  1885. source: { kind: 'user' },
  1886. }), { surfaceOp: 'append' })
  1887. session.append('step/start', { turn, step: 1 })
  1888. if (turn === 1) {
  1889. session.append('request/header', {
  1890. header: { config: { provider: MODEL, model: MODEL } },
  1891. reason: 'initial',
  1892. })
  1893. }
  1894. session.append('assistant/message', {
  1895. stream: [],
  1896. turn,
  1897. step: 1,
  1898. message: createMessage({
  1899. role: 'assistant',
  1900. content: [{ type: 'text', text: `ok ${turn}` }],
  1901. source: {
  1902. kind: 'model',
  1903. ...{ provider: MODEL, model: MODEL },
  1904. },
  1905. }),
  1906. }, { surfaceOp: 'append' })
  1907. session.append('step/end', { turn, step: 1 })
  1908. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  1909. }
  1910. session.append('turn/start', { turn: turns + 1 })
  1911. return session
  1912. }
  1913. it('selects an image-dense range only when the routed price counts visual tokens', () => {
  1914. const session = imageConversation()
  1915. const routed = pricedContext().tokenMeter.measure(session)
  1916. const neutral = createContext().tokenMeter.measure(session)
  1917. expect(routed.surfaceTokens).toBeGreaterThan(neutral.surfaceTokens + 4 * IMAGE_VISUAL_TOKENS - 200)
  1918. expect(routed.nodes.map(node => node.seq)).toEqual(neutral.nodes.map(node => node.seq))
  1919. expect(routed.nodes.map(node => node.heuristicTokens)).toEqual(neutral.nodes.map(node => node.tokens))
  1920. // The same verbatim tail budget retains almost everything under the
  1921. // neutral heuristic but forces a cut once visual tokens are counted.
  1922. expect(selectCompactableRange(session, neutral, 350)).toBeNull()
  1923. const range = selectCompactableRange(session, routed, 350)
  1924. expect(range).not.toBeNull()
  1925. })
  1926. it('accepts a summary larger than the span heuristic when the route price shrinks', async () => {
  1927. // A single short image message prices below a framed summary under the
  1928. // fixed heuristic but far above it under the route: the shrink comparison
  1929. // must ask whether the replacement lowers route pressure.
  1930. const ctx = pricedContext(1_000)
  1931. const session = imageConversation(1)
  1932. const before = ctx.tokenMeter.measure(session)
  1933. const imageNode = before.nodes[0]!
  1934. const compact = new TestCompactionEngine(ctx, { auto: false })
  1935. compact.summary = [{
  1936. type: 'text',
  1937. text: 'summary text sized between the heuristic and route prices of the shadowed image message, '
  1938. + 'long enough that the fixed heuristic alone would reject it as not smaller '
  1939. + 'while the route-priced comparison accepts the pressure reduction.',
  1940. }]
  1941. const framed = ctx.tokenMeter.estimateMessage(createUserMessage({
  1942. content: frameSummary(compact.summary),
  1943. source: { kind: 'plugin', plugin: 'test' },
  1944. }))
  1945. expect(framed).toBeGreaterThan(imageNode.heuristicTokens)
  1946. expect(framed).toBeLessThan(imageNode.tokens)
  1947. const result = await compact.compactRegion(imageNode.seq, imageNode.seq, agent(session), SIGNAL)
  1948. expect(result.shadowedSeqs).toEqual([imageNode.seq])
  1949. expect(result.shadowedTokenCount).toBe(imageNode.heuristicTokens)
  1950. })
  1951. it('triggers pressure compaction from routed visual tokens and logs heuristic shadow prices', async () => {
  1952. const ctx = pricedContext(1_000)
  1953. const session = imageConversation()
  1954. const before = ctx.tokenMeter.measure(session)
  1955. const compact = new TestCompactionEngine(ctx, {
  1956. auto: false,
  1957. thresholdRatio: 0.8,
  1958. retainTokens: 350,
  1959. })
  1960. // The same history stays below the 800-token threshold without pricing.
  1961. const neutralResult = await compactIfNeeded(service({
  1962. auto: false,
  1963. thresholdRatio: 0.8,
  1964. retainTokens: 350,
  1965. }), session)
  1966. expect(neutralResult).toBeNull()
  1967. const result = await compact.compactIfNeeded(agent(session), 'pressure', SIGNAL)
  1968. expect(result).not.toBeNull()
  1969. // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
  1970. const summaryEvent = session.snapshotEvents().find(event => event.type === 'compaction/summary')
  1971. expect(summaryEvent).toBeDefined()
  1972. const shadowedHeuristic = before.nodes
  1973. .filter(node => result?.shadowedSeqs.includes(node.seq))
  1974. .reduce((total, node) => total + node.heuristicTokens, 0)
  1975. expect(summaryEvent?.data.shadowedTokenCount).toBe(shadowedHeuristic)
  1976. })
  1977. })