dsh-context-compression-improved 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +8 -8
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +212 -16
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +1 -19
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +75 -54
  22. package/packages/selector/README.md +7 -12
  23. package/packages/selector/README.zh.md +6 -13
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +16 -16
  27. package/packages/selector/lib/client.d.ts +97 -5
  28. package/packages/selector/lib/client.js +1884 -92
  29. package/packages/selector/lib/config.js +863 -6
  30. package/packages/selector/lib/index.d.ts +29 -21
  31. package/packages/selector/lib/index.js +424 -18
  32. package/packages/selector/lib/invariant.js +4 -4
  33. package/packages/selector/lib/pruner.d.ts +179 -4
  34. package/packages/selector/lib/pruner.js +1406 -371
  35. package/packages/selector/lib/style.css +42 -0
  36. package/packages/selector/lib/tail-trim.js +13 -4
  37. package/packages/selector/package.json +18 -27
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +200 -62
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/profiles.ts +431 -342
  61. package/packages/selector/src/pruner/state.ts +57 -43
  62. package/packages/selector/src/pruner.ts +2736 -2154
  63. package/packages/selector/src/runtime/audit.ts +303 -231
  64. package/packages/selector/src/runtime/config.ts +756 -642
  65. package/packages/selector/src/runtime/measurement.ts +436 -432
  66. package/packages/selector/src/runtime/monitor.ts +235 -0
  67. package/packages/selector/src/runtime/retrieve.ts +479 -457
  68. package/packages/selector/src/runtime/savings.ts +337 -0
  69. package/packages/selector/src/runtime/session-events.ts +30 -17
  70. package/packages/selector/src/runtime/summary-command.ts +127 -0
  71. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  72. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  73. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  74. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  75. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  76. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  77. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  78. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  79. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  80. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  81. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
  82. package/packages/selector/src/runtime/types.ts +365 -325
  83. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  84. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  85. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  86. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  87. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  88. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  89. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  90. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  91. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  92. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  93. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  94. package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
  95. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  96. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  97. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  98. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  99. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  100. package/packages/selector/tests/runtime/audit.spec.ts +275 -172
  101. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  102. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  103. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  104. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  105. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
  106. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  107. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  108. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  109. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  110. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  111. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  112. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  113. package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
  114. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  115. package/pnpm-workspace.yaml +66 -19
  116. package/scripts/capture-profile-baseline.mjs +42 -0
  117. package/scripts/generate-tokenizer-fixtures.py +81 -81
  118. package/scripts/generate-vision-fixtures.py +208 -208
  119. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  120. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  121. package/scripts/toolclass-corpus-replay.mjs +281 -273
  122. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  123. package/tests/TEST_INVENTORY.md +41 -42
  124. package/scripts/capture-profile-baseline.ts +0 -80
  125. package/tsconfig.scripts.json +0 -13
  126. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  127. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,2154 +1,2736 @@
1
- /**
2
- * Replay-safe, model-free context-compression selector for tool results.
3
- *
4
- * Standard profiles never rewrite ordinary Assistant prose. The only durable
5
- * replacements emitted here are content-only `tool/result` rewrites whose
6
- * full source remains in the append-only Session log.
7
- *
8
- * @module dsh-context-compression-improved-runtime
9
- */
10
-
11
- import { Service } from '@deepseek-ai/cordis'
12
- import type { Context } from '@deepseek-ai/cordis'
13
- import z from '@deepseek-ai/schemastery'
14
- import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
15
- import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm'
16
- import type { Session, SessionEvent, ToolResultMessage } from '@deepseek-ai/dsh-session'
17
- import type {} from '@deepseek-ai/dsh-agent'
18
- import type {} from '@deepseek-ai/dsh-compaction'
19
- import type {} from '@deepseek-ai/dsh-settings'
20
- import type {
21
- CompactionTokenView,
22
- ObservedPromptUsage,
23
- } from './runtime/measurement.ts'
24
- import { measureForCompaction } from './runtime/measurement.ts'
25
- import { sessionEvents } from './runtime/session-events.ts'
26
- import { countExactCanonicalTextFields } from './runtime/token-count.ts'
27
- import type {} from '@deepseek-ai/dsh-tools'
28
- import {
29
- tailTrimMessage,
30
- tailTrimRef,
31
- tailTrimStub,
32
- } from './runtime/tail-trim.ts'
33
- import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
34
- import type { PrunerState } from './pruner/state.ts'
35
- import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
36
- import type { ToolCallInfo, SnapshotCandidate, PlannedReplacement, HistoryPlanOutcome } from './pruner/types.ts'
37
- import {
38
- onlyTextBlock,
39
- onlyTextBlocks,
40
- countToolContent,
41
- sameProviderMeasurementKey,
42
- unavailableCount,
43
- recoveryMarker,
44
- summarize,
45
- emptyResult,
46
- measureContent,
47
- pressureCost,
48
- nativePruneContent,
49
- } from './pruner/content.ts'
50
- import {
51
- hasOpenTurn,
52
- rootToolResultSeq,
53
- sourceRef as sourceRefFn,
54
- latestCompletedToolStep,
55
- routeAuditFact,
56
- tokenizerAuditFact,
57
- isError,
58
- historyOutcome,
59
- } from './pruner/session.ts'
60
- import { buildLocatorBlock, findCompactionTrace } from './runtime/tokenpilot/locator.ts'
61
- import { clusterOmittedLines, isSupersededRead, toolCallPath } from './runtime/tokenpilot/read-state.ts'
62
- import {
63
- Estimator,
64
- backoffCooldownMs,
65
- buildEstimatorSystemPrompt,
66
- buildEstimatorUserPrompt,
67
- isCoolingDown,
68
- parseEstimatorAnswer,
69
- type EstimatorFailures,
70
- type EstimatorSample,
71
- } from './runtime/tokenpilot/estimator.ts'
72
-
73
- import {
74
- DedupeTable,
75
- dedupeHash,
76
- dedupePlaceholder,
77
- flattenPlainText,
78
- } from './runtime/tokenpilot/dedup.ts'
79
- import {
80
- charsForTokens,
81
- charsToTokens,
82
- codePointLength,
83
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
84
- ContextCompressionSettingsSchema,
85
- parseContextCompressionSettings,
86
- DEFAULTS,
87
- PRUNE_MARKER,
88
- resolveConfig,
89
- resolvePolicy,
90
- } from './runtime/config.ts'
91
- import {
92
- historicalPlaceholder,
93
- reduceFreshToolResult,
94
- verifyReduction,
95
- } from './runtime/reducers.ts'
96
- import type {
97
- CompressionPolicy,
98
- ContextCompressionSettings,
99
- HistoryMode,
100
- PrunedEntry,
101
- PruneResult,
102
- PruneSessionOptions,
103
- PruneStage,
104
- ToolResultPruneConfig,
105
- } from './runtime/types.ts'
106
- import { COMPRESSION_PROFILES } from './runtime/types.ts'
107
- import {
108
- decideConservativeAdaptive,
109
- deriveAdaptiveTokenBounds,
110
- } from './runtime/adaptive-cost.ts'
111
- import {
112
- DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
113
- priceOfficialDeepSeekUsage,
114
- resolveOfficialDeepSeekPrice,
115
- } from './runtime/deepseek-official-pricing.ts'
116
- import { emitCompressionAudit } from './runtime/audit.ts'
117
- import { assertNever, deepFreeze } from './runtime/value.ts'
118
- import type {
119
- CompressionAuditComponent,
120
- CompressionAuditEvaluationStatus,
121
- } from './runtime/audit.ts'
122
-
123
- export {
124
- codePointLength,
125
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
126
- ContextCompressionSettingsSchema,
127
- parseContextCompressionSettings,
128
- AUTO_COMPACT_THRESHOLD_LIMITS,
129
- DEFAULTS,
130
- isCompressionProfile,
131
- isValidAutoCompactThresholdPercent,
132
- PRUNE_MARKER,
133
- resolveConfig,
134
- resolvePolicy,
135
- } from './runtime/config.ts'
136
- export {
137
- CustomCompressionPolicySchema,
138
- DEFAULT_CUSTOM_COMPRESSION_POLICY,
139
- resolveCustomPolicy,
140
- } from './runtime/custom-policy.ts'
141
- export type { CustomPolicyResolutionOptions } from './runtime/custom-policy.ts'
142
- export { historicalPlaceholder, normalizeTerminalText, reduceFreshToolResult, verifyReduction } from './runtime/reducers.ts'
143
- export { measureForCompaction } from './runtime/measurement.ts'
144
- export type {
145
- CompactionTokenView,
146
- MeasuredTokenSurfaceNode,
147
- } from './runtime/measurement.ts'
148
- export type {
149
- AutoCompactSettings,
150
- CodeSkeletonSettings,
151
- CompressionPolicy,
152
- CompressionProfile,
153
- CustomCompressionBudget,
154
- CustomCompressionPolicy,
155
- CustomCompressionUnit,
156
- CustomHistoryPolicy,
157
- CustomPrefixPolicy,
158
- CustomTailTrimPolicy,
159
- CustomCompressionPolicyV1,
160
- CustomCompressionPolicyV2,
161
- CustomCompressionPolicyV3,
162
- ContextCompressionSettings,
163
- HistoryMode,
164
- PrunedEntry,
165
- PruneResult,
166
- PruneSessionOptions,
167
- PruneStage,
168
- ResolvedConfig,
169
- ToolResultPruneConfig,
170
- } from './runtime/types.ts'
171
-
172
- // Re-export the canonical profile list from the type module as a runtime value.
173
- export { COMPRESSION_PROFILES } from './runtime/types.ts'
174
-
175
-
176
-
177
- declare module '@deepseek-ai/cordis' {
178
- interface Context {
179
- toolResultPruner: ToolResultPruner
180
- }
181
- }
182
-
183
- /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
184
- export class ToolResultPruner extends Service {
185
- static inject = ['tokenMeter']
186
-
187
- static Config: z<ToolResultPruneConfig> = z.object({
188
- profile: z.union([...COMPRESSION_PROFILES]).default(DEFAULTS.profile),
189
- headChars: z.number().step(1).min(0).default(DEFAULTS.headChars),
190
- tailChars: z.number().step(1).min(0).default(DEFAULTS.tailChars),
191
- nativeTriggerTokens: z.number().step(1).min(1).required(false),
192
- nativeTargetTokens: z.number().step(1).min(1).required(false),
193
- freshTriggerTokens: z.number().step(1).min(1).required(false),
194
- freshTargetTokens: z.number().step(1).min(1).required(false),
195
- aggregateTriggerTokens: z.number().step(1).min(1).required(false),
196
- aggregateTargetTokens: z.number().step(1).min(1).required(false),
197
- historyTriggerTokens: z.number().step(1).min(1).required(false),
198
- historyKeepRecentToolCalls: z.number().step(1).min(0).required(false),
199
- historyKeepRecentTokens: z.number().step(1).min(0).required(false),
200
- historyMinReclaimTokens: z.number().step(1).min(1).required(false),
201
- autoCompactThresholdPercent: z.number().step(1).min(50).max(90).required(false),
202
- })
203
-
204
- /** Consolidated per-session mutable state. */
205
- readonly state: PrunerState
206
-
207
- constructor(ctx: Context, config: ToolResultPruneConfig = {}) {
208
- super(ctx, 'toolResultPruner')
209
- ctx.inject(['tools', 'systemPrompt'], recoveryCtx => {
210
- installContextCompressionRetrieve(recoveryCtx)
211
- })
212
- this.state = {
213
- config: resolveConfig(config),
214
- sessionSettings: new WeakMap(),
215
- firstExposure: new WeakMap(),
216
- recoveryExemptions: new WeakMap(),
217
- dedupeTables: new WeakMap(),
218
- estimatorVerdicts: new WeakMap(),
219
- estimatorFailures: new WeakMap(),
220
- warnedFailures: new WeakMap(),
221
- postflightDiagnostics: new WeakMap(),
222
- activeRequestBoundaries: new WeakMap(),
223
- tailTrimBoundaryAttempts: new WeakMap(),
224
- policyResolutionAudits: new WeakMap(),
225
- }
226
-
227
- ctx.on('session/event', (session, event) => {
228
- if (event.type === 'compaction/summary') {
229
- emitCompressionAudit(ctx.logger, {
230
- schemaVersion: 1,
231
- kind: 'native-auto-compact',
232
- sessionId: String(session.id),
233
- manifestEventType: 'compaction/summary',
234
- manifestSeq: event.seq,
235
- reducer: 'llm-summary',
236
- provider: event.data.provider,
237
- model: event.data.model,
238
- tokensBefore: event.data.shadowedTokenCount,
239
- tokensAfter: null,
240
- })
241
- return
242
- }
243
- if (event.type === 'compaction/end') {
244
- // TokenPilot-inspired A2: annotate the landed summary checkpoint with
245
- // an Exact Sources locator block. Strictly after compaction/end so no
246
- // open-compaction invariant ever observes the rewrite.
247
- try {
248
- this.attachSummaryLocator(session, event.data.compactionId)
249
- } catch (error: unknown) {
250
- this.auditFailure(session, 'pressure', 'summary-locator', error)
251
- ctx.logger.warn('context-compression summary locator failed open: %o', error)
252
- }
253
- }
254
- })
255
-
256
- // This is the true first-exposure boundary available in the Harness:
257
- // the preceding step's results are already durable, the new step is open,
258
- // and the next model request has not yet derived its history.
259
- ctx.on('agent/pre-step', async ({ agent, signal, turn, step }, next) => {
260
- const boundary = {}
261
- this.state.activeRequestBoundaries.set(agent.session, boundary)
262
- try {
263
- if (!signal.aborted) {
264
- try {
265
- // Only the immediately preceding step can contain results that have
266
- // not yet been exposed. This freezes both REDUCE and KEEP decisions:
267
- // older original events are never reconsidered after a profile change.
268
- this.runRequestBoundary(agent.session, turn, step - 1, signal)
269
- } catch (error: unknown) {
270
- this.auditFailure(agent.session, 'fresh', 'request-boundary', error)
271
- ctx.logger.warn('context-compression fresh pass failed open: %o', error)
272
- }
273
- }
274
- return await next()
275
- } finally {
276
- if (this.state.activeRequestBoundaries.get(agent.session) === boundary) {
277
- this.state.activeRequestBoundaries.delete(agent.session)
278
- }
279
- }
280
- }, { prepend: true })
281
-
282
- ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
283
- if (signal.aborted) return
284
- try {
285
- const step = latestCompletedToolStep(agent.session, turn)
286
- if (step !== undefined) this.runRequestBoundary(agent.session, turn, step, signal)
287
- } catch (error: unknown) {
288
- this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
289
- ctx.logger.warn('context-compression terminal pass failed open: %o', error)
290
- }
291
- // TokenPilot-inspired E1: advisory estimator pass, strictly off the
292
- // synchronous chain. Verdicts only feed the next pressure pass.
293
- void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
294
- })
295
- }
296
-
297
- /**
298
- * Measure text content in Unicode code points; non-text blocks cost zero.
299
- * @param blocks - tool-result content to measure.
300
- * @returns total Unicode code points across text blocks.
301
- */
302
- measureContent(blocks: readonly ContentBlock[]): number {
303
- return measureContent(blocks)
304
- }
305
-
306
- /**
307
- * Apply the configured native head/middle/tail transform.
308
- * @param blocks - original tool-result content.
309
- * @returns reduced content, or `null` when no reduction is required.
310
- */
311
- pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null {
312
- return nativePruneContent(
313
- blocks,
314
- this.state.config.headChars + codePointLength(PRUNE_MARKER) + this.state.config.tailChars,
315
- this.state.config.headChars,
316
- this.state.config.tailChars,
317
- )
318
- }
319
-
320
- /**
321
- * Run one stable-surface pass. `fresh` is invoked before every request and
322
- * only reduces original oversized results. `pressure` is called by
323
- * compaction-basic and may additionally age old results at one high-water.
324
- * @param session - session whose current tool-result surface may be rewritten.
325
- * @param options - pass stage and optional completed-step coordinates.
326
- * @returns landed replacements and aggregate Unicode-code-point savings.
327
- */
328
- pruneSession(session: Session, options: PruneSessionOptions = {}): PruneResult {
329
- const stage = options.stage ?? 'pressure'
330
- // External callers (compaction-basic) do not carry routed capacity; the
331
- // runtime resolves it itself so the frozen Auto Compact linkage and the
332
- // Custom percentage policy see one consistent context window.
333
- const contextWindowTokens = options.contextWindowTokens ?? this.contextWindowForRequest(session)
334
- const policy = this.activePolicy(session, contextWindowTokens, stage)
335
- if (policy === undefined) return emptyResult()
336
- const profile = policy.profile
337
- const view = measureForCompaction(this.ctx, session)
338
- if (stage === 'fresh') return this.decideFreshStep(session, options, policy, view)
339
- if (profile === 'off') return emptyResult()
340
-
341
- const landed: PrunedEntry[] = []
342
- if (policy.nativeToolResultEnabled) {
343
- const candidates = this.snapshot(session, view)
344
- const eligible = candidates.filter(candidate => !this.isRecoveryExempt(session, candidate))
345
- const exactUnavailable = eligible.some(candidate => candidate.count.kind !== 'exact-tokenizer')
346
- if (exactUnavailable) {
347
- this.warnExactUnavailable(session, view, 'native')
348
- }
349
- const planned = eligible
350
- .map(candidate => this.planNative(candidate, session, stage, policy, view))
351
- .filter((entry): entry is PlannedReplacement => entry !== null)
352
- landed.push(...this.landAll(session, planned))
353
- if (landed.length === 0) {
354
- const chars = eligible.map(candidate => candidate.characterPressure)
355
- this.auditComponent(session, policy, 'native-tool-result', 'pressure', 'skipped',
356
- chars.length === 0 ? 'no-tool-result-candidates'
357
- : Math.max(...chars) <= charsForTokens(policy.nativeTriggerTokens) ? 'at-or-below-trigger'
358
- : planned.length === 0 ? 'no-valid-reduction'
359
- : 'recovery-tool-unavailable', {
360
- measurementKind: 'characters',
361
- ...(chars.length === 0 ? {} : { currentTokens: charsToTokens(Math.max(...chars)) }),
362
- triggerTokens: policy.nativeTriggerTokens,
363
- targetTokens: policy.nativeTargetTokens,
364
- })
365
- }
366
- return summarize(landed)
367
- }
368
-
369
- let historyOutcome: HistoryPlanOutcome = { kind: 'planned', plans: [] }
370
- let historyAllowed = false
371
- if (policy.historyMode === 'adaptive') {
372
- historyOutcome = this.planHistoricalAging(session, policy, view)
373
- // Adaptive cost authority is meaningful only after the structural
374
- // planner has formed a real batch. A planning skip keeps its own reason
375
- // (for example exact-tokenizer-unavailable) and never becomes a false
376
- // adaptive-cost-rejected decision merely because it has zero plans.
377
- if (historyOutcome.kind === 'planned') {
378
- const capacityPressure = this.capacityPressureActive(session, view, policy)
379
- historyAllowed = this.adaptiveHistoryAllowed(
380
- session,
381
- view,
382
- historyOutcome.plans,
383
- capacityPressure,
384
- )
385
- if (historyAllowed) {
386
- landed.push(...this.landAll(session, historyOutcome.plans))
387
- }
388
- }
389
- } else {
390
- historyAllowed = this.historyAllowed(session, policy, view)
391
- if (historyAllowed) {
392
- historyOutcome = this.planHistoricalAging(session, policy, view)
393
- if (historyOutcome.kind === 'planned') {
394
- landed.push(...this.landAll(session, historyOutcome.plans))
395
- }
396
- }
397
- }
398
- if (!landed.some(entry => entry.stage === 'pressure')) {
399
- this.auditHistoryEvaluation(session, policy, view, historyAllowed, historyOutcome)
400
- }
401
- if (policy.tailTrim?.enabled === true) {
402
- const tailView = measureForCompaction(this.ctx, session)
403
- this.landOldestTailTrimGroup(session, policy, tailView)
404
- } else {
405
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'disabled', 'profile-policy')
406
- }
407
- return summarize(landed)
408
- }
409
-
410
- private activeSettings(session: Session): ContextCompressionSettings {
411
- const frozen = this.state.sessionSettings.get(session)
412
- if (frozen !== undefined) return frozen
413
- // Harness 0.1.1 brands namespace values through a helper while 0.1.2
414
- // validates the same public literal at its SettingsProvider boundary.
415
- const settings = this.ctx.get('settings')?.get(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
416
- let resolved: ContextCompressionSettings
417
- let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
418
- ? 'plugin-config-fallback'
419
- : 'host-settings'
420
- let autoCompactThresholdSource: 'generation-config' | 'host-settings' | 'schema-default'
421
- = settings === undefined ? 'schema-default' : 'host-settings'
422
- let settingsInvalidFallback: 'lossless-off' | undefined
423
- try {
424
- resolved = settings === undefined
425
- ? ContextCompressionSettingsSchema({ profile: this.state.config.profile } as never)
426
- // Validate the Host value BEFORE cloning: structuredClone normalizes
427
- // class/exotic prototypes to Object.prototype and would otherwise
428
- // erase the very boundary the parser is responsible for enforcing.
429
- : parseContextCompressionSettings(settings)
430
- } catch (error: unknown) {
431
- // A malformed persisted document must fail open LOSSLESSLY: freezing the
432
- // deployment default could silently re-enable lossy compression the
433
- // user never chose (for example a stored `off` plus an unknown key), so
434
- // the session freezes effectively off and keeps every original result.
435
- const reason = error instanceof Error ? error.message : String(error)
436
- this.auditFailure(session, 'pressure', 'policy-resolution', error)
437
- this.warnOnce(
438
- session,
439
- `settings-invalid:${reason}`,
440
- 'context-compression froze this session effectively off because the stored settings document is invalid: %s',
441
- reason,
442
- )
443
- resolved = ContextCompressionSettingsSchema({ profile: 'off' } as never)
444
- settingsSource = 'plugin-config-fallback'
445
- autoCompactThresholdSource = 'schema-default'
446
- settingsInvalidFallback = 'lossless-off'
447
- }
448
- if (this.state.config.autoCompactThresholdPercent !== undefined) {
449
- // The preset overlay froze this generation's threshold into the
450
- // deployment config; it supersedes the live Host setting so Auto
451
- // Compact and micro compact can never split across two thresholds.
452
- resolved = {
453
- ...resolved,
454
- autoCompact: { thresholdPercent: this.state.config.autoCompactThresholdPercent },
455
- }
456
- autoCompactThresholdSource = 'generation-config'
457
- }
458
- const snapshot = deepFreeze(structuredClone(resolved))
459
- this.state.sessionSettings.set(session, snapshot)
460
- emitCompressionAudit(this.ctx.logger, {
461
- schemaVersion: 1,
462
- kind: 'policy-frozen',
463
- sessionId: String(session.id),
464
- settingsSource,
465
- autoCompactThresholdSource,
466
- ...settingsInvalidFallback === undefined ? {} : { settingsInvalidFallback },
467
- settings: snapshot,
468
- deploymentConfig: this.state.config,
469
- })
470
- return snapshot
471
- }
472
-
473
- /**
474
- * TokenPilot-inspired A2: replace the compaction summary checkpoint node
475
- * with the same summary plus an Exact Sources locator block. Fails open:
476
- * any unresolved shape (no trace, no checkpoint node, already annotated)
477
- * leaves the summary untouched.
478
- */
479
- private attachSummaryLocator(session: Session, compactionId: string): void {
480
- const policy = this.activePolicy(session)
481
- if (policy?.presetOptions?.summaryLocator !== true) return
482
- const events = sessionEvents(session)
483
- const trace = findCompactionTrace(events, compactionId)
484
- if (trace === undefined) return
485
- const located = buildLocatorBlock(events, trace.summaryShadowedRange)
486
- if (located === null) return
487
- const block = located.text
488
- // Locate the summary checkpoint surface node: the user/message replacement
489
- // carrying this compaction's checkpoint provenance. Newest match wins.
490
- let checkpointSeq: number | undefined
491
- for (const seq of [...session.surface.nodes].reverse()) {
492
- const event = events[seq]
493
- if (event === undefined || event.type !== 'user/message') continue
494
- const source = (event.data as { source?: { compactionId?: unknown } }).source
495
- if (source === undefined || source === null) continue
496
- if (source.compactionId !== compactionId) continue
497
- checkpointSeq = seq
498
- break
499
- }
500
- if (checkpointSeq === undefined) return
501
- const original = events[checkpointSeq]
502
- if (original?.type !== 'user/message') return
503
- const data = original.data as UserMessage & { source?: unknown }
504
- const content = data.content.map(block => ({ ...block })) as typeof data.content
505
- const textBlocks = content.filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text')
506
- const lastText = textBlocks.at(-1)
507
- const marker = '## Exact Sources (locators)'
508
- if (lastText === undefined) return
509
- if (lastText.text.includes(marker)) return
510
- lastText.text = `${lastText.text}\n\n${block}`
511
- // Drop the checkpoint provenance: this replacement is a plain plugin-source
512
- // user/message surface rewrite, not a new compaction checkpoint, and
513
- // carrying the marker would fail the host's closed-transaction validation.
514
- const replacement = createUserMessage({
515
- content,
516
- source: { kind: 'plugin', plugin: 'dsh-context-compression-improved-runtime' },
517
- })
518
- session.append('user/message', replacement, {
519
- surfaceOp: { op: 'replace', start: checkpointSeq, end: checkpointSeq },
520
- sourceEventSeqs: [checkpointSeq],
521
- })
522
- emitCompressionAudit(this.ctx.logger, {
523
- schemaVersion: 1,
524
- kind: 'summary-locator',
525
- sessionId: String(session.id),
526
- profile: policy.profile,
527
- checkpointSeq,
528
- summarySeq: trace.summarySeq,
529
- locatorChars: codePointLength(located.text),
530
- spillFiles: located.spillFiles,
531
- touchedFiles: located.touchedFiles,
532
- })
533
- }
534
-
535
- /**
536
- * TokenPilot-inspired E1: sample oversized historical reads and ask the
537
- * auxiliary estimator whether their file state is still likely to be
538
- * referenced. Fire-and-forget: never awaited on the pruning chain, failures
539
- * back off exponentially per Session, verdicts only extend the rule-only
540
- * superseded classification.
541
- */
542
- private async postflightEstimatorPass(session: Session, signal: AbortSignal): Promise<void> {
543
- const policy = this.activePolicy(session)
544
- const presetOptions = policy?.presetOptions
545
- if (policy === undefined || presetOptions?.readState !== true) return
546
- const estimatorMode = presetOptions.estimator?.mode ?? ''
547
- if (estimatorMode === '') return
548
- const failures = this.state.estimatorFailures.get(session)
549
- if (isCoolingDown(failures, Date.now())) return
550
-
551
- const events = sessionEvents(session)
552
- const samples: EstimatorSample[] = []
553
- const now = Date.now()
554
- for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
555
- if (samples.length >= 3) break
556
- if (candidate.event.data.turn === undefined) continue
557
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) continue
558
- const path = toolCallPath(candidate.call.arguments)
559
- if (path === undefined) continue
560
- if (isSupersededRead(events, candidate.seq, path)) continue
561
- if (this.state.estimatorVerdicts.get(session)?.has(candidate.seq) === true) continue
562
- samples.push({ seq: candidate.seq, path, turn: candidate.event.data.turn })
563
- }
564
- if (samples.length === 0) return
565
-
566
- const estimator = new Estimator(this.ctx, this.activeSettings(session).presetOptions ?? {})
567
- const answer = await estimator.ask(buildEstimatorSystemPrompt(), buildEstimatorUserPrompt(samples), signal)
568
- const latencyMs = Date.now() - now
569
- const ok = answer !== undefined && signal.aborted === false
570
- let expired = 0
571
- if (ok && answer !== undefined) {
572
- let verdicts = this.state.estimatorVerdicts.get(session)
573
- if (verdicts === undefined) {
574
- verdicts = new Map()
575
- this.state.estimatorVerdicts.set(session, verdicts)
576
- }
577
- for (const verdict of parseEstimatorAnswer(answer)) {
578
- if (verdicts.has(verdict.seq)) continue
579
- verdicts.set(verdict.seq, verdict.expired)
580
- if (verdict.expired) expired += 1
581
- }
582
- } else {
583
- const next: EstimatorFailures = {
584
- failures: (failures?.failures ?? 0) + 1,
585
- cooldownUntil: Date.now() + backoffCooldownMs((failures?.failures ?? 0) + 1),
586
- }
587
- this.state.estimatorFailures.set(session, next)
588
- }
589
- emitCompressionAudit(this.ctx.logger, {
590
- schemaVersion: 1,
591
- kind: 'estimator-outcome',
592
- sessionId: String(session.id),
593
- profile: policy.profile,
594
- channel: estimatorMode === 'host' ? 'host' : 'direct',
595
- sampled: samples.length,
596
- expired,
597
- latencyMs,
598
- ok,
599
- })
600
- }
601
-
602
- private activePolicy(
603
- session: Session,
604
- contextWindowTokens?: number,
605
- stage: PruneStage = 'pressure',
606
- ): CompressionPolicy | undefined {
607
- const settings = this.activeSettings(session)
608
- try {
609
- const policy = resolvePolicy(
610
- this.state.config,
611
- settings.profile,
612
- settings.custom,
613
- {
614
- ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
615
- autoCompactThresholdPercent: settings.autoCompact.thresholdPercent,
616
- },
617
- )
618
- // Route changes must produce a fresh audit record even when the policy
619
- // object is unchanged, or the dedupe would hide a mid-session reroute.
620
- const route = routeAuditFact(session)
621
- const auditKey = JSON.stringify({
622
- policy,
623
- contextWindowTokens: contextWindowTokens ?? null,
624
- route: route ?? null,
625
- })
626
- // Deduplicate only CONSECUTIVE identical resolutions: a permanent set
627
- // would hide an A -> B -> A reroute's third record.
628
- if (this.state.policyResolutionAudits.get(session) !== auditKey) {
629
- this.state.policyResolutionAudits.set(session, auditKey)
630
- // Deployment config overrides win over the Auto Compact linkage, so a
631
- // standard profile whose History watermarks were replaced must not
632
- // audit itself as purely linkage-derived.
633
- const overriddenLinkedFields = ([
634
- 'historyTriggerTokens',
635
- 'historyKeepRecentTokens',
636
- 'historyMinReclaimTokens',
637
- ] as const).filter(key => this.state.config[key] !== undefined).length
638
- emitCompressionAudit(this.ctx.logger, {
639
- schemaVersion: 1,
640
- kind: 'policy-resolved',
641
- sessionId: String(session.id),
642
- policy,
643
- ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
644
- coordination: {
645
- thresholdPercent: settings.autoCompact.thresholdPercent,
646
- ...policy.autoCompactTokens === undefined ? {} : { autoCompactTokens: policy.autoCompactTokens },
647
- ...policy.microDeadlineTokens === undefined ? {} : { microDeadlineTokens: policy.microDeadlineTokens },
648
- paramSource: settings.profile === 'custom'
649
- ? 'custom-manual'
650
- : overriddenLinkedFields === 3 ? 'deployment-override'
651
- : overriddenLinkedFields > 0 ? 'mixed'
652
- : policy.microDeadlineTokens === undefined ? 'fixed-preset' : 'auto-compact-linked',
653
- },
654
- ...route === undefined ? {} : { route },
655
- ...route === undefined ? {} : tokenizerAuditFact(route),
656
- })
657
- }
658
- return policy
659
- } catch (error: unknown) {
660
- const reason = error instanceof Error ? error.message : String(error)
661
- this.auditFailure(session, stage, 'policy-resolution', error)
662
- this.warnOnce(
663
- session,
664
- `custom-policy:${settings.profile}:${reason}`,
665
- 'context-compression kept original tool results because the Custom policy is not effective: %s',
666
- reason,
667
- )
668
- return undefined
669
- }
670
- }
671
-
672
-
673
-
674
- private contextWindowForRequest(
675
- session: Session,
676
- ): number | undefined {
677
- const settings = this.activeSettings(session)
678
- // History linkage needs routed capacity for standard profiles, and the
679
- // Custom percentage policy needs it for context-percent documents. Off and
680
- // Native never link, and token-unit Custom stays manual.
681
- if (settings.profile === 'off' || settings.profile === 'native') return undefined
682
- if (settings.profile === 'custom' && settings.custom.unit !== 'context-percent') return undefined
683
- const config = session.requestHeader()?.config
684
- const routed = session.requestContext()
685
- if (config === undefined || config.provider.length === 0 || config.model.length === 0 || routed === undefined) {
686
- return undefined
687
- }
688
- if (routed.provider !== config.provider || routed.model !== config.model) {
689
- this.warnOnce(
690
- session,
691
- `custom-context-window-route:${config.provider}\0${config.model}`,
692
- 'context-compression kept the context-linked policy inactive because durable route capacity belongs to %s/%s, not %s/%s',
693
- routed.provider,
694
- routed.model,
695
- config.provider,
696
- config.model,
697
- )
698
- return undefined
699
- }
700
- if (!Number.isSafeInteger(routed.contextWindow) || routed.contextWindow === undefined || routed.contextWindow <= 0) {
701
- this.warnOnce(
702
- session,
703
- `custom-context-window-capacity:${config.provider}\0${config.model}`,
704
- 'context-compression kept the context-linked policy inactive because %s/%s has no positive durable context capacity',
705
- config.provider,
706
- config.model,
707
- )
708
- return undefined
709
- }
710
- return routed.contextWindow
711
- }
712
-
713
- private runRequestBoundary(
714
- session: Session,
715
- turn: number,
716
- step: number,
717
- signal: AbortSignal,
718
- ): void {
719
- const contextWindowTokens = this.contextWindowForRequest(session)
720
- if (signal.aborted) return
721
- const policy = this.activePolicy(session, contextWindowTokens, 'fresh')
722
- if (policy === undefined) return
723
- const capacity = contextWindowTokens === undefined ? {} : { contextWindowTokens }
724
- this.pruneSession(session, { stage: 'fresh', freshTurn: turn, freshStep: step, ...capacity })
725
- if (policy.historyMode !== 'disabled' || policy.tailTrim?.enabled === true) {
726
- this.pruneSession(session, { stage: 'pressure', ...capacity })
727
- }
728
- }
729
-
730
- /** Resolve historical-aging authority without accepting caller-supplied elevation. */
731
- private historyAllowed(session: Session, policy: CompressionPolicy, view: CompactionTokenView): boolean {
732
- switch (policy.historyMode) {
733
- case 'disabled':
734
- return false
735
- case 'routine':
736
- return true
737
- case 'capacity-pressure':
738
- return this.capacityPressureActive(session, view, policy)
739
- case 'adaptive':
740
- return false
741
- /* v8 ignore next -- closed-union exhaustiveness guard */
742
- default:
743
- return assertNever(policy.historyMode, 'history mode')
744
- }
745
- }
746
-
747
- /**
748
- * Match the compaction-basic pressure gate using public durable data. The
749
- * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
750
- * fixed 0.7 ratio once the standard-profile linkage resolved; without
751
- * linkage the 0.7 ratio is the documented fallback and reproduces the
752
- * previous behavior.
753
- */
754
- private capacityPressureActive(
755
- session: Session,
756
- view: CompactionTokenView,
757
- policy: CompressionPolicy,
758
- ): boolean {
759
- const deadline = policy.microDeadlineTokens
760
- if (deadline !== undefined) return view.totalTokens >= deadline
761
- const header = session.requestHeader()?.config
762
- const routed = session.requestContext()
763
- const contextWindow = routed?.contextWindow
764
- if (header === undefined || routed === undefined
765
- || routed.provider !== header.provider
766
- || routed.model !== header.model
767
- || contextWindow === undefined
768
- || !Number.isSafeInteger(contextWindow)
769
- || contextWindow <= 0) return false
770
- return view.totalTokens >= Math.floor(contextWindow * CAPACITY_PRESSURE_RATIO)
771
- }
772
-
773
- /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
774
- private logAdaptivePostflight(session: Session, usage: ObservedPromptUsage): void {
775
- const attemptId = String(usage.attemptId)
776
- if (this.state.postflightDiagnostics.get(session) === attemptId) return
777
- this.state.postflightDiagnostics.set(session, attemptId)
778
-
779
- const key = usage.key
780
- let priceRecord: Readonly<Record<string, unknown>> | undefined
781
- let cost: ReturnType<typeof priceOfficialDeepSeekUsage> | { readonly kind: 'unpriced'; readonly reason: string }
782
- if (key === undefined) {
783
- cost = { kind: 'unpriced', reason: 'measurement key unavailable' }
784
- } else if (usage.responseModelId !== key.modelId) {
785
- cost = { kind: 'unpriced', reason: 'response model mismatch or unavailable' }
786
- } else if (usage.observedOutputTokens === undefined) {
787
- cost = { kind: 'unpriced', reason: 'output token count unavailable' }
788
- } else if (usage.cacheStatus !== 'complete'
789
- || usage.cacheReadTokens === undefined
790
- || usage.cacheMissTokens === undefined) {
791
- cost = { kind: 'unpriced', reason: 'complete cache split unavailable' }
792
- } else {
793
- const startedAt = new Date(usage.startedAtMs)
794
- const completedAt = new Date(usage.completedAtMs)
795
- const resolution = resolveOfficialDeepSeekPrice({
796
- provider: key.provider,
797
- baseUrlClass: key.baseUrlClass,
798
- apiRoute: key.apiRoute,
799
- modelId: key.modelId,
800
- currency: 'USD',
801
- at: startedAt,
802
- })
803
- if (resolution.kind === 'priced') {
804
- priceRecord = {
805
- catalogVersion: resolution.record.catalogVersion,
806
- checkedAt: resolution.record.checkedAt,
807
- sourceUrl: resolution.record.sourceUrl,
808
- currency: resolution.record.currency,
809
- modelId: resolution.record.modelId,
810
- apiRoute: resolution.record.apiRoute,
811
- startBand: resolution.record.band,
812
- }
813
- }
814
- cost = priceOfficialDeepSeekUsage({
815
- provider: key.provider,
816
- baseUrlClass: key.baseUrlClass,
817
- apiRoute: key.apiRoute,
818
- modelId: key.modelId,
819
- currency: 'USD',
820
- startedAt,
821
- completedAt,
822
- usage: {
823
- cacheReadTokens: usage.cacheReadTokens,
824
- cacheMissTokens: usage.cacheMissTokens,
825
- outputTokens: usage.observedOutputTokens,
826
- },
827
- })
828
- }
829
-
830
- this.ctx.logger.debug(`context-compression adaptive postflight ${JSON.stringify({
831
- sessionId: String(session.id),
832
- providerRequestOrdinal: Number(usage.providerRequestOrdinal),
833
- attemptId,
834
- startedAtMs: usage.startedAtMs,
835
- completedAtMs: usage.completedAtMs,
836
- measurementKind: usage.measurement.kind,
837
- catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
838
- ...(priceRecord === undefined ? {} : { priceRecord }),
839
- usage: {
840
- promptTokens: usage.observedPromptTokens,
841
- ...(usage.observedOutputTokens === undefined ? {} : { outputTokens: usage.observedOutputTokens }),
842
- cacheStatus: usage.cacheStatus ?? 'unknown',
843
- ...(usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens }),
844
- ...(usage.cacheMissTokens === undefined ? {} : { cacheMissTokens: usage.cacheMissTokens }),
845
- },
846
- cost,
847
- })}`)
848
- }
849
-
850
- /** Decide one already-planned History batch from adjacent request-level facts only. */
851
- private adaptiveHistoryAllowed(
852
- session: Session,
853
- view: CompactionTokenView,
854
- plans: readonly PlannedReplacement[],
855
- capacityPressure: boolean,
856
- ): boolean {
857
- const log = (
858
- allowHistory: boolean,
859
- reason: string,
860
- detail: Readonly<Record<string, unknown>> = {},
861
- ): boolean => {
862
- this.ctx.logger.debug(`context-compression adaptive ${JSON.stringify({
863
- sessionId: String(session.id),
864
- allowHistory,
865
- reason,
866
- catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
867
- ...detail,
868
- })}`)
869
- return allowHistory
870
- }
871
- const usage = view.lastCompletedUsage
872
- if (usage !== undefined) this.logAdaptivePostflight(session, usage)
873
- if (plans.length === 0) return false
874
- if (capacityPressure) return log(true, 'capacity-override')
875
-
876
- const currentKey = view.latestEnvelopeKey
877
- if (usage === undefined) return log(false, 'usage-unavailable')
878
- if (usage.key === undefined || currentKey === undefined) {
879
- return log(false, 'measurement-key-unavailable')
880
- }
881
- if (!sameProviderMeasurementKey(usage.key, currentKey)) {
882
- return log(false, 'measurement-key-mismatch')
883
- }
884
- if (usage.responseModelId !== usage.key.modelId) {
885
- return log(false, 'response-model-mismatch-or-unavailable')
886
- }
887
- if (usage.cacheStatus !== 'complete'
888
- || usage.cacheReadTokens === undefined
889
- || usage.cacheMissTokens === undefined) {
890
- return log(false, 'cache-split-incomplete')
891
- }
892
-
893
- const price = resolveOfficialDeepSeekPrice({
894
- provider: usage.key.provider,
895
- baseUrlClass: usage.key.baseUrlClass,
896
- apiRoute: usage.key.apiRoute,
897
- modelId: usage.key.modelId,
898
- currency: 'USD',
899
- at: new Date(),
900
- })
901
- if (price.kind === 'unpriced') return log(false, `adaptive-unknown-price:${price.reason}`)
902
-
903
- const exactReclaimedTokens = plans.reduce(
904
- (sum, plan) => sum + plan.tokensBefore - plan.tokensAfter,
905
- 0,
906
- )
907
- const earliestChangedSeq = Math.min(...plans.map(plan => plan.candidate.seq))
908
- const bounds = deriveAdaptiveTokenBounds({
909
- exactReclaimedTokens,
910
- earliestChangedSeq,
911
- previousPromptTokens: usage.observedPromptTokens,
912
- expectedTokenizerRevision: usage.key.tokenizerRevision,
913
- previousRequestMeasurement: usage.measurement,
914
- measuredNodes: view.measuredNodes,
915
- })
916
- const decision = decideConservativeAdaptive({
917
- capacityPressure: false,
918
- bounds,
919
- inputCacheHitRate: price.record.inputCacheHit,
920
- inputCacheMissRate: price.record.inputCacheMiss,
921
- observedCacheReadTokens: usage.cacheReadTokens,
922
- })
923
- return log(decision.allowHistory, decision.reason, {
924
- priceBand: price.record.band,
925
- observedPromptTokens: usage.observedPromptTokens,
926
- observedCacheReadTokens: usage.cacheReadTokens,
927
- bounds,
928
- ...'minimumRemovalValue' in decision
929
- ? { minimumRemovalValue: decision.minimumRemovalValue }
930
- : {},
931
- ...'maximumCacheLossPenalty' in decision
932
- ? { maximumCacheLossPenalty: decision.maximumCacheLossPenalty }
933
- : {},
934
- })
935
- }
936
-
937
- private decisions(session: Session): Set<number> {
938
- let decisions = this.state.firstExposure.get(session)
939
- if (decisions === undefined) {
940
- decisions = new Set()
941
- this.state.firstExposure.set(session, decisions)
942
- }
943
- return decisions
944
- }
945
-
946
- /**
947
- * TokenPilot-style skipReduction: recovery tool output is permanently exempt
948
- * from every reduction pass so retrieved content can never enter a
949
- * compress-restore-oscillation loop. A call-name match covers the built-in
950
- * recovery tool; the per-session set admits future recovery paths.
951
- */
952
- private isRecoveryExempt(session: Session, candidate: SnapshotCandidate): boolean {
953
- if (candidate.call.name === 'context_compression_retrieve') return true
954
- return this.state.recoveryExemptions.get(session)?.has(candidate.seq) ?? false
955
- }
956
-
957
- /** Register a result seq as permanently exempt from further reduction. */
958
- private grantRecoveryExemption(session: Session, seq: number): void {
959
- let exemptions = this.state.recoveryExemptions.get(session)
960
- if (exemptions === undefined) {
961
- exemptions = new Set()
962
- this.state.recoveryExemptions.set(session, exemptions)
963
- }
964
- exemptions.add(seq)
965
- }
966
-
967
- private decideFreshStep(
968
- session: Session,
969
- options: PruneSessionOptions,
970
- policy: CompressionPolicy,
971
- view: CompactionTokenView,
972
- ): PruneResult {
973
- if (options.freshTurn === undefined || options.freshStep === undefined) {
974
- this.auditComponent(session, policy, 'fresh', 'fresh',
975
- policy.freshEnabled ? 'skipped' : 'disabled',
976
- policy.freshEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
977
- this.auditComponent(session, policy, 'aggregate', 'fresh',
978
- policy.aggregateEnabled ? 'skipped' : 'disabled',
979
- policy.aggregateEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
980
- return emptyResult()
981
- }
982
- const decisions = this.decisions(session)
983
- const candidates = this.snapshot(session, view).filter(candidate =>
984
- typeof candidate.event.surfaceOp !== 'object'
985
- && candidate.event.data.turn === options.freshTurn
986
- && candidate.event.data.step === options.freshStep
987
- && !decisions.has(candidate.seq))
988
- if (candidates.length === 0) {
989
- this.auditComponent(session, policy, 'fresh', 'fresh',
990
- policy.freshEnabled ? 'skipped' : 'disabled',
991
- policy.freshEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
992
- this.auditComponent(session, policy, 'aggregate', 'fresh',
993
- policy.aggregateEnabled ? 'skipped' : 'disabled',
994
- policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
995
- return emptyResult()
996
- }
997
-
998
- const plans = new Map<number, PlannedReplacement>()
999
- let freshPlanned = 0
1000
- const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
1001
- const candidateChars = candidates.map(candidate => candidate.characterPressure)
1002
- const maxCandidateChars = candidateChars.length === 0 ? undefined : Math.max(...candidateChars)
1003
- if (policy.freshEnabled) {
1004
- if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
1005
- && candidate.count.kind !== 'exact-tokenizer')) {
1006
- this.warnExactUnavailable(session, view, 'fresh')
1007
- }
1008
- for (const candidate of candidates) {
1009
- if (this.isRecoveryExempt(session, candidate)) continue
1010
- if (dedupeEnabled) {
1011
- const dedupePlan = this.planDedupe(candidate, session, policy, view)
1012
- if (dedupePlan !== null) {
1013
- plans.set(candidate.seq, dedupePlan)
1014
- continue
1015
- }
1016
- }
1017
- const plan = this.planFresh(candidate, session, policy, view)
1018
- if (plan !== null) {
1019
- plans.set(candidate.seq, plan)
1020
- freshPlanned += 1
1021
- }
1022
- }
1023
- }
1024
- let aggregateInputChars: number | undefined
1025
- let aggregatePlanned = 0
1026
- if (policy.aggregateEnabled) {
1027
- let total = candidates.reduce((sum, candidate) => sum
1028
- + (plans.get(candidate.seq)?.charsAfter ?? candidate.characterPressure), 0)
1029
- aggregateInputChars = total
1030
- if (total > charsForTokens(policy.aggregateTriggerTokens)) {
1031
- const remaining = candidates
1032
- .filter(candidate => !this.isRecoveryExempt(session, candidate))
1033
- .sort((a, b) => Number(isError(a)) - Number(isError(b))
1034
- || (plans.get(b.seq)?.charsAfter ?? b.characterPressure)
1035
- - (plans.get(a.seq)?.charsAfter ?? a.characterPressure))
1036
- for (const candidate of remaining) {
1037
- const previous = plans.get(candidate.seq)
1038
- const plan = this.planAggregate(candidate, session, view)
1039
- const previousChars = previous?.charsAfter ?? candidate.characterPressure
1040
- if (plan === null || plan.charsAfter >= previousChars) continue
1041
- plans.set(candidate.seq, plan)
1042
- aggregatePlanned += 1
1043
- total -= previousChars - plan.charsAfter
1044
- if (total <= charsForTokens(policy.aggregateTargetTokens)) break
1045
- }
1046
- if (total > charsForTokens(policy.aggregateTargetTokens)) {
1047
- this.ctx.logger.warn(
1048
- 'context-compression fresh aggregate residual: %d characters exceed target %d',
1049
- total,
1050
- charsForTokens(policy.aggregateTargetTokens),
1051
- )
1052
- }
1053
- }
1054
- }
1055
-
1056
- const landed = this.landAll(session, candidates
1057
- .map(candidate => plans.get(candidate.seq))
1058
- .filter((plan): plan is PlannedReplacement => plan !== undefined))
1059
- const freshLanded = landed.some(entry => entry.stage === 'fresh'
1060
- && plans.get(entry.originalSeq)?.component === 'fresh')
1061
- const aggregateLanded = landed.some(entry => entry.stage === 'fresh'
1062
- && plans.get(entry.originalSeq)?.component === 'aggregate')
1063
- if (!freshLanded) {
1064
- this.auditComponent(session, policy, 'fresh', 'fresh',
1065
- policy.freshEnabled ? 'skipped' : 'disabled',
1066
- !policy.freshEnabled ? 'profile-policy'
1067
- : (maxCandidateChars ?? 0) <= charsForTokens(policy.freshTriggerTokens) ? 'at-or-below-trigger'
1068
- : freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
1069
- : freshPlanned === 0 ? 'no-valid-reduction'
1070
- : 'recovery-tool-unavailable', {
1071
- measurementKind: 'characters',
1072
- ...(maxCandidateChars === undefined ? {} : { currentTokens: charsToTokens(maxCandidateChars) }),
1073
- triggerTokens: policy.freshTriggerTokens,
1074
- targetTokens: policy.freshTargetTokens,
1075
- })
1076
- }
1077
- if (!aggregateLanded) {
1078
- this.auditComponent(session, policy, 'aggregate', 'fresh',
1079
- policy.aggregateEnabled ? 'skipped' : 'disabled',
1080
- !policy.aggregateEnabled ? 'profile-policy'
1081
- : (aggregateInputChars ?? 0) <= charsForTokens(policy.aggregateTriggerTokens) ? 'at-or-below-trigger'
1082
- : aggregatePlanned === 0 ? 'no-valid-reduction'
1083
- : 'recovery-tool-unavailable', {
1084
- measurementKind: 'characters',
1085
- ...(aggregateInputChars === undefined ? {} : { currentTokens: charsToTokens(aggregateInputChars) }),
1086
- triggerTokens: policy.aggregateTriggerTokens,
1087
- targetTokens: policy.aggregateTargetTokens,
1088
- })
1089
- }
1090
- for (const candidate of candidates) decisions.add(candidate.seq)
1091
- return summarize(landed)
1092
- }
1093
-
1094
- private snapshot(session: Session, view: CompactionTokenView): SnapshotCandidate[] {
1095
- const events = sessionEvents(session)
1096
- const calls = new Map<string, ToolCallInfo>()
1097
- for (const event of events) {
1098
- if (event.type === 'tool/call') {
1099
- calls.set(event.data.callId, { name: event.data.name, arguments: event.data.arguments })
1100
- }
1101
- }
1102
- const candidates: SnapshotCandidate[] = []
1103
- const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1104
- const projectionPrices = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1105
- for (const seq of [...session.surface.nodes]) {
1106
- const event = events[seq]
1107
- if (event?.type !== 'tool/result') continue
1108
- const shadowedHeuristicTokenCount = projectionPrices.get(seq)
1109
- if (shadowedHeuristicTokenCount === undefined) {
1110
- throw new Error(`surface node ${String(seq)} is absent from the atomic legacy projection`)
1111
- }
1112
- const content = event.data.message.content[0].content
1113
- candidates.push({
1114
- seq,
1115
- event,
1116
- call: calls.get(event.data.message.source.callId) ?? { name: 'unknown', arguments: '{}' },
1117
- count: onlyTextBlocks(content) === null
1118
- ? unavailableCount(`surface node ${String(seq)} contains unsupported rich tool-result content`)
1119
- : measured.get(seq) ?? unavailableCount(`surface node ${String(seq)} is absent from the atomic token view`),
1120
- shadowedHeuristicTokenCount,
1121
- characterPressure: pressureCost(content),
1122
- })
1123
- }
1124
- return candidates
1125
- }
1126
-
1127
- private planNative(
1128
- candidate: SnapshotCandidate,
1129
- session: Session,
1130
- stage: PruneStage,
1131
- policy: CompressionPolicy,
1132
- view: CompactionTokenView,
1133
- ): PlannedReplacement | null {
1134
- if (this.isRecoveryExempt(session, candidate)) return null
1135
- if (candidate.characterPressure <= charsForTokens(policy.nativeTriggerTokens)) return null
1136
- const result = candidate.event.data.message.content[0]
1137
- if (onlyTextBlocks(result.content) === null) return null
1138
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1139
- // R9b site: the marker's retrieve hint starts at the event line right
1140
- // after the retained head, computed inside nativePruneContent.
1141
- const marker = (startLine: number): string => recoveryMarker(sourceRefFn(session, sourceSeq), 'tool result middle pruned', startLine)
1142
- let head = this.state.config.headChars
1143
- let tail = this.state.config.tailChars
1144
- for (let attempt = 0; attempt < 10; attempt += 1) {
1145
- const threshold = head + codePointLength(marker(1)) + tail
1146
- const content = nativePruneContent(result.content, threshold, head, tail, marker)
1147
- if (content !== null) {
1148
- const plan = this.plan(
1149
- candidate,
1150
- content,
1151
- sourceSeq,
1152
- 'native-head-tail',
1153
- stage,
1154
- 'native-tool-result',
1155
- undefined,
1156
- view,
1157
- )
1158
- if (plan !== null && plan.tokensAfter <= policy.nativeTargetTokens) return plan
1159
- }
1160
- if (head === 0 && tail === 0) break
1161
- head = Math.floor(head / 2)
1162
- tail = Math.floor(tail / 2)
1163
- }
1164
- return this.planAggregate(
1165
- candidate,
1166
- session,
1167
- view,
1168
- 'native-whole-result',
1169
- stage,
1170
- policy.nativeTargetTokens,
1171
- 'native-tool-result',
1172
- )
1173
- }
1174
-
1175
- /**
1176
- * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
1177
- * oversized tool result with a pointer to its first occurrence. The first
1178
- * occurrence's hash is always recorded so later repeats can point at the
1179
- * append-only original event even after the surface copy is reduced.
1180
- */
1181
- private planDedupe(
1182
- candidate: SnapshotCandidate,
1183
- session: Session,
1184
- policy: CompressionPolicy,
1185
- view: CompactionTokenView,
1186
- ): PlannedReplacement | null {
1187
- if (typeof candidate.event.surfaceOp === 'object') return null
1188
- const result = candidate.event.data.message.content[0]
1189
- const text = flattenPlainText(result.content)
1190
- if (text === undefined) return null
1191
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1192
- let table = this.state.dedupeTables.get(session)
1193
- if (table === undefined) {
1194
- table = new DedupeTable()
1195
- this.state.dedupeTables.set(session, table)
1196
- }
1197
- const hash = dedupeHash(text, 'trim-eol')
1198
- const entry = table.get(hash)
1199
- if (entry !== undefined && entry.seq !== candidate.seq) {
1200
- const placeholder = dedupePlaceholder(entry, codePointLength(text))
1201
- const plan = this.plan(
1202
- candidate,
1203
- [{ type: 'text', text: placeholder }],
1204
- entry.seq,
1205
- 'dedupe-pointer',
1206
- 'fresh',
1207
- 'fresh',
1208
- undefined,
1209
- view,
1210
- { noNetSavingsGuard: true },
1211
- )
1212
- if (plan !== null) return plan
1213
- return null
1214
- }
1215
- if (entry === undefined) {
1216
- table.record(hash, {
1217
- seq: candidate.seq,
1218
- sourceRef: sourceRefFn(session, candidate.seq),
1219
- toolName: candidate.call.name,
1220
- originalChars: codePointLength(text),
1221
- })
1222
- }
1223
- return null
1224
- }
1225
-
1226
- private planFresh(
1227
- candidate: SnapshotCandidate,
1228
- session: Session,
1229
- policy: CompressionPolicy,
1230
- view: CompactionTokenView,
1231
- ): PlannedReplacement | null {
1232
- // A replace event already reflects one frozen first-exposure decision. The
1233
- // pre-step coordinate filter prevents previously-kept originals from ever
1234
- // being reconsidered after their first request.
1235
- if (typeof candidate.event.surfaceOp === 'object') return null
1236
- const result = candidate.event.data.message.content[0]
1237
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1238
- const sourceSeq = candidate.seq
1239
- const sourceRef = sourceRefFn(session, sourceSeq)
1240
- const textBlock = onlyTextBlock(result.content)
1241
- if (textBlock !== null) {
1242
- let budgetChars = Math.max(1, Math.floor(codePointLength(textBlock.text) * 0.75))
1243
- const codeSkeleton = this.activeSettings(session).codeSkeleton.enabled
1244
- for (let attempt = 0; attempt < 10; attempt += 1) {
1245
- const output = reduceFreshToolResult({
1246
- toolName: candidate.call.name,
1247
- argumentsText: candidate.call.arguments,
1248
- text: textBlock.text,
1249
- budgetChars,
1250
- sourceRef,
1251
- isError: result.isError === true || candidate.event.data.error !== undefined,
1252
- codeSkeleton,
1253
- })
1254
- if (output !== null) {
1255
- const plan = this.plan(
1256
- candidate,
1257
- [{ ...textBlock, text: output.text }],
1258
- sourceSeq,
1259
- output.reducer,
1260
- 'fresh',
1261
- 'fresh',
1262
- undefined,
1263
- view,
1264
- {
1265
- noNetSavingsGuard: policy.presetOptions?.noNetSavingsGuard === true,
1266
- ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }),
1267
- },
1268
- )
1269
- if (plan !== null && plan.charsAfter <= charsForTokens(policy.freshTargetTokens)) return plan
1270
- }
1271
- if (budgetChars === 1) break
1272
- budgetChars = Math.max(1, Math.floor(budgetChars / 2))
1273
- }
1274
- }
1275
-
1276
- return this.planAggregate(
1277
- candidate,
1278
- session,
1279
- view,
1280
- 'fresh-whole-result',
1281
- 'fresh',
1282
- policy.freshTargetTokens,
1283
- 'fresh',
1284
- )
1285
- }
1286
-
1287
- private planAggregate(
1288
- candidate: SnapshotCandidate,
1289
- session: Session,
1290
- view: CompactionTokenView,
1291
- reducer = 'fresh-step-aggregate',
1292
- stage: PruneStage = 'fresh',
1293
- targetTokens?: number,
1294
- component: CompressionAuditComponent = 'aggregate',
1295
- historyMode?: HistoryMode,
1296
- ): PlannedReplacement | null {
1297
- if (isError(candidate)) {
1298
- return this.planErrorEvidence(
1299
- candidate,
1300
- session,
1301
- view,
1302
- stage,
1303
- targetTokens,
1304
- component,
1305
- historyMode,
1306
- )
1307
- }
1308
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1309
- const sourceRef = sourceRefFn(session, sourceSeq)
1310
- // The placeholder below is a single text block, so a rich tool result (for
1311
- // example one carrying an image) must never reach it. The character basis
1312
- // no longer inherits the exact-tokenizer precondition that used to reject
1313
- // this path implicitly, so the guard has to be explicit.
1314
- const redacted = candidate.event.data.message.content[0]
1315
- if (onlyTextBlocks(redacted.content) === null) return null
1316
- const text = [
1317
- '[Tool result reduced to satisfy the completed-step aggregate budget]',
1318
- `tool: ${candidate.call.name}`,
1319
- `source: ${sourceRef}`,
1320
- 'Use context_compression_retrieve with this source if the omitted evidence is necessary.',
1321
- ].join('\n')
1322
- const plan = this.plan(
1323
- candidate,
1324
- [{ type: 'text', text }],
1325
- sourceSeq,
1326
- reducer,
1327
- stage,
1328
- component,
1329
- historyMode,
1330
- view,
1331
- )
1332
- return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1333
- ? plan
1334
- : null
1335
- }
1336
-
1337
- /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
1338
- private planErrorEvidence(
1339
- candidate: SnapshotCandidate,
1340
- session: Session,
1341
- view: CompactionTokenView,
1342
- stage: PruneStage,
1343
- targetTokens?: number,
1344
- component: CompressionAuditComponent = 'aggregate',
1345
- historyMode?: HistoryMode,
1346
- ): PlannedReplacement | null {
1347
- if (!isError(candidate)) return null
1348
- const result = candidate.event.data.message.content[0]
1349
- const blocks = onlyTextBlocks(result.content)
1350
- if (blocks === null) return null
1351
- const text = blocks.map(block => block.text).join('\n')
1352
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1353
- const sourceRef = sourceRefFn(session, sourceSeq)
1354
- const output = historicalPlaceholder({
1355
- toolName: candidate.call.name,
1356
- sourceRef,
1357
- charsBefore: codePointLength(text),
1358
- isError: true,
1359
- text,
1360
- compact: false,
1361
- })
1362
- const input = {
1363
- toolName: candidate.call.name,
1364
- argumentsText: candidate.call.arguments,
1365
- text,
1366
- budgetChars: 1_200,
1367
- sourceRef,
1368
- isError: true,
1369
- }
1370
- if (!verifyReduction(input, output)) return null
1371
- const plan = this.plan(
1372
- candidate,
1373
- [{ type: 'text', text: output.text }],
1374
- sourceSeq,
1375
- 'error-evidence-placeholder',
1376
- stage,
1377
- component,
1378
- historyMode,
1379
- view,
1380
- )
1381
- return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1382
- ? plan
1383
- : null
1384
- }
1385
-
1386
- private planHistoricalAging(
1387
- session: Session,
1388
- policy: CompressionPolicy,
1389
- view: CompactionTokenView,
1390
- ): HistoryPlanOutcome {
1391
- const candidates = this.snapshot(session, view)
1392
- const events = sessionEvents(session)
1393
- const chars = candidates.map(candidate => candidate.characterPressure)
1394
- const total = chars.reduce((sum, charsOfNode) => sum + charsOfNode, 0)
1395
- const trigger = charsForTokens(policy.historyTriggerTokens)
1396
- // Full-request last chance: ordinary prose, images, prompts, or schemas can
1397
- // push the complete request past the Auto Compact deadline before the tool
1398
- // results alone cross the profile trigger.
1399
- const deadline = policy.microDeadlineTokens
1400
- const lastChance = deadline !== undefined && view.totalTokens >= deadline
1401
- if (total <= trigger && !lastChance) return { kind: 'below-profile-trigger' }
1402
-
1403
- const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
1404
- const isUnsafe = (candidate: SnapshotCandidate): boolean => {
1405
- if (this.isRecoveryExempt(session, candidate)) return true
1406
- const result = candidate.event.data.message.content[0]
1407
- const block = onlyTextBlock(result.content)
1408
- return block?.text.includes('[Old tool result content cleared from active context]') === true
1409
- }
1410
- // Distinguish "nothing safe to touch" (recovery tool output or already
1411
- // cleared) from "everything left is inside the protected working set":
1412
- // both skip, but they are different operational facts.
1413
- const safe = candidates.filter(candidate => !isUnsafe(candidate))
1414
- const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1415
- if (eligible.length === 0) {
1416
- return safe.length === 0
1417
- ? { kind: 'no-safe-candidates' }
1418
- : { kind: 'protected-working-set' }
1419
- }
1420
- const planned: PlannedReplacement[] = []
1421
- let reclaim = 0
1422
- // Linked batches must reach the deadline target; unlinked batches keep
1423
- // the traditional minimum-reclaim commit threshold. All arithmetic runs on
1424
- // the character basis: token-named thresholds enter via charsForTokens.
1425
- const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens)
1426
- const microTarget = deadline === undefined ? undefined : Math.max(0, charsForTokens(deadline) - minReclaimChars)
1427
- const required = Math.max(
1428
- minReclaimChars,
1429
- total - trigger,
1430
- ...(microTarget === undefined ? [] : [charsForTokens(view.totalTokens) - microTarget]),
1431
- )
1432
- const batchTarget = microTarget === undefined
1433
- ? minReclaimChars
1434
- : required
1435
- for (const candidate of eligible) {
1436
- const result = candidate.event.data.message.content[0]
1437
- const block = onlyTextBlock(result.content)
1438
- // TokenPilot-inspired R2: a read output whose file was later mutated is
1439
- // superseded — its text can no longer match the file — so it takes the
1440
- // small whole-result placeholder before the ordinary reducer runs.
1441
- if (policy.presetOptions?.readState === true && block !== null) {
1442
- const readPath = toolCallPath(candidate.call.arguments)
1443
- const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
1444
- if (readPath !== undefined
1445
- && (isSupersededRead(events, candidate.seq, readPath) || estimatorExpired)) {
1446
- const plan = this.planAggregate(
1447
- candidate,
1448
- session,
1449
- view,
1450
- 'superseded-read-whole-result',
1451
- 'pressure',
1452
- undefined,
1453
- 'history',
1454
- policy.historyMode,
1455
- )
1456
- if (plan === null) continue
1457
- planned.push(plan)
1458
- reclaim += plan.charsBefore - plan.charsAfter
1459
- if (reclaim >= required) break
1460
- continue
1461
- }
1462
- }
1463
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1464
- if (block === null) {
1465
- const plan = this.planAggregate(
1466
- candidate,
1467
- session,
1468
- view,
1469
- 'historical-rich-whole-result',
1470
- 'pressure',
1471
- undefined,
1472
- 'history',
1473
- policy.historyMode,
1474
- )
1475
- if (plan === null) continue
1476
- planned.push(plan)
1477
- reclaim += plan.charsBefore - plan.charsAfter
1478
- if (reclaim >= required) break
1479
- continue
1480
- }
1481
- const output = historicalPlaceholder({
1482
- toolName: candidate.call.name,
1483
- sourceRef: sourceRefFn(session, sourceSeq),
1484
- charsBefore: codePointLength(block.text),
1485
- isError: result.isError === true || candidate.event.data.error !== undefined,
1486
- text: block.text,
1487
- compact: false,
1488
- })
1489
- const verifyInput = {
1490
- toolName: candidate.call.name,
1491
- argumentsText: candidate.call.arguments,
1492
- text: block.text,
1493
- budgetChars: 1_200,
1494
- sourceRef: sourceRefFn(session, sourceSeq),
1495
- isError: result.isError === true || candidate.event.data.error !== undefined,
1496
- }
1497
- if (!verifyReduction(verifyInput, output)) continue
1498
- // TokenPilot-inspired R3: when read-state semantics are on, append an
1499
- // error/warn/info census of the omitted lines so the model keeps
1500
- // meta-knowledge about what was dropped.
1501
- let replacementText = output.text
1502
- if (policy.presetOptions?.readState === true) {
1503
- const omitted = countOmittedLines(block.text, output.text)
1504
- const census = omitted === undefined ? undefined : clusterOmittedLines(block.text, omitted)
1505
- if (census !== undefined) replacementText = `${output.text}
1506
- [... ${census} ...]`
1507
- }
1508
- const plan = this.plan(
1509
- candidate,
1510
- [{ ...block, text: replacementText }],
1511
- sourceSeq,
1512
- output.reducer,
1513
- 'pressure',
1514
- 'history',
1515
- policy.historyMode,
1516
- view,
1517
- { ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }) },
1518
- )
1519
- if (plan === null) continue
1520
- planned.push(plan)
1521
- reclaim += plan.charsBefore - plan.charsAfter
1522
- if (reclaim >= required) break
1523
- }
1524
- // Linked batches must reach the deadline target; unlinked batches keep
1525
- // the traditional minimum-reclaim commit threshold.
1526
- if (reclaim >= batchTarget && planned.length > 0) return historyOutcome(planned)
1527
- return lastChance
1528
- ? { kind: 'cannot-reach-deadline-target', reclaim, required }
1529
- : { kind: 'insufficient-reclaim', reclaim, required }
1530
- }
1531
-
1532
- private protectedHistoryResultSeqs(
1533
- session: Session,
1534
- policy: CompressionPolicy,
1535
- view: CompactionTokenView,
1536
- ): Set<number> {
1537
- const candidates = this.snapshot(session, view)
1538
- return this.protectedHistoryCandidateSeqs(candidates, policy)
1539
- }
1540
-
1541
- /** Select the newest completed tool calls and token tail for History-derived stages. */
1542
- private protectedHistoryCandidateSeqs(
1543
- candidates: readonly SnapshotCandidate[],
1544
- policy: CompressionPolicy,
1545
- ): Set<number> {
1546
- const protectedSeqs = new Set<number>()
1547
- for (let index = candidates.length - 1;
1548
- index >= 0 && candidates.length - index <= policy.historyKeepRecentToolCalls;
1549
- index--) {
1550
- const candidate = candidates[index]
1551
- if (candidate !== undefined) protectedSeqs.add(candidate.seq)
1552
- }
1553
- let recentChars = 0
1554
- for (let index = candidates.length - 1;
1555
- index >= 0 && recentChars < charsForTokens(policy.historyKeepRecentTokens);
1556
- index--) {
1557
- const candidate = candidates[index]
1558
- if (candidate === undefined) continue
1559
- protectedSeqs.add(candidate.seq)
1560
- recentChars += candidate.characterPressure
1561
- }
1562
- return protectedSeqs
1563
- }
1564
-
1565
- /** Atomically replace at most one oldest safe completed tool-call group. */
1566
- private landOldestTailTrimGroup(
1567
- session: Session,
1568
- policy: CompressionPolicy,
1569
- view: CompactionTokenView,
1570
- ): void {
1571
- const tailTrim = policy.tailTrim
1572
- if (tailTrim?.enabled !== true) return
1573
- const events = sessionEvents(session)
1574
- if (view.currentSurfaceChars <= charsForTokens(tailTrim.triggerTokens)) {
1575
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1576
- 'at-or-below-trigger', {
1577
- measurementKind: 'characters',
1578
- currentTokens: charsToTokens(view.currentSurfaceChars),
1579
- triggerTokens: tailTrim.triggerTokens,
1580
- })
1581
- return
1582
- }
1583
- const surfaceCount = view.currentSurface
1584
- const exactSurface = surfaceCount.kind === 'exact-tokenizer' ? surfaceCount : undefined
1585
- if (!this.hasRecoveryTool(session)) {
1586
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1587
- 'recovery-tool-unavailable', {
1588
- measurementKind: 'characters',
1589
- currentTokens: charsToTokens(view.currentSurfaceChars),
1590
- triggerTokens: tailTrim.triggerTokens,
1591
- })
1592
- return
1593
- }
1594
- if (!hasOpenTurn(session)) {
1595
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1596
- 'no-open-turn', {
1597
- measurementKind: 'characters',
1598
- currentTokens: charsToTokens(view.currentSurfaceChars),
1599
- triggerTokens: tailTrim.triggerTokens,
1600
- })
1601
- return
1602
- }
1603
- const protectedResults = this.protectedHistoryResultSeqs(session, policy, view)
1604
- const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1605
- const nodeChars = new Map(view.measuredNodes.map(node => [node.seq, node.characterPressure]))
1606
- const heuristic = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1607
- const completedTurns = new Set<number>()
1608
- const completedSteps = new Set<string>()
1609
- for (const event of events) {
1610
- if (event.type === 'turn/end') completedTurns.add(event.data.turn)
1611
- else if (event.type === 'step/end') completedSteps.add(`${String(event.data.turn)}:${String(event.data.step)}`)
1612
- }
1613
- const firstCompletedSurfaceTurn = session.surface.nodes
1614
- .map(seq => events[seq])
1615
- .filter((event): event is SessionEvent<'assistant/message'> | SessionEvent<'tool/result'> =>
1616
- (event?.type === 'assistant/message' || event?.type === 'tool/result')
1617
- && completedTurns.has(event.data.turn))
1618
- .reduce<number | undefined>(
1619
- (first, event) => first === undefined ? event.data.turn : Math.min(first, event.data.turn),
1620
- undefined,
1621
- )
1622
- const nodes = [...session.surface.nodes]
1623
- for (let index = 0; index < nodes.length; index++) {
1624
- const assistantSeq = nodes[index]
1625
- if (assistantSeq === undefined) continue
1626
- const assistant = events[assistantSeq]
1627
- if (assistant?.type !== 'assistant/message'
1628
- || assistant.data.interrupted === true
1629
- || assistant.data.message.content.length === 0
1630
- || assistant.data.message.content.some(block => block.type !== 'tool-call')
1631
- || assistant.data.turn === firstCompletedSurfaceTurn
1632
- || !completedTurns.has(assistant.data.turn)
1633
- || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue
1634
- const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
1635
- if (calls.some(call => call.name === 'context_compression_retrieve')) continue
1636
- const callIds = calls.map(call => String(call.id))
1637
- if (new Set(callIds).size !== callIds.length) continue
1638
- const resultSeqs = nodes.slice(index + 1, index + 1 + calls.length)
1639
- if (resultSeqs.length !== calls.length || resultSeqs.some(seq => protectedResults.has(seq))) continue
1640
- const results = resultSeqs.map(seq => events[seq])
1641
- if (results.some((event): boolean => {
1642
- if (event?.type !== 'tool/result'
1643
- || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
1644
- || event.data.error !== undefined) return true
1645
- const block = event.data.message.content[0]
1646
- if (block.isError === true) return true
1647
- // Images and other rich inner blocks stay fail-open: a TailTrim stub
1648
- // would silently delete them from the active context.
1649
- return block.content.some(contentBlock => contentBlock.type !== 'text')
1650
- })) continue
1651
- const next = events[nodes[index + 1 + calls.length] ?? -1]
1652
- if (next?.type === 'tool/result'
1653
- && next.data.turn === assistant.data.turn
1654
- && next.data.step === assistant.data.step) continue
1655
- const resultIds = results.map(event => event?.type === 'tool/result'
1656
- ? String(event.data.message.source.callId) : '')
1657
- if (new Set(resultIds).size !== resultIds.length
1658
- || resultIds.some((id, resultIndex) => id !== callIds[resultIndex])) continue
1659
- const shadowedSeqs = [assistantSeq, ...resultSeqs]
1660
- const roots = shadowedSeqs.map(seq => this.uniqueAppendRoot(session, seq))
1661
- if (roots.some(root => root === null)) continue
1662
- const sourceEventSeqs = roots as number[]
1663
- if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) continue
1664
- // Exact tokens stay telemetry-only: they are recorded when every
1665
- // shadowed node shares the surface tokenizer identity, and derived from
1666
- // characters otherwise. The skip decisions above and below are all
1667
- // character-based.
1668
- let exactTokensBefore: number | undefined
1669
- if (exactSurface !== undefined) {
1670
- let sum = 0
1671
- let allExact = true
1672
- for (const seq of shadowedSeqs) {
1673
- const count = measured.get(seq)
1674
- if (count?.kind !== 'exact-tokenizer'
1675
- || count.tokenizerId !== exactSurface.tokenizerId
1676
- || count.tokenizerRevision !== exactSurface.tokenizerRevision) {
1677
- allExact = false
1678
- break
1679
- }
1680
- sum += count.tokens
1681
- }
1682
- if (allExact) exactTokensBefore = sum
1683
- }
1684
- const charsBefore = shadowedSeqs.reduce((sum, seq) => sum + (nodeChars.get(seq) ?? 0), 0)
1685
- const manifestSeq = events.length
1686
- const ref = tailTrimRef(String(session.id), manifestSeq)
1687
- const stub = tailTrimStub(ref, calls.map(call => call.name), sourceEventSeqs)
1688
- if (stub === null) continue
1689
- const stubChars = codePointLength(stub)
1690
- if (stubChars <= 0
1691
- || charsBefore - stubChars < charsForTokens(policy.historyMinReclaimTokens)) continue
1692
- let exactTokensAfter: number | undefined
1693
- if (exactTokensBefore !== undefined && exactSurface !== undefined) {
1694
- const stubCount = countExactCanonicalTextFields(
1695
- [stub],
1696
- candidate => view.countCanonicalText(candidate),
1697
- 'TailTrim group stub',
1698
- )
1699
- if (stubCount.kind === 'exact-tokenizer'
1700
- && stubCount.tokenizerId === exactSurface.tokenizerId
1701
- && stubCount.tokenizerRevision === exactSurface.tokenizerRevision) {
1702
- exactTokensAfter = stubCount.tokens
1703
- }
1704
- }
1705
- const exact = exactTokensBefore !== undefined && exactTokensAfter !== undefined
1706
- const tokensBefore = exactTokensBefore ?? charsToTokens(charsBefore)
1707
- const tokensAfter = exactTokensAfter ?? charsToTokens(stubChars)
1708
- const heuristicTokens = shadowedSeqs.reduce((sum, seq) => sum + (heuristic.get(seq) ?? 0), 0)
1709
- const range = { start: assistantSeq, end: resultSeqs.at(-1) ?? assistantSeq }
1710
- if (!this.reserveTailTrimBoundaryAttempt(session)) {
1711
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1712
- 'already-attempted-at-request-boundary', {
1713
- measurementKind: 'characters',
1714
- currentTokens: charsToTokens(view.currentSurfaceChars),
1715
- triggerTokens: tailTrim.triggerTokens,
1716
- })
1717
- return
1718
- }
1719
- const manifest = session.append('compaction/prune', {
1720
- shadowedRange: range,
1721
- shadowedSeqs,
1722
- shadowedTokenCount: heuristicTokens,
1723
- })
1724
- let replacement: SessionEvent<'user/message'>
1725
- try {
1726
- replacement = session.append('user/message', tailTrimMessage(stub), {
1727
- surfaceOp: { op: 'replace', ...range },
1728
- sourceEventSeqs: [manifest.seq, ...shadowedSeqs],
1729
- })
1730
- } catch (error) {
1731
- this.auditPublicationFailure(
1732
- session,
1733
- 'pressure',
1734
- 'tail-trim',
1735
- manifest.seq,
1736
- error,
1737
- )
1738
- return
1739
- }
1740
- emitCompressionAudit(this.ctx.logger, {
1741
- schemaVersion: 1,
1742
- kind: 'rewrite',
1743
- sessionId: String(session.id),
1744
- profile: policy.profile,
1745
- component: 'tail-trim',
1746
- stage: 'pressure',
1747
- reducer: 'pair-preserving-tail-trim',
1748
- manifestEventType: 'compaction/prune',
1749
- manifestSeq: manifest.seq,
1750
- replacementSeq: replacement.seq,
1751
- sourceSeqs: sourceEventSeqs,
1752
- tokensBefore,
1753
- tokensAfter,
1754
- tokensRemoved: tokensBefore - tokensAfter,
1755
- measurementBasis: exact ? 'exact-tokenizer' : 'characters',
1756
- tokenizerId: exact === true && exactSurface !== undefined
1757
- ? exactSurface.tokenizerId
1758
- : 'characters',
1759
- tokenizerRevision: exact === true && exactSurface !== undefined
1760
- ? exactSurface.tokenizerRevision
1761
- : 'chars-per-token-4.0',
1762
- })
1763
- return
1764
- }
1765
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1766
- 'no-safe-eligible-tool-group', {
1767
- measurementKind: 'characters',
1768
- currentTokens: charsToTokens(view.currentSurfaceChars),
1769
- triggerTokens: tailTrim.triggerTokens,
1770
- })
1771
- }
1772
-
1773
- private reserveTailTrimBoundaryAttempt(session: Session): boolean {
1774
- const boundary = this.state.activeRequestBoundaries.get(session)
1775
- if (boundary === undefined) return true
1776
- if (this.state.tailTrimBoundaryAttempts.get(session) === boundary) return false
1777
- this.state.tailTrimBoundaryAttempts.set(session, boundary)
1778
- return true
1779
- }
1780
-
1781
- private uniqueAppendRoot(session: Session, seq: number): number | null {
1782
- const events = sessionEvents(session)
1783
- const pending: Array<{ seq: number; depth: number }> = [{ seq, depth: 0 }]
1784
- const visited = new Set<number>()
1785
- const roots = new Set<number>()
1786
- while (pending.length > 0) {
1787
- const next = pending.pop()
1788
- if (next === undefined || next.depth > 64 || visited.has(next.seq)) continue
1789
- visited.add(next.seq)
1790
- if (visited.size > 64) return null
1791
- const event = events[next.seq]
1792
- if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
1793
- if (event.surfaceOp === 'append') roots.add(event.seq)
1794
- else if (typeof event.surfaceOp === 'object') {
1795
- const sources = event.sourceEventSeqs
1796
- if (sources === undefined || sources.length === 0) return null
1797
- for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
1798
- } else return null
1799
- if (roots.size > 1) return null
1800
- }
1801
- return roots.size === 1 ? [...roots][0] ?? null : null
1802
- }
1803
-
1804
- private plan(
1805
- candidate: SnapshotCandidate,
1806
- content: ContentBlock[],
1807
- sourceSeq: number,
1808
- reducer: string,
1809
- stage: PruneStage,
1810
- component: CompressionAuditComponent,
1811
- historyMode: HistoryMode | undefined,
1812
- view: CompactionTokenView,
1813
- options: { readonly noNetSavingsGuard?: boolean, readonly elidedLines?: number } = {},
1814
- ): PlannedReplacement | null {
1815
- const charsBefore = candidate.characterPressure
1816
- const charsAfter = pressureCost(content)
1817
- // Character proof replaces the exact-tokenizer precondition: a reduction
1818
- // must shrink the decision surface regardless of the routed model id.
1819
- if (charsAfter <= 0 || charsAfter >= charsBefore) return null
1820
- // Tokens are telemetry only: exact when both sides share one bundled
1821
- // tokenizer identity, otherwise derived from the character measurement.
1822
- const countBefore = candidate.count
1823
- const countAfter = countToolContent(content, view)
1824
- const exact = countBefore.kind === 'exact-tokenizer'
1825
- && countAfter.kind === 'exact-tokenizer'
1826
- && countAfter.tokenizerId === countBefore.tokenizerId
1827
- && countAfter.tokenizerRevision === countBefore.tokenizerRevision
1828
- const tokensBefore = exact ? countBefore.tokens : charsToTokens(charsBefore)
1829
- const tokensAfter = exact ? countAfter.tokens : charsToTokens(charsAfter)
1830
- // TokenPilot-style no-net-savings: even when the exact tokenizer reports a
1831
- // saving, a replacement whose text is not smaller than its original adds
1832
- // noise without reclaiming context. Text-level because the placeholder
1833
- // guidance lines (source refs, retrieval hints) must pay for themselves.
1834
- if (options.noNetSavingsGuard === true) {
1835
- const originalBlocks = onlyTextBlocks(candidate.event.data.message.content[0].content)
1836
- const replacementBlocks = onlyTextBlocks(content)
1837
- if (originalBlocks !== null && replacementBlocks !== null) {
1838
- const originalChars = originalBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
1839
- const replacementChars = replacementBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
1840
- if (replacementChars >= originalChars) return null
1841
- }
1842
- }
1843
- return {
1844
- candidate,
1845
- content,
1846
- sourceSeq,
1847
- reducer,
1848
- stage,
1849
- component,
1850
- ...historyMode === undefined ? {} : { historyMode },
1851
- charsBefore,
1852
- charsAfter,
1853
- tokensBefore,
1854
- tokensAfter,
1855
- measurementBasis: exact ? 'exact-tokenizer' : 'characters',
1856
- tokenizerId: exact ? countBefore.tokenizerId : 'characters',
1857
- tokenizerRevision: exact ? countBefore.tokenizerRevision : 'chars-per-token-4.0',
1858
- ...options.elidedLines === undefined ? {} : { elidedLines: options.elidedLines },
1859
- }
1860
- }
1861
-
1862
- private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
1863
- const { candidate } = plan
1864
- const result = candidate.event.data.message.content[0]
1865
- const message = freezeMessage<ToolResultMessage>({
1866
- ...candidate.event.data.message,
1867
- content: [{ ...result, content: plan.content }] as [typeof result],
1868
- })
1869
- const manifest = session.append('compaction/prune', {
1870
- shadowedRange: { start: candidate.seq, end: candidate.seq },
1871
- shadowedSeqs: [candidate.seq],
1872
- shadowedTokenCount: candidate.shadowedHeuristicTokenCount,
1873
- })
1874
- let replacement: SessionEvent<'tool/result'>
1875
- try {
1876
- replacement = session.append('tool/result', {
1877
- ...candidate.event.data,
1878
- message,
1879
- }, {
1880
- surfaceOp: { op: 'replace', start: candidate.seq, end: candidate.seq },
1881
- sourceEventSeqs: [candidate.seq],
1882
- })
1883
- } catch (error) {
1884
- this.auditPublicationFailure(
1885
- session,
1886
- plan.stage,
1887
- plan.component,
1888
- manifest.seq,
1889
- error,
1890
- )
1891
- return null
1892
- }
1893
- emitCompressionAudit(this.ctx.logger, {
1894
- schemaVersion: 1,
1895
- kind: 'rewrite',
1896
- sessionId: String(session.id),
1897
- profile: this.activeSettings(session).profile,
1898
- component: plan.component,
1899
- stage: plan.stage,
1900
- reducer: plan.reducer,
1901
- ...plan.historyMode === undefined ? {} : { historyMode: plan.historyMode },
1902
- manifestEventType: 'compaction/prune',
1903
- manifestSeq: manifest.seq,
1904
- replacementSeq: replacement.seq,
1905
- sourceSeqs: [plan.sourceSeq],
1906
- tokensBefore: plan.tokensBefore,
1907
- tokensAfter: plan.tokensAfter,
1908
- tokensRemoved: plan.tokensBefore - plan.tokensAfter,
1909
- measurementBasis: plan.measurementBasis,
1910
- tokenizerId: plan.tokenizerId,
1911
- tokenizerRevision: plan.tokenizerRevision,
1912
- // task_4c/G7 telemetry: original-event lines the reducer elided. Audit
1913
- // record ONLY — the replacement content is untouched by this field.
1914
- ...plan.elidedLines === undefined ? {} : { elidedLines: plan.elidedLines },
1915
- })
1916
- return {
1917
- originalSeq: candidate.seq,
1918
- sourceSeq: plan.sourceSeq,
1919
- replacementSeq: replacement.seq,
1920
- callId: candidate.event.data.message.source.callId,
1921
- reducer: plan.reducer,
1922
- stage: plan.stage,
1923
- charsBefore: plan.charsBefore,
1924
- charsAfter: plan.charsAfter,
1925
- tokensBefore: plan.tokensBefore,
1926
- tokensAfter: plan.tokensAfter,
1927
- }
1928
- }
1929
-
1930
- private landAll(session: Session, plans: readonly PlannedReplacement[]): PrunedEntry[] {
1931
- if (plans.length === 0) return []
1932
- if (!this.hasRecoveryTool(session)) {
1933
- this.warnOnce(
1934
- session,
1935
- 'missing-context-retrieve',
1936
- 'context-compression kept original tool results because context_compression_retrieve is unavailable',
1937
- )
1938
- return []
1939
- }
1940
- if (!hasOpenTurn(session)) {
1941
- throw new Error('tool-result pruning cannot append a surface replacement outside any open turn')
1942
- }
1943
- const landed: PrunedEntry[] = []
1944
- for (const plan of plans) {
1945
- const entry = this.land(session, plan)
1946
- if (entry === null) break
1947
- landed.push(entry)
1948
- }
1949
- return landed
1950
- }
1951
-
1952
- private hasRecoveryTool(session: Session): boolean {
1953
- const tools = this.ctx.get('tools')
1954
- if (tools === undefined) return false
1955
- const agent = this.ctx.get('agents')?.get(session.id)
1956
- return tools.get('context_compression_retrieve', agent) !== undefined
1957
- }
1958
-
1959
- private auditHistoryEvaluation(
1960
- session: Session,
1961
- policy: CompressionPolicy,
1962
- view: CompactionTokenView,
1963
- allowed: boolean,
1964
- outcome: HistoryPlanOutcome,
1965
- ): void {
1966
- if (policy.historyMode === 'disabled') {
1967
- this.auditComponent(session, policy, 'history', 'pressure', 'disabled', 'profile-policy', {
1968
- historyMode: policy.historyMode,
1969
- })
1970
- return
1971
- }
1972
- if (!allowed && outcome.kind === 'planned') {
1973
- // The authority gate itself refused: below the frozen micro deadline
1974
- // (capacity-pressure) or the adaptive cost estimate rejected the batch.
1975
- const deadlineTrigger = policy.microDeadlineTokens
1976
- const capacity = deadlineTrigger === undefined ? session.requestContext()?.contextWindow : undefined
1977
- const capacityTrigger = deadlineTrigger !== undefined
1978
- ? deadlineTrigger
1979
- : Number.isSafeInteger(capacity) && capacity !== undefined && capacity > 0
1980
- ? Math.floor(capacity * CAPACITY_PRESSURE_RATIO)
1981
- : undefined
1982
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
1983
- policy.historyMode === 'capacity-pressure'
1984
- ? 'below-micro-deadline' : 'adaptive-cost-rejected', {
1985
- historyMode: policy.historyMode,
1986
- measurementKind: 'characters',
1987
- currentTokens: view.totalTokens,
1988
- ...(capacityTrigger === undefined ? {} : { triggerTokens: capacityTrigger }),
1989
- })
1990
- return
1991
- }
1992
- const deadline = policy.microDeadlineTokens
1993
- const lastChance = deadline !== undefined && view.totalTokens >= deadline
1994
- const detail = (extra: Readonly<Record<string, number>> = {}): Readonly<{
1995
- historyMode?: HistoryMode
1996
- measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
1997
- currentTokens?: number
1998
- triggerTokens?: number
1999
- reclaimTokens?: number
2000
- requiredTokens?: number
2001
- }> => ({
2002
- historyMode: policy.historyMode,
2003
- measurementKind: 'characters',
2004
- currentTokens: view.totalTokens,
2005
- ...(outcome.kind === 'insufficient-reclaim' || outcome.kind === 'cannot-reach-deadline-target'
2006
- ? { reclaimTokens: outcome.reclaim, requiredTokens: outcome.required }
2007
- : {}),
2008
- ...extra,
2009
- })
2010
- switch (outcome.kind) {
2011
- case 'below-profile-trigger':
2012
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2013
- 'below-profile-trigger', detail({ triggerTokens: policy.historyTriggerTokens }))
2014
- return
2015
- case 'no-safe-candidates':
2016
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2017
- 'no-safe-candidates', detail({ triggerTokens: policy.historyTriggerTokens }))
2018
- return
2019
- case 'protected-working-set':
2020
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2021
- 'protected-working-set', detail({ triggerTokens: policy.historyTriggerTokens }))
2022
- return
2023
- case 'insufficient-reclaim':
2024
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2025
- 'insufficient-reclaim', detail({ triggerTokens: policy.historyTriggerTokens }))
2026
- return
2027
- case 'cannot-reach-deadline-target':
2028
- // Planning engaged through the full-request last-chance gate; the
2029
- // routine trigger numbers below would misdescribe why nothing landed.
2030
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2031
- 'cannot-reach-deadline-target', detail(lastChance ? { triggerTokens: deadline } : {}))
2032
- return
2033
- case 'planned':
2034
- // A committed batch that landed nothing means the recovery tool was
2035
- // unavailable at landing time; a degenerate empty commit reads as an
2036
- // unreachable target instead.
2037
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2038
- outcome.plans.length > 0 ? 'recovery-tool-unavailable' : 'insufficient-reclaim',
2039
- detail({ triggerTokens: lastChance ? deadline : policy.historyTriggerTokens }))
2040
- return
2041
- /* v8 ignore next -- closed-union exhaustiveness guard */
2042
- default:
2043
- return assertNever(outcome, 'history plan outcome')
2044
- }
2045
- }
2046
-
2047
- private auditComponent(
2048
- session: Session,
2049
- policy: CompressionPolicy,
2050
- component: CompressionAuditComponent,
2051
- stage: PruneStage,
2052
- status: CompressionAuditEvaluationStatus,
2053
- reason: string,
2054
- detail: Readonly<{
2055
- historyMode?: HistoryMode
2056
- measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
2057
- currentTokens?: number
2058
- triggerTokens?: number
2059
- targetTokens?: number
2060
- reclaimTokens?: number
2061
- requiredTokens?: number
2062
- }> = {},
2063
- ): void {
2064
- emitCompressionAudit(this.ctx.logger, {
2065
- schemaVersion: 1,
2066
- kind: 'component-evaluation',
2067
- sessionId: String(session.id),
2068
- profile: policy.profile,
2069
- component,
2070
- stage,
2071
- status,
2072
- reason,
2073
- ...detail,
2074
- })
2075
- }
2076
-
2077
- private auditFailure(
2078
- session: Session,
2079
- stage: PruneStage,
2080
- operation:
2081
- | 'request-boundary'
2082
- | 'terminal-pass'
2083
- | 'policy-resolution'
2084
- | 'summary-locator'
2085
- | 'publication',
2086
- error: unknown,
2087
- ): void {
2088
- emitCompressionAudit(this.ctx.logger, {
2089
- schemaVersion: 1,
2090
- kind: 'failure',
2091
- sessionId: String(session.id),
2092
- stage,
2093
- operation,
2094
- errorName: error instanceof Error ? error.name : 'UnknownError',
2095
- errorMessage: error instanceof Error ? error.message : String(error),
2096
- })
2097
- }
2098
-
2099
- private auditPublicationFailure(
2100
- session: Session,
2101
- stage: PruneStage,
2102
- component: CompressionAuditComponent,
2103
- manifestSeq: number,
2104
- error: unknown,
2105
- ): void {
2106
- emitCompressionAudit(this.ctx.logger, {
2107
- schemaVersion: 1,
2108
- kind: 'failure',
2109
- sessionId: String(session.id),
2110
- stage,
2111
- operation: 'publication',
2112
- component,
2113
- manifestSeq,
2114
- errorName: error instanceof Error ? error.name : 'UnknownError',
2115
- errorMessage: 'surface replacement append failed after compaction/prune committed',
2116
- })
2117
- }
2118
-
2119
- private warnExactUnavailable(
2120
- session: Session,
2121
- view: CompactionTokenView,
2122
- gate: 'native' | 'fresh' | 'aggregate' | 'history' | 'tailtrim',
2123
- ): void {
2124
- const provider = view.providerRoute ?? 'unbound-provider'
2125
- const model = view.modelId ?? 'unbound-model'
2126
- this.warnOnce(
2127
- session,
2128
- `exact-tokenizer:${gate}:${provider}\0${model}`,
2129
- 'context-compression %s is measuring on the character basis: exact tokenizer counts are unavailable for %s/%s',
2130
- gate,
2131
- provider,
2132
- model,
2133
- )
2134
- }
2135
-
2136
- private warnOnce(
2137
- session: Session,
2138
- key: string,
2139
- message: string,
2140
- ...args: unknown[]
2141
- ): void {
2142
- let warned = this.state.warnedFailures.get(session)
2143
- if (warned === undefined) {
2144
- warned = new Set()
2145
- this.state.warnedFailures.set(session, warned)
2146
- }
2147
- if (warned.has(key)) return
2148
- warned.add(key)
2149
- this.ctx.logger.warn(message, ...args)
2150
- }
2151
-
2152
- }
2153
-
2154
- export default ToolResultPruner
1
+ /**
2
+ * Replay-safe, model-free context-compression selector for tool results.
3
+ *
4
+ * Standard profiles never rewrite ordinary Assistant prose. The only durable
5
+ * replacements emitted here are content-only `tool/result` rewrites whose
6
+ * full source remains in the append-only Session log.
7
+ *
8
+ * @module dsh-context-compression-improved-runtime
9
+ */
10
+
11
+ import { Service } from '@deepseek-ai/cordis'
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import z from '@deepseek-ai/schemastery'
14
+ import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
15
+ import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm'
16
+ import { SessionSeq } from '@deepseek-ai/dsh-session'
17
+ import type { Session, SessionEvent, ToolResultMessage } from '@deepseek-ai/dsh-session'
18
+ import type {} from '@deepseek-ai/dsh-agent'
19
+ import type {} from '@deepseek-ai/dsh-compaction'
20
+ import type {} from '@deepseek-ai/dsh-settings'
21
+ import type {
22
+ CompactionTokenView,
23
+ ObservedPromptUsage,
24
+ } from './runtime/measurement.ts'
25
+ import { measureForCompaction, officialRequestUsage } from './runtime/measurement.ts'
26
+ import { eventBySeq, sessionEvents } from './runtime/session-events.ts'
27
+ import { countExactCanonicalTextFields } from './runtime/token-count.ts'
28
+ import type {} from '@deepseek-ai/dsh-tools'
29
+ import {
30
+ tailTrimMessage,
31
+ tailTrimRef,
32
+ tailTrimStub,
33
+ } from './runtime/tail-trim.ts'
34
+ import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
35
+ import type { PrunerState } from './pruner/state.ts'
36
+ import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
37
+ import type { ToolCallInfo, SnapshotCandidate, PlannedReplacement, HistoryPlanOutcome } from './pruner/types.ts'
38
+ import {
39
+ onlyTextBlock,
40
+ onlyTextBlocks,
41
+ countToolContent,
42
+ sameProviderMeasurementKey,
43
+ unavailableCount,
44
+ recoveryMarker,
45
+ summarize,
46
+ emptyResult,
47
+ pressureCost,
48
+ nativePruneContent,
49
+ } from './pruner/content.ts'
50
+ import {
51
+ hasOpenTurn,
52
+ rootToolResultSeq,
53
+ sourceRef as sourceRefFn,
54
+ latestCompletedToolStep,
55
+ routeAuditFact,
56
+ tokenizerAuditFact,
57
+ isError,
58
+ historyOutcome,
59
+ } from './pruner/session.ts'
60
+ import { buildLocatorBlock, findCompactionTrace } from './runtime/tokenpilot/locator.ts'
61
+ import { clusterOmittedLines, isSupersededRead, toolCallPath } from './runtime/tokenpilot/read-state.ts'
62
+ import {
63
+ Estimator,
64
+ backoffCooldownMs,
65
+ buildEstimatorSystemPrompt,
66
+ buildEstimatorUserPrompt,
67
+ isCoolingDown,
68
+ parseEstimatorAnswerDetailed,
69
+ type EstimatorFailures,
70
+ type EstimatorSample,
71
+ } from './runtime/tokenpilot/estimator.ts'
72
+ import {
73
+ adviseCandidates,
74
+ DEFAULT_ADVICE_ALPHA,
75
+ DEFAULT_ADVICE_HIGH_IMPACT_TOKENS,
76
+ } from './runtime/tokenpilot/benefit.ts'
77
+ import { SideChannel } from './runtime/tokenpilot/sidechannel.ts'
78
+ import {
79
+ advisorCandidatePreview,
80
+ collectTailText,
81
+ collectTaskSemantics,
82
+ runSessionAdvisorPass,
83
+ } from './runtime/tokenpilot/advisor.ts'
84
+ import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
85
+ import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
86
+ import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
87
+ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
88
+ import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
89
+ import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
90
+ import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
91
+ import { observeContextUsage } from './runtime/monitor.ts'
92
+
93
+ import {
94
+ DedupeTable,
95
+ dedupeHash,
96
+ dedupePlaceholder,
97
+ flattenPlainText,
98
+ } from './runtime/tokenpilot/dedup.ts'
99
+ import { getSavingsLedger } from './runtime/savings.ts'
100
+
101
+ /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
102
+ function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
103
+ return flattenPlainText(candidate.event.data.message.content)
104
+ }
105
+ import {
106
+ charsForTokens,
107
+ charsToTokens,
108
+ codePointLength,
109
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
110
+ ContextCompressionSettingsSchema,
111
+ parseContextCompressionSettings,
112
+ DEFAULTS,
113
+ PRUNE_MARKER,
114
+ resolveConfig,
115
+ resolvePolicy,
116
+ } from './runtime/config.ts'
117
+ import {
118
+ historicalPlaceholder,
119
+ reduceFreshToolResult,
120
+ verifyReduction,
121
+ } from './runtime/reducers.ts'
122
+ import type {
123
+ CompressionPolicy,
124
+ ContextCompressionSettings,
125
+ HistoryMode,
126
+ PrunedEntry,
127
+ PruneResult,
128
+ PruneSessionOptions,
129
+ PruneStage,
130
+ ToolResultPruneConfig,
131
+ } from './runtime/types.ts'
132
+ import { COMPRESSION_PROFILES } from './runtime/types.ts'
133
+ import {
134
+ decideConservativeAdaptive,
135
+ deriveAdaptiveTokenBounds,
136
+ } from './runtime/adaptive-cost.ts'
137
+ import {
138
+ DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
139
+ priceOfficialDeepSeekUsage,
140
+ resolveOfficialDeepSeekPrice,
141
+ } from './runtime/deepseek-official-pricing.ts'
142
+ import { emitCompressionAudit } from './runtime/audit.ts'
143
+ import { assertNever, deepFreeze } from './runtime/value.ts'
144
+ import type {
145
+ CompressionAuditComponent,
146
+ CompressionAuditEvaluationStatus,
147
+ } from './runtime/audit.ts'
148
+
149
+ export {
150
+ codePointLength,
151
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
152
+ ContextCompressionSettingsSchema,
153
+ parseContextCompressionSettings,
154
+ AUTO_COMPACT_THRESHOLD_LIMITS,
155
+ DEFAULTS,
156
+ isCompressionProfile,
157
+ isValidAutoCompactThresholdPercent,
158
+ PRUNE_MARKER,
159
+ resolveConfig,
160
+ resolvePolicy,
161
+ } from './runtime/config.ts'
162
+ export {
163
+ CustomCompressionPolicySchema,
164
+ DEFAULT_CUSTOM_COMPRESSION_POLICY,
165
+ resolveCustomPolicy,
166
+ } from './runtime/custom-policy.ts'
167
+ export type { CustomPolicyResolutionOptions } from './runtime/custom-policy.ts'
168
+ export { historicalPlaceholder, normalizeTerminalText, reduceFreshToolResult, verifyReduction } from './runtime/reducers.ts'
169
+ export { measureForCompaction } from './runtime/measurement.ts'
170
+ export type {
171
+ CompactionTokenView,
172
+ MeasuredTokenSurfaceNode,
173
+ } from './runtime/measurement.ts'
174
+ export type {
175
+ AutoCompactSettings,
176
+ CodeSkeletonSettings,
177
+ CompressionPolicy,
178
+ CompressionProfile,
179
+ CustomCompressionBudget,
180
+ CustomCompressionPolicy,
181
+ CustomCompressionUnit,
182
+ CustomHistoryPolicy,
183
+ CustomPrefixPolicy,
184
+ CustomTailTrimPolicy,
185
+ CustomCompressionPolicyV1,
186
+ CustomCompressionPolicyV2,
187
+ CustomCompressionPolicyV3,
188
+ ContextCompressionSettings,
189
+ HistoryMode,
190
+ PrunedEntry,
191
+ PruneResult,
192
+ PruneSessionOptions,
193
+ PruneStage,
194
+ ToolResultPruneConfig,
195
+ } from './runtime/types.ts'
196
+
197
+ // Re-export the canonical profile list from the type module as a runtime value.
198
+ export { COMPRESSION_PROFILES } from './runtime/types.ts'
199
+
200
+ declare module '@deepseek-ai/cordis' {
201
+ interface Context {
202
+ toolResultPruner: ToolResultPruner
203
+ }
204
+ }
205
+
206
+ /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
207
+ export class ToolResultPruner extends Service {
208
+ static inject = ['tokenMeter']
209
+
210
+ static Config: z<ToolResultPruneConfig> = z.object({
211
+ profile: z.union([...COMPRESSION_PROFILES]).default(DEFAULTS.profile),
212
+ headChars: z.number().step(1).min(0).default(DEFAULTS.headChars),
213
+ tailChars: z.number().step(1).min(0).default(DEFAULTS.tailChars),
214
+ nativeTriggerTokens: z.number().step(1).min(1).required(false),
215
+ nativeTargetTokens: z.number().step(1).min(1).required(false),
216
+ freshTriggerTokens: z.number().step(1).min(1).required(false),
217
+ freshTargetTokens: z.number().step(1).min(1).required(false),
218
+ aggregateTriggerTokens: z.number().step(1).min(1).required(false),
219
+ aggregateTargetTokens: z.number().step(1).min(1).required(false),
220
+ historyTriggerTokens: z.number().step(1).min(1).required(false),
221
+ historyKeepRecentToolCalls: z.number().step(1).min(0).required(false),
222
+ historyKeepRecentTokens: z.number().step(1).min(0).required(false),
223
+ historyMinReclaimTokens: z.number().step(1).min(1).required(false),
224
+ autoCompactThresholdPercent: z.number().step(1).min(50).max(90).required(false),
225
+ })
226
+
227
+ /** Consolidated per-session mutable state. */
228
+ readonly state: PrunerState
229
+
230
+ /** 0.1.5-specific: per-session sets of already-audited native summary seqs. */
231
+ private readonly auditedNativeSummaries = new WeakMap<Session, Set<number>>()
232
+
233
+ constructor(ctx: Context, config: ToolResultPruneConfig = {}) {
234
+ super(ctx, 'toolResultPruner')
235
+ ctx.inject(['tools', 'systemPrompt'], recoveryCtx => {
236
+ installContextCompressionRetrieve(recoveryCtx)
237
+ })
238
+ this.state = {
239
+ config: resolveConfig(config),
240
+ sessionSettings: new WeakMap(),
241
+ firstExposure: new WeakMap(),
242
+ recoveryExemptions: new WeakMap(),
243
+ dedupeTables: new WeakMap(),
244
+ estimatorVerdicts: new WeakMap(),
245
+ estimatorFailures: new WeakMap(),
246
+ warnedFailures: new WeakMap(),
247
+ postflightDiagnostics: new WeakMap(),
248
+ activeRequestBoundaries: new WeakMap(),
249
+ tailTrimBoundaryAttempts: new WeakMap(),
250
+ policyResolutionAudits: new WeakMap(),
251
+ turnClocks: new WeakMap(),
252
+ estimatorRemainingTurns: new WeakMap(),
253
+ advisorChannels: new WeakMap(),
254
+ pendingIntentFolds: new WeakMap(),
255
+ intentFoldedSeqs: new WeakMap(),
256
+ intentBaselines: new WeakMap(),
257
+ }
258
+
259
+ // 会话结束汇总(dsh-token-optimizer monitor 模式的同款体验):输出该会话的
260
+ // 净节省/缓存命中率一行账。事件名探测式注册——老代际不发 session/disposed
261
+ // 时监听器静默闲置,不构成任何行为差异。
262
+ try {
263
+ ;(ctx as unknown as { on: (name: string, handler: (session: Session) => void) => unknown }).on(
264
+ 'session/disposed',
265
+ (session) => {
266
+ try {
267
+ const line = getSavingsLedger().sessionSummaryLine(String(session.id))
268
+ if (line.includes('requests=0') === false || line.includes('net=0(exact)/0(est)') === false) {
269
+ ctx.logger.info('context-compression session savings (%s): %s', String(session.id), line)
270
+ }
271
+ } catch {
272
+ /* 汇总失败不影响 dispose */
273
+ }
274
+ },
275
+ )
276
+ } catch {
277
+ /* 宿主不支持该事件名:静默 */
278
+ }
279
+
280
+ ctx.on('session/event', (session, event) => {
281
+ this.scanForSeededNativeSummary(session)
282
+ if (event.type === 'compaction/summary') {
283
+ this.emitNativeSummaryAudit(session, event.seq, event.data)
284
+ return
285
+ }
286
+ if (event.type === 'compaction/end') {
287
+ // TokenPilot-inspired A2: annotate the landed summary checkpoint with
288
+ // an Exact Sources locator block. Strictly after compaction/end so no
289
+ // open-compaction invariant ever observes the rewrite.
290
+ try {
291
+ this.attachSummaryLocator(session, event.data.compactionId)
292
+ } catch (error: unknown) {
293
+ this.auditFailure(session, 'pressure', 'summary-locator', error)
294
+ ctx.logger.warn('context-compression summary locator failed open: %o', error)
295
+ }
296
+ }
297
+ })
298
+
299
+ // This is the true first-exposure boundary available in the Harness:
300
+ // the preceding step's results are already durable, the new step is open,
301
+ // and the next model request has not yet derived its history.
302
+ ctx.on('agent/pre-step', async ({ agent, signal, turn, step }, next) => {
303
+ const boundary = {}
304
+ this.state.activeRequestBoundaries.set(agent.session, boundary)
305
+ try {
306
+ if (!signal.aborted) {
307
+ try {
308
+ // Only the immediately preceding step can contain results that have
309
+ // not yet been exposed. This freezes both REDUCE and KEEP decisions:
310
+ // older original events are never reconsidered after a profile change.
311
+ this.turnClock(agent.session, turn)
312
+ this.runRequestBoundary(agent.session, turn, step - 1, signal)
313
+ } catch (error: unknown) {
314
+ this.auditFailure(agent.session, 'fresh', 'request-boundary', error)
315
+ ctx.logger.warn('context-compression fresh pass failed open: %o', error)
316
+ }
317
+ }
318
+ const outcome = await next()
319
+ // BasicCompactionEngine's own pre-step may have just landed a Native
320
+ // auto-compact summary (possibly through a seed-reopen that never
321
+ // reaches the event firehose): scan once more after the step opens.
322
+ this.scanForSeededNativeSummary(agent.session)
323
+ return outcome
324
+ } finally {
325
+ if (this.state.activeRequestBoundaries.get(agent.session) === boundary) {
326
+ this.state.activeRequestBoundaries.delete(agent.session)
327
+ }
328
+ }
329
+ }, { prepend: true })
330
+
331
+ ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
332
+ if (signal.aborted) return
333
+ try {
334
+ const step = latestCompletedToolStep(agent.session, turn)
335
+ if (step !== undefined) this.runRequestBoundary(agent.session, turn, step, signal)
336
+ } catch (error: unknown) {
337
+ this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
338
+ ctx.logger.warn('context-compression terminal pass failed open: %o', error)
339
+ }
340
+ // 压缩监控观测:每回合无条件记录上下文占用——面板占用条与
341
+ // 灾难性遗忘区建议的数据源,与 intentSummary 门控解耦(门关也可观测)。
342
+ try {
343
+ observeContextUsage(
344
+ String(agent.session.id),
345
+ measureForCompaction(this.ctx, agent.session).totalTokens,
346
+ this.contextWindowForRequest(agent.session),
347
+ )
348
+ } catch { /* 观测失败静默:面板显示陈旧/空态 */ }
349
+ // TokenPilot-inspired E1: advisory estimator pass, strictly off the
350
+ // synchronous chain. Verdicts only feed the next pressure pass.
351
+ void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
352
+ // Advisory relevance advisor: statistics and suggestions only — its
353
+ // summaries, scores, and decay figure never touch any decision path.
354
+ // Strictly fire-and-forget, with its own backoff state.
355
+ void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
356
+ // Turn-tail intent summary: strictly fire-and-forget like the advisor;
357
+ // the growth gate inside decides whether a summary call is even spent.
358
+ void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
359
+ })
360
+ }
361
+
362
+ /**
363
+ * Measure text content in Unicode code points; non-text blocks cost zero.
364
+ * @param blocks - tool-result content to measure.
365
+ * @returns total Unicode code points across text blocks.
366
+ */
367
+ /**
368
+ * Apply the configured native head/middle/tail transform.
369
+ * @param blocks - original tool-result content.
370
+ * @returns reduced content, or `null` when no reduction is required.
371
+ */
372
+ pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null {
373
+ return nativePruneContent(
374
+ blocks,
375
+ this.state.config.headChars + codePointLength(PRUNE_MARKER) + this.state.config.tailChars,
376
+ this.state.config.headChars,
377
+ this.state.config.tailChars,
378
+ )
379
+ }
380
+
381
+ /**
382
+ * Run one stable-surface pass. `fresh` is invoked before every request and
383
+ * only reduces original oversized results. `pressure` is called by
384
+ * compaction-basic and may additionally age old results at one high-water.
385
+ * @param session - session whose current tool-result surface may be rewritten.
386
+ * @param options - pass stage and optional completed-step coordinates.
387
+ * @returns landed replacements and aggregate Unicode-code-point savings.
388
+ */
389
+ pruneSession(session: Session, options: PruneSessionOptions = {}): PruneResult {
390
+ this.scanForSeededNativeSummary(session)
391
+ const stage = options.stage ?? 'pressure'
392
+ // External callers (compaction-basic) do not carry routed capacity; the
393
+ // runtime resolves it itself so the frozen Auto Compact linkage and the
394
+ // Custom percentage policy see one consistent context window.
395
+ const contextWindowTokens = options.contextWindowTokens ?? this.contextWindowForRequest(session)
396
+ const policy = this.activePolicy(session, contextWindowTokens, stage)
397
+ if (policy === undefined) return emptyResult()
398
+ const profile = policy.profile
399
+ const view = measureForCompaction(this.ctx, session)
400
+ if (stage === 'fresh') {
401
+ // 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
402
+ // 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
403
+ const usage = officialRequestUsage(view)
404
+ if (usage !== undefined) {
405
+ getSavingsLedger().recordUsage(String(session.id), usage)
406
+ }
407
+ return this.decideFreshStep(session, options, policy, view)
408
+ }
409
+ if (profile === 'off') return emptyResult()
410
+
411
+ const landed: PrunedEntry[] = []
412
+ if (policy.nativeToolResultEnabled) {
413
+ const candidates = this.snapshot(session, view)
414
+ const eligible = candidates.filter(candidate => !this.isRecoveryExempt(session, candidate))
415
+ const exactUnavailable = eligible.some(candidate => candidate.count.kind !== 'exact-tokenizer')
416
+ if (exactUnavailable) {
417
+ this.warnExactUnavailable(session, view, 'native')
418
+ }
419
+ const planned = eligible
420
+ .map(candidate => this.planNative(candidate, session, stage, policy, view))
421
+ .filter((entry): entry is PlannedReplacement => entry !== null)
422
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, planned, 'history')))
423
+ if (landed.length === 0) {
424
+ const chars = eligible.map(candidate => candidate.characterPressure)
425
+ this.auditComponent(session, policy, 'native-tool-result', 'pressure', 'skipped',
426
+ chars.length === 0 ? 'no-tool-result-candidates'
427
+ : Math.max(...chars) <= charsForTokens(policy.nativeTriggerTokens) ? 'at-or-below-trigger'
428
+ : planned.length === 0 ? 'no-valid-reduction'
429
+ : 'recovery-tool-unavailable', {
430
+ measurementKind: 'characters',
431
+ ...(chars.length === 0 ? {} : { currentTokens: charsToTokens(Math.max(...chars)) }),
432
+ triggerTokens: policy.nativeTriggerTokens,
433
+ targetTokens: policy.nativeTargetTokens,
434
+ })
435
+ }
436
+ return summarize(landed)
437
+ }
438
+
439
+ let historyOutcome: HistoryPlanOutcome = { kind: 'planned', plans: [] }
440
+ let historyAllowed = false
441
+ if (policy.historyMode === 'adaptive') {
442
+ historyOutcome = this.planHistoricalAging(session, policy, view)
443
+ // Adaptive cost authority is meaningful only after the structural
444
+ // planner has formed a real batch. A planning skip keeps its own reason
445
+ // (for example exact-tokenizer-unavailable) and never becomes a false
446
+ // adaptive-cost-rejected decision merely because it has zero plans.
447
+ if (historyOutcome.kind === 'planned') {
448
+ const capacityPressure = this.capacityPressureActive(session, view, policy)
449
+ historyAllowed = this.adaptiveHistoryAllowed(
450
+ session,
451
+ view,
452
+ historyOutcome.plans,
453
+ capacityPressure,
454
+ )
455
+ if (historyAllowed) {
456
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, 'history')))
457
+ }
458
+ }
459
+ } else {
460
+ historyAllowed = this.historyAllowed(session, policy, view)
461
+ if (historyAllowed) {
462
+ historyOutcome = this.planHistoricalAging(session, policy, view)
463
+ if (historyOutcome.kind === 'planned') {
464
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, 'history')))
465
+ }
466
+ }
467
+ }
468
+ if (!landed.some(entry => entry.stage === 'pressure')) {
469
+ this.auditHistoryEvaluation(session, policy, view, historyAllowed, historyOutcome)
470
+ }
471
+ if (policy.tailTrim?.enabled === true) {
472
+ const tailView = measureForCompaction(this.ctx, session)
473
+ this.landOldestTailTrimGroup(session, policy, tailView)
474
+ } else {
475
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'disabled', 'profile-policy')
476
+ }
477
+ return summarize(landed)
478
+ }
479
+
480
+ private activeSettings(session: Session): ContextCompressionSettings {
481
+ const frozen = this.state.sessionSettings.get(session)
482
+ if (frozen !== undefined) return frozen
483
+ // Harness 0.1.1 brands namespace values through a helper while 0.1.2
484
+ // validates the same public literal at its SettingsProvider boundary.
485
+ const settings = this.ctx.get('settings')?.get(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
486
+ let resolved: ContextCompressionSettings
487
+ let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
488
+ ? 'plugin-config-fallback'
489
+ : 'host-settings'
490
+ let autoCompactThresholdSource: 'generation-config' | 'host-settings' | 'schema-default'
491
+ = settings === undefined ? 'schema-default' : 'host-settings'
492
+ let settingsInvalidFallback: 'lossless-off' | undefined
493
+ try {
494
+ resolved = settings === undefined
495
+ ? ContextCompressionSettingsSchema({ profile: this.state.config.profile } as never)
496
+ // Validate the Host value BEFORE cloning: structuredClone normalizes
497
+ // class/exotic prototypes to Object.prototype and would otherwise
498
+ // erase the very boundary the parser is responsible for enforcing.
499
+ : parseContextCompressionSettings(settings)
500
+ } catch (error: unknown) {
501
+ // A malformed persisted document must fail open LOSSLESSLY: freezing the
502
+ // deployment default could silently re-enable lossy compression the
503
+ // user never chose (for example a stored `off` plus an unknown key), so
504
+ // the session freezes effectively off and keeps every original result.
505
+ const reason = error instanceof Error ? error.message : String(error)
506
+ this.auditFailure(session, 'pressure', 'policy-resolution', error)
507
+ this.warnOnce(
508
+ session,
509
+ `settings-invalid:${reason}`,
510
+ 'context-compression froze this session effectively off because the stored settings document is invalid: %s',
511
+ reason,
512
+ )
513
+ resolved = ContextCompressionSettingsSchema({ profile: 'off' } as never)
514
+ settingsSource = 'plugin-config-fallback'
515
+ autoCompactThresholdSource = 'schema-default'
516
+ settingsInvalidFallback = 'lossless-off'
517
+ }
518
+ if (this.state.config.autoCompactThresholdPercent !== undefined) {
519
+ // The preset overlay froze this generation's threshold into the
520
+ // deployment config; it supersedes the live Host setting so Auto
521
+ // Compact and micro compact can never split across two thresholds.
522
+ resolved = {
523
+ ...resolved,
524
+ autoCompact: { thresholdPercent: this.state.config.autoCompactThresholdPercent },
525
+ }
526
+ autoCompactThresholdSource = 'generation-config'
527
+ }
528
+ const snapshot = deepFreeze(structuredClone(resolved))
529
+ this.state.sessionSettings.set(session, snapshot)
530
+ emitCompressionAudit(this.ctx.logger, {
531
+ schemaVersion: 1,
532
+ kind: 'policy-frozen',
533
+ sessionId: String(session.id),
534
+ settingsSource,
535
+ autoCompactThresholdSource,
536
+ ...settingsInvalidFallback === undefined ? {} : { settingsInvalidFallback },
537
+ settings: snapshot,
538
+ deploymentConfig: this.state.config,
539
+ })
540
+ return snapshot
541
+ }
542
+
543
+ /**
544
+ * TokenPilot-inspired A2: replace the compaction summary checkpoint node
545
+ * with the same summary plus an Exact Sources locator block. Fails open:
546
+ * any unresolved shape (no trace, no checkpoint node, already annotated)
547
+ * leaves the summary untouched.
548
+ */
549
+ private attachSummaryLocator(session: Session, compactionId: string): void {
550
+ const policy = this.activePolicy(session)
551
+ if (policy?.presetOptions?.summaryLocator !== true) return
552
+ const events = sessionEvents(session)
553
+ const trace = findCompactionTrace(events, compactionId)
554
+ if (trace === undefined) return
555
+ const located = buildLocatorBlock(events, trace.summaryShadowedRange)
556
+ if (located === null) return
557
+ const block = located.text
558
+ // Locate the summary checkpoint surface node: the user/message replacement
559
+ // carrying this compaction's checkpoint provenance. Newest match wins.
560
+ let checkpointSeq: number | undefined
561
+ for (const seq of [...session.surface.nodes].reverse()) {
562
+ const event = eventBySeq(events, seq)
563
+ if (event === undefined || event.type !== 'user/message') continue
564
+ const source = (event.data as { source?: { compactionId?: unknown } }).source
565
+ if (source === undefined || source === null) continue
566
+ if (source.compactionId !== compactionId) continue
567
+ checkpointSeq = seq
568
+ break
569
+ }
570
+ if (checkpointSeq === undefined) return
571
+ const original = events[checkpointSeq]
572
+ if (original?.type !== 'user/message') return
573
+ const data = original.data as UserMessage & { source?: unknown }
574
+ const content = data.content.map(block => ({ ...block })) as typeof data.content
575
+ const textBlocks = content.filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text')
576
+ const lastText = textBlocks.at(-1)
577
+ const marker = '## Exact Sources (locators)'
578
+ if (lastText === undefined) return
579
+ if (lastText.text.includes(marker)) return
580
+ lastText.text = `${lastText.text}\n\n${block}`
581
+ // Drop the checkpoint provenance: this replacement is a plain plugin-source
582
+ // user/message surface rewrite, not a new compaction checkpoint, and
583
+ // carrying the marker would fail the host's closed-transaction validation.
584
+ const replacement = createUserMessage({
585
+ content,
586
+ source: { kind: 'plugin', plugin: 'dsh-context-compression-improved-runtime' },
587
+ })
588
+ session.append('user/message', replacement, {
589
+ surfaceOp: { op: 'replace', startSeq: SessionSeq(checkpointSeq), endSeq: SessionSeq(checkpointSeq) },
590
+ sourceEventSeqs: [SessionSeq(checkpointSeq)],
591
+ })
592
+ emitCompressionAudit(this.ctx.logger, {
593
+ schemaVersion: 1,
594
+ kind: 'summary-locator',
595
+ sessionId: String(session.id),
596
+ profile: policy.profile,
597
+ checkpointSeq,
598
+ summarySeq: trace.summarySeq,
599
+ locatorChars: codePointLength(located.text),
600
+ spillFiles: located.spillFiles,
601
+ touchedFiles: located.touchedFiles,
602
+ })
603
+ }
604
+
605
+ /**
606
+ * TokenPilot-inspired E1: sample oversized historical reads and ask the
607
+ * auxiliary estimator whether their file state is still likely to be
608
+ * referenced. Fire-and-forget: never awaited on the pruning chain, failures
609
+ * back off exponentially per Session, verdicts only extend the rule-only
610
+ * superseded classification.
611
+ */
612
+ private async postflightEstimatorPass(session: Session, signal: AbortSignal): Promise<void> {
613
+ const policy = this.activePolicy(session)
614
+ const presetOptions = policy?.presetOptions
615
+ if (policy === undefined || presetOptions?.readState !== true) return
616
+ const estimatorMode = presetOptions.estimator?.mode ?? ''
617
+ if (estimatorMode === '') return
618
+ const failures = this.state.estimatorFailures.get(session)
619
+ if (isCoolingDown(failures, Date.now())) return
620
+
621
+ const events = sessionEvents(session)
622
+ const samples: EstimatorSample[] = []
623
+ const now = Date.now()
624
+ for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
625
+ if (samples.length >= 3) break
626
+ if (candidate.event.data.turn === undefined) continue
627
+ if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) continue
628
+ const path = toolCallPath(candidate.call.arguments)
629
+ if (path === undefined) continue
630
+ if (isSupersededRead(events, candidate.seq, path)) continue
631
+ if (this.state.estimatorVerdicts.get(session)?.has(candidate.seq) === true) continue
632
+ samples.push({ seq: candidate.seq, path, turn: candidate.event.data.turn })
633
+ }
634
+ if (samples.length === 0) return
635
+
636
+ const estimator = new Estimator(this.ctx, this.activeSettings(session).presetOptions ?? {})
637
+ const answer = await estimator.ask(buildEstimatorSystemPrompt(), buildEstimatorUserPrompt(samples), signal)
638
+ const latencyMs = Date.now() - now
639
+ const ok = answer !== undefined && signal.aborted === false
640
+ let expired = 0
641
+ if (ok && answer !== undefined) {
642
+ let verdicts = this.state.estimatorVerdicts.get(session)
643
+ if (verdicts === undefined) {
644
+ verdicts = new Map()
645
+ this.state.estimatorVerdicts.set(session, verdicts)
646
+ }
647
+ const detailed = parseEstimatorAnswerDetailed(answer)
648
+ // TokenPilot-inspired R4: the optional session-level Ŝ rides on the same
649
+ // answer; it only sharpens the benefit model and is never required.
650
+ if (detailed.expectedRemainingTurns !== undefined) {
651
+ this.state.estimatorRemainingTurns.set(session, detailed.expectedRemainingTurns)
652
+ }
653
+ for (const verdict of detailed.verdicts) {
654
+ if (verdicts.has(verdict.seq)) continue
655
+ verdicts.set(verdict.seq, verdict.expired)
656
+ if (verdict.expired) expired += 1
657
+ }
658
+ } else {
659
+ const next: EstimatorFailures = {
660
+ failures: (failures?.failures ?? 0) + 1,
661
+ cooldownUntil: Date.now() + backoffCooldownMs((failures?.failures ?? 0) + 1),
662
+ }
663
+ this.state.estimatorFailures.set(session, next)
664
+ }
665
+ emitCompressionAudit(this.ctx.logger, {
666
+ schemaVersion: 1,
667
+ kind: 'estimator-outcome',
668
+ sessionId: String(session.id),
669
+ profile: policy.profile,
670
+ channel: estimatorMode === 'host' ? 'host' : 'direct',
671
+ sampled: samples.length,
672
+ expired,
673
+ latencyMs,
674
+ ok,
675
+ })
676
+ }
677
+
678
+ // ─────────── Advisory relevance advisor (statistics & suggestions only) ───────────
679
+
680
+ /**
681
+ * Advisory advisor pass at the turn boundary, strictly fire-and-forget.
682
+ * Produces todolist-bound tail-task summaries, incremental relevance
683
+ * scores, and a prefix-decay figure — all observational. Every short
684
+ * circuit below (mode off, re-entry, cooldown, no task semantics, no
685
+ * direct endpoint) returns without touching any state the pruning chain
686
+ * reads, so the default configuration adds exactly zero behavior.
687
+ */
688
+ private async postflightAdvisorPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
689
+ const policy = this.activePolicy(session)
690
+ const presetOptions = policy?.presetOptions
691
+ const advisor = presetOptions?.advisor
692
+ if (policy === undefined || presetOptions === undefined || advisor === undefined || advisor.mode === '') return
693
+ const advisorState = getAdvisorState(session)
694
+ if (advisorState.inFlight) return
695
+ if (isCoolingDown(advisorState.failures, Date.now())) return
696
+
697
+ const events = sessionEvents(session)
698
+ const task = collectTaskSemantics(events)
699
+ if (task === undefined) return
700
+
701
+ const settings = this.activeSettings(session).presetOptions ?? {}
702
+ if (advisor.mode === 'direct'
703
+ && (settings.estimatorBaseUrl === undefined || settings.estimatorBaseUrl.length === 0
704
+ || settings.estimatorModel === undefined || settings.estimatorModel.length === 0)) {
705
+ // The advisor reuses the estimator's direct endpoint; when it is not
706
+ // configured there is nothing to ask, so record the aligned reason and
707
+ // back off instead of re-emitting the audit at every turn.
708
+ emitCompressionAudit(this.ctx.logger, {
709
+ schemaVersion: 1,
710
+ kind: 'advisor-outcome',
711
+ sessionId: String(session.id),
712
+ phase: 'summary',
713
+ channel: 'direct',
714
+ ok: false,
715
+ turnIndex: turn,
716
+ reason: 'no-direct-endpoint',
717
+ latencyMs: 0,
718
+ })
719
+ advisorState.failures = {
720
+ failures: (advisorState.failures?.failures ?? 0) + 1,
721
+ cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1),
722
+ }
723
+ return
724
+ }
725
+
726
+ let channel = this.state.advisorChannels.get(session)
727
+ if (channel === undefined) {
728
+ channel = new SideChannel(this.ctx, settings, {
729
+ mode: advisor.mode,
730
+ timeoutMs: advisor.timeoutMs,
731
+ maxTokens: 512,
732
+ })
733
+ this.state.advisorChannels.set(session, channel)
734
+ }
735
+
736
+ const view = measureForCompaction(this.ctx, session)
737
+ const candidates = this.snapshot(session, view)
738
+ .filter(candidate => !this.isRecoveryExempt(session, candidate))
739
+ .map(candidate => ({
740
+ seq: candidate.seq,
741
+ characterPressure: candidate.characterPressure,
742
+ preview: advisorCandidatePreview(candidate.call.name, candidate.event.data.message.content),
743
+ }))
744
+
745
+ let sawFailure = false
746
+ const outcome = await runSessionAdvisorPass(session, channel, record => {
747
+ if (record.ok === false) sawFailure = true
748
+ emitCompressionAudit(this.ctx.logger, record)
749
+ }, {
750
+ profile: policy.profile,
751
+ sessionId: String(session.id),
752
+ turn,
753
+ candidates,
754
+ task: {
755
+ source: task.source,
756
+ todoVersion: task.todoVersion,
757
+ taskText: task.taskText,
758
+ },
759
+ advisor: {
760
+ refreshTurns: advisor.refreshTurns,
761
+ scoreThreshold: advisor.scoreThreshold,
762
+ sampleLimit: advisor.sampleLimit,
763
+ minTokens: advisor.minTokens,
764
+ },
765
+ tailText: collectTailText(events),
766
+ signal,
767
+ })
768
+ if (outcome === undefined && sawFailure && signal.aborted === false) {
769
+ advisorState.failures = {
770
+ failures: (advisorState.failures?.failures ?? 0) + 1,
771
+ cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1),
772
+ }
773
+ } else if (outcome !== undefined) {
774
+ advisorState.failures = undefined
775
+ }
776
+ }
777
+
778
+ // ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
779
+
780
+ /**
781
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
782
+ * passes, select the consumed increment OUTSIDE the protected working set,
783
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
784
+ * verdict stages as a pending fold that the NEXT pressure round lands via
785
+ * the ordinary plan/apply machinery — the synchronous decision path never
786
+ * waits on an LLM.
787
+ */
788
+ private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
789
+ const started = Date.now()
790
+ const sessionId = String(session.id)
791
+ const policy = this.activePolicy(session)
792
+ const settings = this.activeSettings(session)
793
+ const intentEnabled = settings.intentSummary.enabled
794
+ const override = getSummaryOverride(sessionId)
795
+ observeIntentEnabled(sessionId, intentEnabled)
796
+ if (policy === undefined) return
797
+ if (this.state.pendingIntentFolds.has(session)) return
798
+ const advisorState = getAdvisorState(session)
799
+ if (advisorState.inFlight) return
800
+ if (isCoolingDown(advisorState.failures, Date.now())) return
801
+
802
+ const view = measureForCompaction(this.ctx, session)
803
+ // The window is the Auto Compact linkage input: policy.autoCompactTokens
804
+ // == floor(window * threshold/100); invert for the gate floor.
805
+ const thresholdPercent = settings.autoCompact.thresholdPercent
806
+ const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
807
+ ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
808
+ : undefined
809
+ const gate = evaluateIntentGate({
810
+ enabled: intentEnabled,
811
+ override,
812
+ liveTokens: view.totalTokens,
813
+ contextWindow,
814
+ baselineTokens: this.state.intentBaselines.get(session) ?? 0,
815
+ })
816
+ if (!gate.decision) return
817
+
818
+ const settingsPreset = settings.presetOptions
819
+ if (settingsPreset === undefined) return
820
+ if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
821
+ || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
822
+ emitCompressionAudit(this.ctx.logger, {
823
+ schemaVersion: 1,
824
+ kind: 'intent-summary-outcome',
825
+ sessionId,
826
+ ok: false,
827
+ reason: 'no-direct-endpoint',
828
+ turnIndex: turn,
829
+ latencyMs: Date.now() - started,
830
+ })
831
+ return
832
+ }
833
+
834
+ const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
835
+ const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
836
+ const range = computeIntentRange({
837
+ candidates,
838
+ protectedSeqs,
839
+ foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
840
+ maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
841
+ })
842
+ if (range.seqs.length === 0) return
843
+
844
+ const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
845
+ const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
846
+ const errorLines = new Set<string>()
847
+ for (const seq of range.seqs) {
848
+ const candidate = bySeq.get(seq)
849
+ if (candidate === undefined) continue
850
+ const result = candidate.event.data.message as ToolResultMessage
851
+ const text = onlyTextBlock(result.content)?.text ?? ''
852
+ const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
853
+ records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
854
+ for (const line of extractErrorLines(text)) errorLines.add(line)
855
+ }
856
+ if (records.length === 0) return
857
+
858
+ const events = sessionEvents(session)
859
+ const task = collectTaskSemantics(events)
860
+ let channel = this.state.advisorChannels.get(session)
861
+ if (channel === undefined) {
862
+ channel = new SideChannel(this.ctx, settingsPreset, {
863
+ mode: 'direct',
864
+ timeoutMs: 30_000,
865
+ maxTokens: 512,
866
+ })
867
+ this.state.advisorChannels.set(session, channel)
868
+ }
869
+
870
+ const answer = await channel.ask({
871
+ system: buildIntentSummarySystemPrompt(),
872
+ user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
873
+ signal,
874
+ })
875
+ const summaryCallChars = answer?.length ?? 0
876
+ const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
877
+ if (parsed === undefined) {
878
+ const failures = (advisorState.failures?.failures ?? 0) + 1
879
+ advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
880
+ emitCompressionAudit(this.ctx.logger, {
881
+ schemaVersion: 1,
882
+ kind: 'intent-summary-outcome',
883
+ sessionId,
884
+ ok: false,
885
+ reason: answer === undefined ? 'ask-failed' : 'parse-failed',
886
+ turnIndex: turn,
887
+ foldedCount: records.length,
888
+ summaryCallChars,
889
+ latencyMs: Date.now() - started,
890
+ })
891
+ return
892
+ }
893
+ this.state.pendingIntentFolds.set(session, {
894
+ createdAt: Date.now(),
895
+ turn,
896
+ startSeq: range.seqs[0]!,
897
+ endSeq: range.seqs[range.seqs.length - 1]!,
898
+ summary: parsed.summary,
899
+ errorLines: [...errorLines],
900
+ records,
901
+ summaryCallChars,
902
+ })
903
+ emitCompressionAudit(this.ctx.logger, {
904
+ schemaVersion: 1,
905
+ kind: 'intent-summary-outcome',
906
+ sessionId,
907
+ ok: true,
908
+ reason: 'staged',
909
+ turnIndex: turn,
910
+ foldedCount: records.length,
911
+ summaryCallChars,
912
+ latencyMs: Date.now() - started,
913
+ })
914
+ }
915
+
916
+ /**
917
+ * Convert a staged pending fold into per-candidate planned replacements
918
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
919
+ * rich-content, or no longer exists keeps its original text. Returns
920
+ * `undefined` when there is nothing (or no longer anything) to fold.
921
+ */
922
+ private applyPendingIntentFold(
923
+ session: Session,
924
+ policy: CompressionPolicy,
925
+ view: CompactionTokenView,
926
+ eligible: readonly SnapshotCandidate[],
927
+ ): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
928
+ const pending = this.state.pendingIntentFolds.get(session)
929
+ if (pending === undefined) return undefined
930
+ const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
931
+ const foldable = pending.records
932
+ .map(record => record.seq)
933
+ .filter(seq => bySeq.has(seq))
934
+ .sort((a, b) => a - b)
935
+ if (foldable.length === 0) {
936
+ this.state.pendingIntentFolds.delete(session)
937
+ return undefined
938
+ }
939
+ const plans: PlannedReplacement[] = []
940
+ const foldedSeqs = new Set<number>()
941
+ let reclaim = 0
942
+ let charsBefore = 0
943
+ let charsAfter = 0
944
+ for (const seq of foldable) {
945
+ const candidate = bySeq.get(seq)!
946
+ const result = candidate.event.data.message as ToolResultMessage
947
+ const block = onlyTextBlock(result.content)
948
+ if (block === null) continue
949
+ const text = renderIntentFoldBlock(pending, seq)
950
+ const plan = this.plan(
951
+ candidate,
952
+ [{ ...block, text }],
953
+ rootToolResultSeq(session, candidate.seq),
954
+ 'intent-summary',
955
+ 'pressure',
956
+ 'history',
957
+ policy.historyMode,
958
+ view,
959
+ )
960
+ if (plan === null || plan.charsAfter >= plan.charsBefore) continue
961
+ plans.push(plan)
962
+ foldedSeqs.add(seq)
963
+ reclaim += plan.charsBefore - plan.charsAfter
964
+ charsBefore += plan.charsBefore
965
+ charsAfter += plan.charsAfter
966
+ }
967
+ if (plans.length === 0) return undefined
968
+ this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
969
+ return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
970
+ }
971
+
972
+ // ─────────── Advisory benefit model (statistics & suggestions only) ───────────
973
+
974
+ /**
975
+ * Monotonic per-session turn clock for advisory records. Bumped by the agent
976
+ * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
977
+ * observed value.
978
+ */
979
+ private turnClock(session: Session, turn?: number): number {
980
+ const previous = this.state.turnClocks.get(session) ?? 0
981
+ const next = typeof turn === 'number' && Number.isSafeInteger(turn) && turn > previous ? turn : previous
982
+ this.state.turnClocks.set(session, next)
983
+ return next
984
+ }
985
+
986
+ /**
987
+ * Advisory benefit-model hook — what the retired human-gated review pipeline
988
+ * left behind. It is the IDENTITY on the landing path: every plan it is given
989
+ * comes back unchanged, because a reduction must never block automatic
990
+ * processing. The model's band is published as a `reduction-advice` audit and
991
+ * snapshotted onto the advisor state for the read-only report route, so the
992
+ * cache-accounting insight survives without a gate.
993
+ */
994
+ private adviseReplacements(
995
+ session: Session,
996
+ policy: CompressionPolicy,
997
+ plans: readonly PlannedReplacement[],
998
+ stage: 'fresh' | 'history' = 'history',
999
+ ): readonly PlannedReplacement[] {
1000
+ if (plans.length === 0) return plans
1001
+ const remainingTurns = this.state.estimatorRemainingTurns.get(session)
1002
+ const advice = adviseCandidates(plans.map(plan => ({
1003
+ sourceSeq: plan.sourceSeq,
1004
+ tokensBefore: plan.tokensBefore,
1005
+ tokensAfter: plan.tokensAfter,
1006
+ })), {
1007
+ alpha: DEFAULT_ADVICE_ALPHA,
1008
+ // One-phase approximation of the tail that a mutation must refill: the
1009
+ // frozen protected recent-token tail (findings.md, 约束与依赖).
1010
+ tailTokens: Math.max(1, policy.historyKeepRecentTokens),
1011
+ highImpactTokens: DEFAULT_ADVICE_HIGH_IMPACT_TOKENS,
1012
+ ...remainingTurns === undefined ? {} : { remainingTurns },
1013
+ // Fresh plans shape content before its first request — it is not in the
1014
+ // KV cache yet, so no cache break occurs and the refill penalty would be
1015
+ // a phantom cost pricing every realistic fresh batch into the
1016
+ // not-worth-it band.
1017
+ stage,
1018
+ })
1019
+ if (advice === undefined) return plans
1020
+ const turn = this.turnClock(session)
1021
+ const itemSeqs = plans.map(plan => plan.sourceSeq)
1022
+ // Observational snapshot only: the advisory-only invariant (K13) holds
1023
+ // because no decision path reads this field.
1024
+ getAdvisorState(session).lastAdvice = {
1025
+ band: advice.band,
1026
+ turn,
1027
+ itemSeqs,
1028
+ recoveredTokens: advice.benefit.recoveredTokens,
1029
+ penaltyTokens: advice.benefit.penaltyTokens,
1030
+ ...advice.benefit.paybackTurns === undefined ? {} : { paybackTurns: advice.benefit.paybackTurns },
1031
+ }
1032
+ emitCompressionAudit(this.ctx.logger, {
1033
+ schemaVersion: 1,
1034
+ kind: 'reduction-advice',
1035
+ sessionId: String(session.id),
1036
+ profile: policy.profile,
1037
+ band: advice.band,
1038
+ stage,
1039
+ itemSeqs,
1040
+ pricedCandidates: advice.priced,
1041
+ maxTokensBefore: advice.maxTokensBefore,
1042
+ tokensBefore: plans.reduce((sum, plan) => sum + plan.tokensBefore, 0),
1043
+ tokensAfter: plans.reduce((sum, plan) => sum + plan.tokensAfter, 0),
1044
+ recoveredTokens: advice.benefit.recoveredTokens,
1045
+ penaltyTokens: advice.benefit.penaltyTokens,
1046
+ ...advice.benefit.paybackTurns === undefined ? {} : { paybackTurns: advice.benefit.paybackTurns },
1047
+ ...advice.benefit.expectedSaving === undefined ? {} : { expectedSaving: advice.benefit.expectedSaving },
1048
+ turnIndex: turn,
1049
+ })
1050
+ return plans
1051
+ }
1052
+
1053
+ private activePolicy(
1054
+ session: Session,
1055
+ contextWindowTokens?: number,
1056
+ stage: PruneStage = 'pressure',
1057
+ ): CompressionPolicy | undefined {
1058
+ const settings = this.activeSettings(session)
1059
+ try {
1060
+ // R4 bridge: the persisted settings document's presetOptions (the
1061
+ // settings-card writes, including the advisor keys) must reach the
1062
+ // policy — before this bridge only the estimator endpoint read them
1063
+ // directly and every policy consumer saw the deployment defaults. User
1064
+ // settings win over deployment config; absent fields inherit via
1065
+ // mergePresetOptions.
1066
+ const policy = resolvePolicy(
1067
+ settings.presetOptions === undefined
1068
+ ? this.state.config
1069
+ : { ...this.state.config, presetOptions: settings.presetOptions },
1070
+ settings.profile,
1071
+ settings.custom,
1072
+ {
1073
+ ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
1074
+ autoCompactThresholdPercent: settings.autoCompact.thresholdPercent,
1075
+ },
1076
+ )
1077
+ // Route changes must produce a fresh audit record even when the policy
1078
+ // object is unchanged, or the dedupe would hide a mid-session reroute.
1079
+ const route = routeAuditFact(session)
1080
+ const auditKey = JSON.stringify({
1081
+ policy,
1082
+ contextWindowTokens: contextWindowTokens ?? null,
1083
+ route: route ?? null,
1084
+ })
1085
+ // Deduplicate only CONSECUTIVE identical resolutions: a permanent set
1086
+ // would hide an A -> B -> A reroute's third record.
1087
+ if (this.state.policyResolutionAudits.get(session) !== auditKey) {
1088
+ this.state.policyResolutionAudits.set(session, auditKey)
1089
+ // Deployment config overrides win over the Auto Compact linkage, so a
1090
+ // standard profile whose History watermarks were replaced must not
1091
+ // audit itself as purely linkage-derived.
1092
+ const overriddenLinkedFields = ([
1093
+ 'historyTriggerTokens',
1094
+ 'historyKeepRecentTokens',
1095
+ 'historyMinReclaimTokens',
1096
+ ] as const).filter(key => this.state.config[key] !== undefined).length
1097
+ emitCompressionAudit(this.ctx.logger, {
1098
+ schemaVersion: 1,
1099
+ kind: 'policy-resolved',
1100
+ sessionId: String(session.id),
1101
+ policy,
1102
+ ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
1103
+ coordination: {
1104
+ thresholdPercent: settings.autoCompact.thresholdPercent,
1105
+ ...policy.autoCompactTokens === undefined ? {} : { autoCompactTokens: policy.autoCompactTokens },
1106
+ ...policy.microDeadlineTokens === undefined ? {} : { microDeadlineTokens: policy.microDeadlineTokens },
1107
+ paramSource: settings.profile === 'custom'
1108
+ ? 'custom-manual'
1109
+ : overriddenLinkedFields === 3 ? 'deployment-override'
1110
+ : overriddenLinkedFields > 0 ? 'mixed'
1111
+ : policy.microDeadlineTokens === undefined ? 'fixed-preset' : 'auto-compact-linked',
1112
+ },
1113
+ ...route === undefined ? {} : { route },
1114
+ ...route === undefined ? {} : tokenizerAuditFact(route),
1115
+ })
1116
+ }
1117
+ return policy
1118
+ } catch (error: unknown) {
1119
+ const reason = error instanceof Error ? error.message : String(error)
1120
+ this.auditFailure(session, stage, 'policy-resolution', error)
1121
+ this.warnOnce(
1122
+ session,
1123
+ `custom-policy:${settings.profile}:${reason}`,
1124
+ 'context-compression kept original tool results because the Custom policy is not effective: %s',
1125
+ reason,
1126
+ )
1127
+ return undefined
1128
+ }
1129
+ }
1130
+
1131
+ private contextWindowForRequest(
1132
+ session: Session,
1133
+ ): number | undefined {
1134
+ const settings = this.activeSettings(session)
1135
+ // History linkage needs routed capacity for standard profiles, and the
1136
+ // Custom percentage policy needs it for context-percent documents. Off and
1137
+ // Native never link, and token-unit Custom stays manual.
1138
+ if (settings.profile === 'off' || settings.profile === 'native') return undefined
1139
+ if (settings.profile === 'custom' && settings.custom.unit !== 'context-percent') return undefined
1140
+ const config = session.requestHeader()?.config
1141
+ const routed = session.requestContext()
1142
+ if (config === undefined || config.provider.length === 0 || config.model.length === 0 || routed === undefined) {
1143
+ return undefined
1144
+ }
1145
+ if (routed.provider !== config.provider || routed.model !== config.model) {
1146
+ this.warnOnce(
1147
+ session,
1148
+ `custom-context-window-route:${config.provider}\0${config.model}`,
1149
+ 'context-compression kept the context-linked policy inactive because durable route capacity belongs to %s/%s, not %s/%s',
1150
+ routed.provider,
1151
+ routed.model,
1152
+ config.provider,
1153
+ config.model,
1154
+ )
1155
+ return undefined
1156
+ }
1157
+ if (!Number.isSafeInteger(routed.contextWindow) || routed.contextWindow === undefined || routed.contextWindow <= 0) {
1158
+ this.warnOnce(
1159
+ session,
1160
+ `custom-context-window-capacity:${config.provider}\0${config.model}`,
1161
+ 'context-compression kept the context-linked policy inactive because %s/%s has no positive durable context capacity',
1162
+ config.provider,
1163
+ config.model,
1164
+ )
1165
+ return undefined
1166
+ }
1167
+ return routed.contextWindow
1168
+ }
1169
+
1170
+ private runRequestBoundary(
1171
+ session: Session,
1172
+ turn: number,
1173
+ step: number,
1174
+ signal: AbortSignal,
1175
+ ): void {
1176
+ const contextWindowTokens = this.contextWindowForRequest(session)
1177
+ if (signal.aborted) return
1178
+ const policy = this.activePolicy(session, contextWindowTokens, 'fresh')
1179
+ if (policy === undefined) return
1180
+ const capacity = contextWindowTokens === undefined ? {} : { contextWindowTokens }
1181
+ this.pruneSession(session, { stage: 'fresh', freshTurn: turn, freshStep: step, ...capacity })
1182
+ if (policy.historyMode !== 'disabled' || policy.tailTrim?.enabled === true) {
1183
+ this.pruneSession(session, { stage: 'pressure', ...capacity })
1184
+ }
1185
+ }
1186
+
1187
+ /** Resolve historical-aging authority without accepting caller-supplied elevation. */
1188
+ private historyAllowed(session: Session, policy: CompressionPolicy, view: CompactionTokenView): boolean {
1189
+ switch (policy.historyMode) {
1190
+ case 'disabled':
1191
+ return false
1192
+ case 'routine':
1193
+ return true
1194
+ case 'capacity-pressure':
1195
+ return this.capacityPressureActive(session, view, policy)
1196
+ case 'adaptive':
1197
+ return false
1198
+ /* v8 ignore next -- closed-union exhaustiveness guard */
1199
+ default:
1200
+ return assertNever(policy.historyMode, 'history mode')
1201
+ }
1202
+ }
1203
+
1204
+ /**
1205
+ * Match the compaction-basic pressure gate using public durable data. The
1206
+ * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
1207
+ * fixed 0.7 ratio once the standard-profile linkage resolved; without
1208
+ * linkage the 0.7 ratio is the documented fallback and reproduces the
1209
+ * previous behavior.
1210
+ */
1211
+ private capacityPressureActive(
1212
+ session: Session,
1213
+ view: CompactionTokenView,
1214
+ policy: CompressionPolicy,
1215
+ ): boolean {
1216
+ const deadline = policy.microDeadlineTokens
1217
+ if (deadline !== undefined) return view.totalTokens >= deadline
1218
+ const header = session.requestHeader()?.config
1219
+ const routed = session.requestContext()
1220
+ const contextWindow = routed?.contextWindow
1221
+ if (header === undefined || routed === undefined
1222
+ || routed.provider !== header.provider
1223
+ || routed.model !== header.model
1224
+ || contextWindow === undefined
1225
+ || !Number.isSafeInteger(contextWindow)
1226
+ || contextWindow <= 0) return false
1227
+ return view.totalTokens >= Math.floor(contextWindow * CAPACITY_PRESSURE_RATIO)
1228
+ }
1229
+
1230
+ /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
1231
+ private logAdaptivePostflight(session: Session, usage: ObservedPromptUsage): void {
1232
+ const attemptId = String(usage.attemptId)
1233
+ if (this.state.postflightDiagnostics.get(session) === attemptId) return
1234
+ this.state.postflightDiagnostics.set(session, attemptId)
1235
+
1236
+ const key = usage.key
1237
+ let priceRecord: Readonly<Record<string, unknown>> | undefined
1238
+ let cost: ReturnType<typeof priceOfficialDeepSeekUsage> | { readonly kind: 'unpriced'; readonly reason: string }
1239
+ if (key === undefined) {
1240
+ cost = { kind: 'unpriced', reason: 'measurement key unavailable' }
1241
+ } else if (usage.responseModelId !== key.modelId) {
1242
+ cost = { kind: 'unpriced', reason: 'response model mismatch or unavailable' }
1243
+ } else if (usage.observedOutputTokens === undefined) {
1244
+ cost = { kind: 'unpriced', reason: 'output token count unavailable' }
1245
+ } else if (usage.cacheStatus !== 'complete'
1246
+ || usage.cacheReadTokens === undefined
1247
+ || usage.cacheMissTokens === undefined) {
1248
+ cost = { kind: 'unpriced', reason: 'complete cache split unavailable' }
1249
+ } else {
1250
+ const startedAt = new Date(usage.startedAtMs)
1251
+ const completedAt = new Date(usage.completedAtMs)
1252
+ const resolution = resolveOfficialDeepSeekPrice({
1253
+ provider: key.provider,
1254
+ baseUrlClass: key.baseUrlClass,
1255
+ apiRoute: key.apiRoute,
1256
+ modelId: key.modelId,
1257
+ currency: 'USD',
1258
+ at: startedAt,
1259
+ })
1260
+ if (resolution.kind === 'priced') {
1261
+ priceRecord = {
1262
+ catalogVersion: resolution.record.catalogVersion,
1263
+ checkedAt: resolution.record.checkedAt,
1264
+ sourceUrl: resolution.record.sourceUrl,
1265
+ currency: resolution.record.currency,
1266
+ modelId: resolution.record.modelId,
1267
+ apiRoute: resolution.record.apiRoute,
1268
+ startBand: resolution.record.band,
1269
+ }
1270
+ }
1271
+ cost = priceOfficialDeepSeekUsage({
1272
+ provider: key.provider,
1273
+ baseUrlClass: key.baseUrlClass,
1274
+ apiRoute: key.apiRoute,
1275
+ modelId: key.modelId,
1276
+ currency: 'USD',
1277
+ startedAt,
1278
+ completedAt,
1279
+ usage: {
1280
+ cacheReadTokens: usage.cacheReadTokens,
1281
+ cacheMissTokens: usage.cacheMissTokens,
1282
+ outputTokens: usage.observedOutputTokens,
1283
+ },
1284
+ })
1285
+ }
1286
+
1287
+ this.ctx.logger.debug(`context-compression adaptive postflight ${JSON.stringify({
1288
+ sessionId: String(session.id),
1289
+ providerRequestOrdinal: Number(usage.providerRequestOrdinal),
1290
+ attemptId,
1291
+ startedAtMs: usage.startedAtMs,
1292
+ completedAtMs: usage.completedAtMs,
1293
+ measurementKind: usage.measurement.kind,
1294
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
1295
+ ...(priceRecord === undefined ? {} : { priceRecord }),
1296
+ usage: {
1297
+ promptTokens: usage.observedPromptTokens,
1298
+ ...(usage.observedOutputTokens === undefined ? {} : { outputTokens: usage.observedOutputTokens }),
1299
+ cacheStatus: usage.cacheStatus ?? 'unknown',
1300
+ ...(usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens }),
1301
+ ...(usage.cacheMissTokens === undefined ? {} : { cacheMissTokens: usage.cacheMissTokens }),
1302
+ },
1303
+ cost,
1304
+ })}`)
1305
+ }
1306
+
1307
+ /** Decide one already-planned History batch from adjacent request-level facts only. */
1308
+ private adaptiveHistoryAllowed(
1309
+ session: Session,
1310
+ view: CompactionTokenView,
1311
+ plans: readonly PlannedReplacement[],
1312
+ capacityPressure: boolean,
1313
+ ): boolean {
1314
+ const log = (
1315
+ allowHistory: boolean,
1316
+ reason: string,
1317
+ detail: Readonly<Record<string, unknown>> = {},
1318
+ ): boolean => {
1319
+ this.ctx.logger.debug(`context-compression adaptive ${JSON.stringify({
1320
+ sessionId: String(session.id),
1321
+ allowHistory,
1322
+ reason,
1323
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
1324
+ ...detail,
1325
+ })}`)
1326
+ return allowHistory
1327
+ }
1328
+ const usage = view.lastCompletedUsage
1329
+ if (usage !== undefined) this.logAdaptivePostflight(session, usage)
1330
+ if (plans.length === 0) return false
1331
+ if (capacityPressure) return log(true, 'capacity-override')
1332
+
1333
+ const currentKey = view.latestEnvelopeKey
1334
+ if (usage === undefined) return log(false, 'usage-unavailable')
1335
+ if (usage.key === undefined || currentKey === undefined) {
1336
+ return log(false, 'measurement-key-unavailable')
1337
+ }
1338
+ if (!sameProviderMeasurementKey(usage.key, currentKey)) {
1339
+ return log(false, 'measurement-key-mismatch')
1340
+ }
1341
+ if (usage.responseModelId !== usage.key.modelId) {
1342
+ return log(false, 'response-model-mismatch-or-unavailable')
1343
+ }
1344
+ if (usage.cacheStatus !== 'complete'
1345
+ || usage.cacheReadTokens === undefined
1346
+ || usage.cacheMissTokens === undefined) {
1347
+ return log(false, 'cache-split-incomplete')
1348
+ }
1349
+
1350
+ const price = resolveOfficialDeepSeekPrice({
1351
+ provider: usage.key.provider,
1352
+ baseUrlClass: usage.key.baseUrlClass,
1353
+ apiRoute: usage.key.apiRoute,
1354
+ modelId: usage.key.modelId,
1355
+ currency: 'USD',
1356
+ at: new Date(),
1357
+ })
1358
+ if (price.kind === 'unpriced') return log(false, `adaptive-unknown-price:${price.reason}`)
1359
+
1360
+ const exactReclaimedTokens = plans.reduce(
1361
+ (sum, plan) => sum + plan.tokensBefore - plan.tokensAfter,
1362
+ 0,
1363
+ )
1364
+ const earliestChangedSeq = Math.min(...plans.map(plan => plan.candidate.seq))
1365
+ const bounds = deriveAdaptiveTokenBounds({
1366
+ exactReclaimedTokens,
1367
+ earliestChangedSeq,
1368
+ previousPromptTokens: usage.observedPromptTokens,
1369
+ expectedTokenizerRevision: usage.key.tokenizerRevision,
1370
+ previousRequestMeasurement: usage.measurement,
1371
+ measuredNodes: view.measuredNodes,
1372
+ })
1373
+ const decision = decideConservativeAdaptive({
1374
+ capacityPressure: false,
1375
+ bounds,
1376
+ inputCacheHitRate: price.record.inputCacheHit,
1377
+ inputCacheMissRate: price.record.inputCacheMiss,
1378
+ observedCacheReadTokens: usage.cacheReadTokens,
1379
+ })
1380
+ return log(decision.allowHistory, decision.reason, {
1381
+ priceBand: price.record.band,
1382
+ observedPromptTokens: usage.observedPromptTokens,
1383
+ observedCacheReadTokens: usage.cacheReadTokens,
1384
+ bounds,
1385
+ ...'minimumRemovalValue' in decision
1386
+ ? { minimumRemovalValue: decision.minimumRemovalValue }
1387
+ : {},
1388
+ ...'maximumCacheLossPenalty' in decision
1389
+ ? { maximumCacheLossPenalty: decision.maximumCacheLossPenalty }
1390
+ : {},
1391
+ })
1392
+ }
1393
+
1394
+ private decisions(session: Session): Set<number> {
1395
+ let decisions = this.state.firstExposure.get(session)
1396
+ if (decisions === undefined) {
1397
+ decisions = new Set()
1398
+ this.state.firstExposure.set(session, decisions)
1399
+ }
1400
+ return decisions
1401
+ }
1402
+
1403
+ /**
1404
+ * TokenPilot-style skipReduction: recovery tool output is permanently exempt
1405
+ * from every reduction pass so retrieved content can never enter a
1406
+ * compress-restore-oscillation loop. A call-name match covers the built-in
1407
+ * recovery tool; the per-session set admits future recovery paths.
1408
+ */
1409
+ private isRecoveryExempt(session: Session, candidate: SnapshotCandidate): boolean {
1410
+ if (candidate.call.name === 'context_compression_retrieve') return true
1411
+ return this.state.recoveryExemptions.get(session)?.has(candidate.seq) ?? false
1412
+ }
1413
+
1414
+ /** Register a result seq as permanently exempt from further reduction. */
1415
+ private grantRecoveryExemption(session: Session, seq: number): void {
1416
+ let exemptions = this.state.recoveryExemptions.get(session)
1417
+ if (exemptions === undefined) {
1418
+ exemptions = new Set()
1419
+ this.state.recoveryExemptions.set(session, exemptions)
1420
+ }
1421
+ exemptions.add(seq)
1422
+ }
1423
+
1424
+ private decideFreshStep(
1425
+ session: Session,
1426
+ options: PruneSessionOptions,
1427
+ policy: CompressionPolicy,
1428
+ view: CompactionTokenView,
1429
+ ): PruneResult {
1430
+ if (options.freshTurn === undefined || options.freshStep === undefined) {
1431
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1432
+ policy.freshEnabled ? 'skipped' : 'disabled',
1433
+ policy.freshEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
1434
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1435
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1436
+ policy.aggregateEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
1437
+ return emptyResult()
1438
+ }
1439
+ const decisions = this.decisions(session)
1440
+ const candidates = this.snapshot(session, view).filter(candidate =>
1441
+ typeof candidate.event.surfaceOp !== 'object'
1442
+ && candidate.event.data.turn === options.freshTurn
1443
+ && candidate.event.data.step === options.freshStep
1444
+ && !decisions.has(candidate.seq))
1445
+ if (candidates.length === 0) {
1446
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1447
+ policy.freshEnabled ? 'skipped' : 'disabled',
1448
+ policy.freshEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
1449
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1450
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1451
+ policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
1452
+ return emptyResult()
1453
+ }
1454
+ // 节省统计(负节省配对):新全文工具结果按 (session,seq) 一次性过账——
1455
+ // 命中"此前压缩过的原文哈希"即记抵消。挂在压力门控之前:全文重读无论
1456
+ // 本轮是否再次压缩,都使原声称的节省不再成立(先骨架后全文 = 负节省)。
1457
+ const ledger = getSavingsLedger()
1458
+ const sid = String(session.id)
1459
+ for (const candidate of candidates) {
1460
+ const text = flattenPlainText(candidate.event.data.message.content)
1461
+ if (text === undefined) continue
1462
+ ledger.noteFullText({
1463
+ sessionId: sid,
1464
+ seq: candidate.seq,
1465
+ text,
1466
+ measure: () =>
1467
+ candidate.count.kind === 'exact-tokenizer' && typeof candidate.count.tokens === 'number'
1468
+ ? { tokens: candidate.count.tokens, basis: 'exact-tokenizer' }
1469
+ : { tokens: Math.ceil(candidate.characterPressure / 4), basis: 'characters' },
1470
+ })
1471
+ }
1472
+
1473
+ const plans = new Map<number, PlannedReplacement>()
1474
+ let freshPlanned = 0
1475
+ const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
1476
+ const candidateChars = candidates.map(candidate => candidate.characterPressure)
1477
+ const maxCandidateChars = candidateChars.length === 0 ? undefined : Math.max(...candidateChars)
1478
+ if (policy.freshEnabled) {
1479
+ if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
1480
+ && candidate.count.kind !== 'exact-tokenizer')) {
1481
+ this.warnExactUnavailable(session, view, 'fresh')
1482
+ }
1483
+ for (const candidate of candidates) {
1484
+ if (this.isRecoveryExempt(session, candidate)) continue
1485
+ if (dedupeEnabled) {
1486
+ const dedupePlan = this.planDedupe(candidate, session, policy, view)
1487
+ if (dedupePlan !== null) {
1488
+ plans.set(candidate.seq, dedupePlan)
1489
+ continue
1490
+ }
1491
+ }
1492
+ const plan = this.planFresh(candidate, session, policy, view)
1493
+ if (plan !== null) {
1494
+ plans.set(candidate.seq, plan)
1495
+ freshPlanned += 1
1496
+ }
1497
+ }
1498
+ }
1499
+ let aggregateInputChars: number | undefined
1500
+ let aggregatePlanned = 0
1501
+ if (policy.aggregateEnabled) {
1502
+ let total = candidates.reduce((sum, candidate) => sum
1503
+ + (plans.get(candidate.seq)?.charsAfter ?? candidate.characterPressure), 0)
1504
+ aggregateInputChars = total
1505
+ if (total > charsForTokens(policy.aggregateTriggerTokens)) {
1506
+ const remaining = candidates
1507
+ .filter(candidate => !this.isRecoveryExempt(session, candidate))
1508
+ .sort((a, b) => Number(isError(a)) - Number(isError(b))
1509
+ || (plans.get(b.seq)?.charsAfter ?? b.characterPressure)
1510
+ - (plans.get(a.seq)?.charsAfter ?? a.characterPressure))
1511
+ for (const candidate of remaining) {
1512
+ const previous = plans.get(candidate.seq)
1513
+ const plan = this.planAggregate(candidate, session, view)
1514
+ const previousChars = previous?.charsAfter ?? candidate.characterPressure
1515
+ if (plan === null || plan.charsAfter >= previousChars) continue
1516
+ plans.set(candidate.seq, plan)
1517
+ aggregatePlanned += 1
1518
+ total -= previousChars - plan.charsAfter
1519
+ if (total <= charsForTokens(policy.aggregateTargetTokens)) break
1520
+ }
1521
+ if (total > charsForTokens(policy.aggregateTargetTokens)) {
1522
+ this.ctx.logger.warn(
1523
+ 'context-compression fresh aggregate residual: %d characters exceed target %d',
1524
+ total,
1525
+ charsForTokens(policy.aggregateTargetTokens),
1526
+ )
1527
+ }
1528
+ }
1529
+ }
1530
+
1531
+ const freshCandidates = candidates
1532
+ .map(candidate => plans.get(candidate.seq))
1533
+ .filter((plan): plan is PlannedReplacement => plan !== undefined)
1534
+ const landed = this.landAll(session, this.adviseReplacements(session, policy, freshCandidates, 'fresh'))
1535
+ const freshLanded = landed.some(entry => entry.stage === 'fresh'
1536
+ && plans.get(entry.originalSeq)?.component === 'fresh')
1537
+ const aggregateLanded = landed.some(entry => entry.stage === 'fresh'
1538
+ && plans.get(entry.originalSeq)?.component === 'aggregate')
1539
+ if (!freshLanded) {
1540
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1541
+ policy.freshEnabled ? 'skipped' : 'disabled',
1542
+ !policy.freshEnabled ? 'profile-policy'
1543
+ : (maxCandidateChars ?? 0) <= charsForTokens(policy.freshTriggerTokens) ? 'at-or-below-trigger'
1544
+ : freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
1545
+ : freshPlanned === 0 ? 'no-valid-reduction'
1546
+ : 'recovery-tool-unavailable', {
1547
+ measurementKind: 'characters',
1548
+ ...(maxCandidateChars === undefined ? {} : { currentTokens: charsToTokens(maxCandidateChars) }),
1549
+ triggerTokens: policy.freshTriggerTokens,
1550
+ targetTokens: policy.freshTargetTokens,
1551
+ })
1552
+ }
1553
+ if (!aggregateLanded) {
1554
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1555
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1556
+ !policy.aggregateEnabled ? 'profile-policy'
1557
+ : (aggregateInputChars ?? 0) <= charsForTokens(policy.aggregateTriggerTokens) ? 'at-or-below-trigger'
1558
+ : aggregatePlanned === 0 ? 'no-valid-reduction'
1559
+ : 'recovery-tool-unavailable', {
1560
+ measurementKind: 'characters',
1561
+ ...(aggregateInputChars === undefined ? {} : { currentTokens: charsToTokens(aggregateInputChars) }),
1562
+ triggerTokens: policy.aggregateTriggerTokens,
1563
+ targetTokens: policy.aggregateTargetTokens,
1564
+ })
1565
+ }
1566
+ for (const candidate of candidates) decisions.add(candidate.seq)
1567
+ return summarize(landed)
1568
+ }
1569
+
1570
+ private snapshot(session: Session, view: CompactionTokenView): SnapshotCandidate[] {
1571
+ const events = sessionEvents(session)
1572
+ const calls = new Map<string, ToolCallInfo>()
1573
+ for (const event of events) {
1574
+ if (event.type === 'tool/call') {
1575
+ calls.set(event.data.callId, { name: event.data.name, arguments: event.data.arguments })
1576
+ }
1577
+ }
1578
+ const candidates: SnapshotCandidate[] = []
1579
+ const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1580
+ const projectionPrices = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1581
+ for (const seq of [...session.surface.nodes]) {
1582
+ const event = eventBySeq(events, seq)
1583
+ if (event?.type !== 'tool/result') continue
1584
+ const shadowedHeuristicTokenCount = projectionPrices.get(seq)
1585
+ if (shadowedHeuristicTokenCount === undefined) {
1586
+ throw new Error(`surface node ${String(seq)} is absent from the atomic legacy projection`)
1587
+ }
1588
+ const content = event.data.message.content[0].content
1589
+ candidates.push({
1590
+ seq,
1591
+ event,
1592
+ call: calls.get(event.data.message.source.callId) ?? { name: 'unknown', arguments: '{}' },
1593
+ count: onlyTextBlocks(content) === null
1594
+ ? unavailableCount(`surface node ${String(seq)} contains unsupported rich tool-result content`)
1595
+ : measured.get(seq) ?? unavailableCount(`surface node ${String(seq)} is absent from the atomic token view`),
1596
+ shadowedHeuristicTokenCount,
1597
+ characterPressure: pressureCost(content),
1598
+ })
1599
+ }
1600
+ return candidates
1601
+ }
1602
+
1603
+ private planNative(
1604
+ candidate: SnapshotCandidate,
1605
+ session: Session,
1606
+ stage: PruneStage,
1607
+ policy: CompressionPolicy,
1608
+ view: CompactionTokenView,
1609
+ ): PlannedReplacement | null {
1610
+ if (this.isRecoveryExempt(session, candidate)) return null
1611
+ if (candidate.characterPressure <= charsForTokens(policy.nativeTriggerTokens)) return null
1612
+ const result = candidate.event.data.message.content[0]
1613
+ if (onlyTextBlocks(result.content) === null) return null
1614
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1615
+ // R9b site: the marker's retrieve hint starts at the event line right
1616
+ // after the retained head, computed inside nativePruneContent.
1617
+ const marker = (startLine: number): string => recoveryMarker(sourceRefFn(session, sourceSeq), 'tool result middle pruned', startLine)
1618
+ let head = this.state.config.headChars
1619
+ let tail = this.state.config.tailChars
1620
+ for (let attempt = 0; attempt < 10; attempt += 1) {
1621
+ const threshold = head + codePointLength(marker(1)) + tail
1622
+ const content = nativePruneContent(result.content, threshold, head, tail, marker)
1623
+ if (content !== null) {
1624
+ const plan = this.plan(
1625
+ candidate,
1626
+ content,
1627
+ sourceSeq,
1628
+ 'native-head-tail',
1629
+ stage,
1630
+ 'native-tool-result',
1631
+ undefined,
1632
+ view,
1633
+ )
1634
+ if (plan !== null && plan.tokensAfter <= policy.nativeTargetTokens) return plan
1635
+ }
1636
+ if (head === 0 && tail === 0) break
1637
+ head = Math.floor(head / 2)
1638
+ tail = Math.floor(tail / 2)
1639
+ }
1640
+ return this.planAggregate(
1641
+ candidate,
1642
+ session,
1643
+ view,
1644
+ 'native-whole-result',
1645
+ stage,
1646
+ policy.nativeTargetTokens,
1647
+ 'native-tool-result',
1648
+ )
1649
+ }
1650
+
1651
+ /**
1652
+ * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
1653
+ * oversized tool result with a pointer to its first occurrence. The first
1654
+ * occurrence's hash is always recorded so later repeats can point at the
1655
+ * append-only original event even after the surface copy is reduced.
1656
+ */
1657
+ private planDedupe(
1658
+ candidate: SnapshotCandidate,
1659
+ session: Session,
1660
+ policy: CompressionPolicy,
1661
+ view: CompactionTokenView,
1662
+ ): PlannedReplacement | null {
1663
+ if (typeof candidate.event.surfaceOp === 'object') return null
1664
+ const result = candidate.event.data.message.content[0]
1665
+ const text = flattenPlainText(result.content)
1666
+ if (text === undefined) return null
1667
+ if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1668
+ let table = this.state.dedupeTables.get(session)
1669
+ if (table === undefined) {
1670
+ table = new DedupeTable()
1671
+ this.state.dedupeTables.set(session, table)
1672
+ }
1673
+ const hash = dedupeHash(text, 'trim-eol')
1674
+ const entry = table.get(hash)
1675
+ if (entry !== undefined && entry.seq !== candidate.seq) {
1676
+ const placeholder = dedupePlaceholder(entry, codePointLength(text))
1677
+ const plan = this.plan(
1678
+ candidate,
1679
+ [{ type: 'text', text: placeholder }],
1680
+ entry.seq,
1681
+ 'dedupe-pointer',
1682
+ 'fresh',
1683
+ 'fresh',
1684
+ undefined,
1685
+ view,
1686
+ { noNetSavingsGuard: true },
1687
+ )
1688
+ if (plan !== null) return plan
1689
+ return null
1690
+ }
1691
+ if (entry === undefined) {
1692
+ table.record(hash, {
1693
+ seq: candidate.seq,
1694
+ sourceRef: sourceRefFn(session, candidate.seq),
1695
+ toolName: candidate.call.name,
1696
+ originalChars: codePointLength(text),
1697
+ })
1698
+ }
1699
+ return null
1700
+ }
1701
+
1702
+ private planFresh(
1703
+ candidate: SnapshotCandidate,
1704
+ session: Session,
1705
+ policy: CompressionPolicy,
1706
+ view: CompactionTokenView,
1707
+ ): PlannedReplacement | null {
1708
+ // A replace event already reflects one frozen first-exposure decision. The
1709
+ // pre-step coordinate filter prevents previously-kept originals from ever
1710
+ // being reconsidered after their first request.
1711
+ if (typeof candidate.event.surfaceOp === 'object') return null
1712
+ const result = candidate.event.data.message.content[0]
1713
+ if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1714
+ const sourceSeq = candidate.seq
1715
+ const sourceRef = sourceRefFn(session, sourceSeq)
1716
+ const textBlock = onlyTextBlock(result.content)
1717
+ if (textBlock !== null) {
1718
+ let budgetChars = Math.max(1, Math.floor(codePointLength(textBlock.text) * 0.75))
1719
+ const codeSkeleton = this.activeSettings(session).codeSkeleton.enabled
1720
+ for (let attempt = 0; attempt < 10; attempt += 1) {
1721
+ const output = reduceFreshToolResult({
1722
+ toolName: candidate.call.name,
1723
+ argumentsText: candidate.call.arguments,
1724
+ text: textBlock.text,
1725
+ budgetChars,
1726
+ sourceRef,
1727
+ isError: result.isError === true || candidate.event.data.error !== undefined,
1728
+ codeSkeleton,
1729
+ })
1730
+ if (output !== null) {
1731
+ const plan = this.plan(
1732
+ candidate,
1733
+ [{ ...textBlock, text: output.text }],
1734
+ sourceSeq,
1735
+ output.reducer,
1736
+ 'fresh',
1737
+ 'fresh',
1738
+ undefined,
1739
+ view,
1740
+ {
1741
+ noNetSavingsGuard: policy.presetOptions?.noNetSavingsGuard === true,
1742
+ ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }),
1743
+ },
1744
+ )
1745
+ if (plan !== null && plan.charsAfter <= charsForTokens(policy.freshTargetTokens)) return plan
1746
+ }
1747
+ if (budgetChars === 1) break
1748
+ budgetChars = Math.max(1, Math.floor(budgetChars / 2))
1749
+ }
1750
+ }
1751
+
1752
+ return this.planAggregate(
1753
+ candidate,
1754
+ session,
1755
+ view,
1756
+ 'fresh-whole-result',
1757
+ 'fresh',
1758
+ policy.freshTargetTokens,
1759
+ 'fresh',
1760
+ )
1761
+ }
1762
+
1763
+ private planAggregate(
1764
+ candidate: SnapshotCandidate,
1765
+ session: Session,
1766
+ view: CompactionTokenView,
1767
+ reducer = 'fresh-step-aggregate',
1768
+ stage: PruneStage = 'fresh',
1769
+ targetTokens?: number,
1770
+ component: CompressionAuditComponent = 'aggregate',
1771
+ historyMode?: HistoryMode,
1772
+ ): PlannedReplacement | null {
1773
+ if (isError(candidate)) {
1774
+ return this.planErrorEvidence(
1775
+ candidate,
1776
+ session,
1777
+ view,
1778
+ stage,
1779
+ targetTokens,
1780
+ component,
1781
+ historyMode,
1782
+ )
1783
+ }
1784
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1785
+ const sourceRef = sourceRefFn(session, sourceSeq)
1786
+ // The placeholder below is a single text block, so a rich tool result (for
1787
+ // example one carrying an image) must never reach it. The character basis
1788
+ // no longer inherits the exact-tokenizer precondition that used to reject
1789
+ // this path implicitly, so the guard has to be explicit.
1790
+ const redacted = candidate.event.data.message.content[0]
1791
+ if (onlyTextBlocks(redacted.content) === null) return null
1792
+ const text = [
1793
+ '[Tool result reduced to satisfy the completed-step aggregate budget]',
1794
+ `tool: ${candidate.call.name}`,
1795
+ `source: ${sourceRef}`,
1796
+ 'Use context_compression_retrieve with this source if the omitted evidence is necessary.',
1797
+ ].join('\n')
1798
+ const plan = this.plan(
1799
+ candidate,
1800
+ [{ type: 'text', text }],
1801
+ sourceSeq,
1802
+ reducer,
1803
+ stage,
1804
+ component,
1805
+ historyMode,
1806
+ view,
1807
+ )
1808
+ return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1809
+ ? plan
1810
+ : null
1811
+ }
1812
+
1813
+ /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
1814
+ private planErrorEvidence(
1815
+ candidate: SnapshotCandidate,
1816
+ session: Session,
1817
+ view: CompactionTokenView,
1818
+ stage: PruneStage,
1819
+ targetTokens?: number,
1820
+ component: CompressionAuditComponent = 'aggregate',
1821
+ historyMode?: HistoryMode,
1822
+ ): PlannedReplacement | null {
1823
+ if (!isError(candidate)) return null
1824
+ const result = candidate.event.data.message.content[0]
1825
+ const blocks = onlyTextBlocks(result.content)
1826
+ if (blocks === null) return null
1827
+ const text = blocks.map(block => block.text).join('\n')
1828
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1829
+ const sourceRef = sourceRefFn(session, sourceSeq)
1830
+ const output = historicalPlaceholder({
1831
+ toolName: candidate.call.name,
1832
+ sourceRef,
1833
+ charsBefore: codePointLength(text),
1834
+ isError: true,
1835
+ text,
1836
+ compact: false,
1837
+ })
1838
+ const input = {
1839
+ toolName: candidate.call.name,
1840
+ argumentsText: candidate.call.arguments,
1841
+ text,
1842
+ budgetChars: 1_200,
1843
+ sourceRef,
1844
+ isError: true,
1845
+ }
1846
+ if (!verifyReduction(input, output)) return null
1847
+ const plan = this.plan(
1848
+ candidate,
1849
+ [{ type: 'text', text: output.text }],
1850
+ sourceSeq,
1851
+ 'error-evidence-placeholder',
1852
+ stage,
1853
+ component,
1854
+ historyMode,
1855
+ view,
1856
+ )
1857
+ return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1858
+ ? plan
1859
+ : null
1860
+ }
1861
+
1862
+ private planHistoricalAging(
1863
+ session: Session,
1864
+ policy: CompressionPolicy,
1865
+ view: CompactionTokenView,
1866
+ ): HistoryPlanOutcome {
1867
+ const candidates = this.snapshot(session, view)
1868
+ const events = sessionEvents(session)
1869
+ const chars = candidates.map(candidate => candidate.characterPressure)
1870
+ const total = chars.reduce((sum, charsOfNode) => sum + charsOfNode, 0)
1871
+ const trigger = charsForTokens(policy.historyTriggerTokens)
1872
+ // Full-request last chance: ordinary prose, images, prompts, or schemas can
1873
+ // push the complete request past the Auto Compact deadline before the tool
1874
+ // results alone cross the profile trigger.
1875
+ const deadline = policy.microDeadlineTokens
1876
+ const lastChance = deadline !== undefined && view.totalTokens >= deadline
1877
+ if (total <= trigger && !lastChance) return { kind: 'below-profile-trigger' }
1878
+
1879
+ const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
1880
+ const isUnsafe = (candidate: SnapshotCandidate): boolean => {
1881
+ if (this.isRecoveryExempt(session, candidate)) return true
1882
+ const result = candidate.event.data.message.content[0]
1883
+ const block = onlyTextBlock(result.content)
1884
+ // Fold-once: an already-folded intent block is never re-candidated.
1885
+ if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
1886
+ return block?.text.includes('[Old tool result content cleared from active context]') === true
1887
+ }
1888
+ // Distinguish "nothing safe to touch" (recovery tool output or already
1889
+ // cleared) from "everything left is inside the protected working set":
1890
+ // both skip, but they are different operational facts.
1891
+ const safe = candidates.filter(candidate => !isUnsafe(candidate))
1892
+ const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1893
+ if (eligible.length === 0) {
1894
+ return safe.length === 0
1895
+ ? { kind: 'no-safe-candidates' }
1896
+ : { kind: 'protected-working-set' }
1897
+ }
1898
+ const planned: PlannedReplacement[] = []
1899
+ let reclaim = 0
1900
+ // Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
1901
+ // postflight lands FIRST, through the same plan pipeline as every other
1902
+ // reducer; its reclaim counts toward the batch target and its seqs are
1903
+ // removed from the ordinary loop (fold-once).
1904
+ const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
1905
+ if (intentApplied !== undefined) {
1906
+ planned.push(...intentApplied.plans)
1907
+ reclaim += intentApplied.reclaim
1908
+ this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
1909
+ this.state.pendingIntentFolds.delete(session)
1910
+ this.state.intentBaselines.set(session, view.totalTokens)
1911
+ recordIntentFold(String(session.id), {
1912
+ turn: intentApplied.turn,
1913
+ startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
1914
+ endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
1915
+ liveTokensBefore: view.totalTokens,
1916
+ at: Date.now(),
1917
+ })
1918
+ emitCompressionAudit(this.ctx.logger, {
1919
+ schemaVersion: 1,
1920
+ kind: 'intent-summary-outcome',
1921
+ sessionId: String(session.id),
1922
+ ok: true,
1923
+ reason: 'landed',
1924
+ foldedCount: intentApplied.plans.length,
1925
+ ...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
1926
+ summaryCallChars: intentApplied.summaryCallChars,
1927
+ })
1928
+ for (let index = eligible.length - 1; index >= 0; index -= 1) {
1929
+ if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
1930
+ }
1931
+ }
1932
+ // Linked batches must reach the deadline target; unlinked batches keep
1933
+ // the traditional minimum-reclaim commit threshold. All arithmetic runs on
1934
+ // the character basis: token-named thresholds enter via charsForTokens.
1935
+ const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens)
1936
+ const microTarget = deadline === undefined ? undefined : Math.max(0, charsForTokens(deadline) - minReclaimChars)
1937
+ const required = Math.max(
1938
+ minReclaimChars,
1939
+ total - trigger,
1940
+ ...(microTarget === undefined ? [] : [charsForTokens(view.totalTokens) - microTarget]),
1941
+ )
1942
+ const batchTarget = microTarget === undefined
1943
+ ? minReclaimChars
1944
+ : required
1945
+ for (const candidate of eligible) {
1946
+ const result = candidate.event.data.message.content[0]
1947
+ const block = onlyTextBlock(result.content)
1948
+ // TokenPilot-inspired R2: a read output whose file was later mutated is
1949
+ // superseded — its text can no longer match the file — so it takes the
1950
+ // small whole-result placeholder before the ordinary reducer runs.
1951
+ if (policy.presetOptions?.readState === true && block !== null) {
1952
+ const readPath = toolCallPath(candidate.call.arguments)
1953
+ const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
1954
+ if (readPath !== undefined
1955
+ && (isSupersededRead(events, candidate.seq, readPath) || estimatorExpired)) {
1956
+ const plan = this.planAggregate(
1957
+ candidate,
1958
+ session,
1959
+ view,
1960
+ 'superseded-read-whole-result',
1961
+ 'pressure',
1962
+ undefined,
1963
+ 'history',
1964
+ policy.historyMode,
1965
+ )
1966
+ if (plan === null) continue
1967
+ planned.push(plan)
1968
+ reclaim += plan.charsBefore - plan.charsAfter
1969
+ if (reclaim >= required) break
1970
+ continue
1971
+ }
1972
+ }
1973
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1974
+ if (block === null) {
1975
+ const plan = this.planAggregate(
1976
+ candidate,
1977
+ session,
1978
+ view,
1979
+ 'historical-rich-whole-result',
1980
+ 'pressure',
1981
+ undefined,
1982
+ 'history',
1983
+ policy.historyMode,
1984
+ )
1985
+ if (plan === null) continue
1986
+ planned.push(plan)
1987
+ reclaim += plan.charsBefore - plan.charsAfter
1988
+ if (reclaim >= required) break
1989
+ continue
1990
+ }
1991
+ const output = historicalPlaceholder({
1992
+ toolName: candidate.call.name,
1993
+ sourceRef: sourceRefFn(session, sourceSeq),
1994
+ charsBefore: codePointLength(block.text),
1995
+ isError: result.isError === true || candidate.event.data.error !== undefined,
1996
+ text: block.text,
1997
+ compact: false,
1998
+ })
1999
+ const verifyInput = {
2000
+ toolName: candidate.call.name,
2001
+ argumentsText: candidate.call.arguments,
2002
+ text: block.text,
2003
+ budgetChars: 1_200,
2004
+ sourceRef: sourceRefFn(session, sourceSeq),
2005
+ isError: result.isError === true || candidate.event.data.error !== undefined,
2006
+ }
2007
+ if (!verifyReduction(verifyInput, output)) continue
2008
+ // TokenPilot-inspired R3: when read-state semantics are on, append an
2009
+ // error/warn/info census of the omitted lines so the model keeps
2010
+ // meta-knowledge about what was dropped.
2011
+ let replacementText = output.text
2012
+ if (policy.presetOptions?.readState === true) {
2013
+ const omitted = countOmittedLines(block.text, output.text)
2014
+ const census = omitted === undefined ? undefined : clusterOmittedLines(block.text, omitted)
2015
+ if (census !== undefined) replacementText = `${output.text}
2016
+ [... ${census} ...]`
2017
+ }
2018
+ const plan = this.plan(
2019
+ candidate,
2020
+ [{ ...block, text: replacementText }],
2021
+ sourceSeq,
2022
+ output.reducer,
2023
+ 'pressure',
2024
+ 'history',
2025
+ policy.historyMode,
2026
+ view,
2027
+ { ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }) },
2028
+ )
2029
+ if (plan === null) continue
2030
+ planned.push(plan)
2031
+ reclaim += plan.charsBefore - plan.charsAfter
2032
+ if (reclaim >= required) break
2033
+ }
2034
+ // Linked batches must reach the deadline target; unlinked batches keep
2035
+ // the traditional minimum-reclaim commit threshold.
2036
+ if (reclaim >= batchTarget && planned.length > 0) return historyOutcome(planned)
2037
+ return lastChance
2038
+ ? { kind: 'cannot-reach-deadline-target', reclaim, required }
2039
+ : { kind: 'insufficient-reclaim', reclaim, required }
2040
+ }
2041
+
2042
+ private protectedHistoryResultSeqs(
2043
+ session: Session,
2044
+ policy: CompressionPolicy,
2045
+ view: CompactionTokenView,
2046
+ ): Set<number> {
2047
+ const candidates = this.snapshot(session, view)
2048
+ return this.protectedHistoryCandidateSeqs(candidates, policy)
2049
+ }
2050
+
2051
+ /** Select the newest completed tool calls and token tail for History-derived stages. */
2052
+ private protectedHistoryCandidateSeqs(
2053
+ candidates: readonly SnapshotCandidate[],
2054
+ policy: CompressionPolicy,
2055
+ ): Set<number> {
2056
+ const protectedSeqs = new Set<number>()
2057
+ for (let index = candidates.length - 1;
2058
+ index >= 0 && candidates.length - index <= policy.historyKeepRecentToolCalls;
2059
+ index--) {
2060
+ const candidate = candidates[index]
2061
+ if (candidate !== undefined) protectedSeqs.add(candidate.seq)
2062
+ }
2063
+ let recentChars = 0
2064
+ for (let index = candidates.length - 1;
2065
+ index >= 0 && recentChars < charsForTokens(policy.historyKeepRecentTokens);
2066
+ index--) {
2067
+ const candidate = candidates[index]
2068
+ if (candidate === undefined) continue
2069
+ protectedSeqs.add(candidate.seq)
2070
+ recentChars += candidate.characterPressure
2071
+ }
2072
+ return protectedSeqs
2073
+ }
2074
+
2075
+ /** Atomically replace at most one oldest safe completed tool-call group. */
2076
+ private landOldestTailTrimGroup(
2077
+ session: Session,
2078
+ policy: CompressionPolicy,
2079
+ view: CompactionTokenView,
2080
+ ): void {
2081
+ const tailTrim = policy.tailTrim
2082
+ if (tailTrim?.enabled !== true) return
2083
+ const events = sessionEvents(session)
2084
+ if (view.currentSurfaceChars <= charsForTokens(tailTrim.triggerTokens)) {
2085
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2086
+ 'at-or-below-trigger', {
2087
+ measurementKind: 'characters',
2088
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2089
+ triggerTokens: tailTrim.triggerTokens,
2090
+ })
2091
+ return
2092
+ }
2093
+ const surfaceCount = view.currentSurface
2094
+ const exactSurface = surfaceCount.kind === 'exact-tokenizer' ? surfaceCount : undefined
2095
+ if (!this.hasRecoveryTool(session)) {
2096
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2097
+ 'recovery-tool-unavailable', {
2098
+ measurementKind: 'characters',
2099
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2100
+ triggerTokens: tailTrim.triggerTokens,
2101
+ })
2102
+ return
2103
+ }
2104
+ if (!hasOpenTurn(session)) {
2105
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2106
+ 'no-open-turn', {
2107
+ measurementKind: 'characters',
2108
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2109
+ triggerTokens: tailTrim.triggerTokens,
2110
+ })
2111
+ return
2112
+ }
2113
+ const protectedResults = this.protectedHistoryResultSeqs(session, policy, view)
2114
+ const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
2115
+ const nodeChars = new Map(view.measuredNodes.map(node => [node.seq, node.characterPressure]))
2116
+ const heuristic = new Map(view.nodes.map(node => [node.seq, node.tokens]))
2117
+ const completedTurns = new Set<number>()
2118
+ const completedSteps = new Set<string>()
2119
+ for (const event of events) {
2120
+ if (event.type === 'turn/end') completedTurns.add(event.data.turn)
2121
+ else if (event.type === 'step/end') completedSteps.add(`${String(event.data.turn)}:${String(event.data.step)}`)
2122
+ }
2123
+ const firstCompletedSurfaceTurn = session.surface.nodes
2124
+ .map(seq => eventBySeq(events, seq))
2125
+ .filter((event): event is SessionEvent<'assistant/message'> | SessionEvent<'tool/result'> =>
2126
+ (event?.type === 'assistant/message' || event?.type === 'tool/result')
2127
+ && completedTurns.has(event.data.turn))
2128
+ .reduce<number | undefined>(
2129
+ (first, event) => first === undefined ? event.data.turn : Math.min(first, event.data.turn),
2130
+ undefined,
2131
+ )
2132
+ const nodes = [...session.surface.nodes]
2133
+ for (let index = 0; index < nodes.length; index++) {
2134
+ const assistantSeq = nodes[index]
2135
+ if (assistantSeq === undefined) continue
2136
+ const assistant = eventBySeq(events, assistantSeq)
2137
+ if (assistant?.type !== 'assistant/message'
2138
+ || assistant.data.interrupted === true
2139
+ || assistant.data.message.content.length === 0
2140
+ || assistant.data.message.content.some(block => block.type !== 'tool-call')
2141
+ || assistant.data.turn === firstCompletedSurfaceTurn
2142
+ || !completedTurns.has(assistant.data.turn)
2143
+ || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue
2144
+ const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
2145
+ if (calls.some(call => call.name === 'context_compression_retrieve')) continue
2146
+ const callIds = calls.map(call => String(call.id))
2147
+ if (new Set(callIds).size !== callIds.length) continue
2148
+ const resultSeqs = nodes.slice(index + 1, index + 1 + calls.length)
2149
+ if (resultSeqs.length !== calls.length || resultSeqs.some(seq => protectedResults.has(seq))) continue
2150
+ const results = resultSeqs.map(seq => events[seq])
2151
+ if (results.some((event): boolean => {
2152
+ if (event?.type !== 'tool/result'
2153
+ || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
2154
+ || event.data.error !== undefined) return true
2155
+ const block = event.data.message.content[0]
2156
+ if (block.isError === true) return true
2157
+ // Images and other rich inner blocks stay fail-open: a TailTrim stub
2158
+ // would silently delete them from the active context.
2159
+ return block.content.some(contentBlock => contentBlock.type !== 'text')
2160
+ })) continue
2161
+ const next = events[nodes[index + 1 + calls.length] ?? -1]
2162
+ if (next?.type === 'tool/result'
2163
+ && next.data.turn === assistant.data.turn
2164
+ && next.data.step === assistant.data.step) continue
2165
+ const resultIds = results.map(event => event?.type === 'tool/result'
2166
+ ? String(event.data.message.source.callId) : '')
2167
+ if (new Set(resultIds).size !== resultIds.length
2168
+ || resultIds.some((id, resultIndex) => id !== callIds[resultIndex])) continue
2169
+ const shadowedSeqs = [assistantSeq, ...resultSeqs]
2170
+ const roots = shadowedSeqs.map(seq => this.uniqueAppendRoot(session, seq))
2171
+ if (roots.some(root => root === null)) continue
2172
+ const sourceEventSeqs = roots as number[]
2173
+ if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) continue
2174
+ // Exact tokens stay telemetry-only: they are recorded when every
2175
+ // shadowed node shares the surface tokenizer identity, and derived from
2176
+ // characters otherwise. The skip decisions above and below are all
2177
+ // character-based.
2178
+ let exactTokensBefore: number | undefined
2179
+ if (exactSurface !== undefined) {
2180
+ let sum = 0
2181
+ let allExact = true
2182
+ for (const seq of shadowedSeqs) {
2183
+ const count = measured.get(seq)
2184
+ if (count?.kind !== 'exact-tokenizer'
2185
+ || count.tokenizerId !== exactSurface.tokenizerId
2186
+ || count.tokenizerRevision !== exactSurface.tokenizerRevision) {
2187
+ allExact = false
2188
+ break
2189
+ }
2190
+ sum += count.tokens
2191
+ }
2192
+ if (allExact) exactTokensBefore = sum
2193
+ }
2194
+ const charsBefore = shadowedSeqs.reduce((sum, seq) => sum + (nodeChars.get(seq) ?? 0), 0)
2195
+ const manifestSeq = events.length
2196
+ const ref = tailTrimRef(String(session.id), manifestSeq)
2197
+ const stub = tailTrimStub(ref, calls.map(call => call.name), sourceEventSeqs)
2198
+ if (stub === null) continue
2199
+ const stubChars = codePointLength(stub)
2200
+ if (stubChars <= 0
2201
+ || charsBefore - stubChars < charsForTokens(policy.historyMinReclaimTokens)) continue
2202
+ let exactTokensAfter: number | undefined
2203
+ if (exactTokensBefore !== undefined && exactSurface !== undefined) {
2204
+ const stubCount = countExactCanonicalTextFields(
2205
+ [stub],
2206
+ candidate => view.countCanonicalText(candidate),
2207
+ 'TailTrim group stub',
2208
+ )
2209
+ if (stubCount.kind === 'exact-tokenizer'
2210
+ && stubCount.tokenizerId === exactSurface.tokenizerId
2211
+ && stubCount.tokenizerRevision === exactSurface.tokenizerRevision) {
2212
+ exactTokensAfter = stubCount.tokens
2213
+ }
2214
+ }
2215
+ const exact = exactTokensBefore !== undefined && exactTokensAfter !== undefined
2216
+ const tokensBefore = exactTokensBefore ?? charsToTokens(charsBefore)
2217
+ const tokensAfter = exactTokensAfter ?? charsToTokens(stubChars)
2218
+ const heuristicTokens = shadowedSeqs.reduce((sum, seq) => sum + (heuristic.get(seq) ?? 0), 0)
2219
+ const range = { start: SessionSeq(assistantSeq), end: SessionSeq(resultSeqs.at(-1) ?? assistantSeq) }
2220
+ const surfaceRange = { op: 'replace' as const, startSeq: range.start, endSeq: range.end }
2221
+ if (!this.reserveTailTrimBoundaryAttempt(session)) {
2222
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2223
+ 'already-attempted-at-request-boundary', {
2224
+ measurementKind: 'characters',
2225
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2226
+ triggerTokens: tailTrim.triggerTokens,
2227
+ })
2228
+ return
2229
+ }
2230
+ const manifest = session.append('compaction/prune', {
2231
+ shadowedRange: range,
2232
+ shadowedSeqs,
2233
+ shadowedTokenCount: heuristicTokens,
2234
+ })
2235
+ let replacement: SessionEvent<'user/message'>
2236
+ try {
2237
+ replacement = session.append('user/message', tailTrimMessage(stub), {
2238
+ surfaceOp: surfaceRange,
2239
+ sourceEventSeqs: [manifest.seq, ...shadowedSeqs],
2240
+ })
2241
+ } catch (error) {
2242
+ this.auditPublicationFailure(
2243
+ session,
2244
+ 'pressure',
2245
+ 'tail-trim',
2246
+ manifest.seq,
2247
+ error,
2248
+ )
2249
+ return
2250
+ }
2251
+ emitCompressionAudit(this.ctx.logger, {
2252
+ schemaVersion: 1,
2253
+ kind: 'rewrite',
2254
+ sessionId: String(session.id),
2255
+ profile: policy.profile,
2256
+ component: 'tail-trim',
2257
+ stage: 'pressure',
2258
+ reducer: 'pair-preserving-tail-trim',
2259
+ manifestEventType: 'compaction/prune',
2260
+ manifestSeq: manifest.seq,
2261
+ replacementSeq: replacement.seq,
2262
+ sourceSeqs: sourceEventSeqs,
2263
+ tokensBefore,
2264
+ tokensAfter,
2265
+ tokensRemoved: tokensBefore - tokensAfter,
2266
+ measurementBasis: exact ? 'exact-tokenizer' : 'characters',
2267
+ tokenizerId: exact === true && exactSurface !== undefined
2268
+ ? exactSurface.tokenizerId
2269
+ : 'characters',
2270
+ tokenizerRevision: exact === true && exactSurface !== undefined
2271
+ ? exactSurface.tokenizerRevision
2272
+ : 'chars-per-token-4.0',
2273
+ })
2274
+ // 节省统计:tail-trim 组的原文配对键(纯文本结果才登记,富内容跳过——
2275
+ // 与 land() 同口径:只记已落盘、可配对者)。
2276
+ const groupText = shadowedSeqs
2277
+ .map(seq => sessionEvents(session)[seq])
2278
+ .filter((event): event is SessionEvent<'tool/result'> => event?.type === 'tool/result')
2279
+ .map(event => flattenPlainText(event.data.message.content))
2280
+ .filter((text): text is string => text !== undefined)
2281
+ .join('\n')
2282
+ if (groupText.length > 0) {
2283
+ getSavingsLedger().recordSaving({
2284
+ sessionId: String(session.id),
2285
+ component: 'tail-trim',
2286
+ tokensBefore,
2287
+ tokensAfter,
2288
+ basis: exact ? 'exact-tokenizer' : 'characters',
2289
+ sourceSeq: manifestSeq,
2290
+ originalText: groupText,
2291
+ })
2292
+ }
2293
+ return
2294
+ }
2295
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2296
+ 'no-safe-eligible-tool-group', {
2297
+ measurementKind: 'characters',
2298
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2299
+ triggerTokens: tailTrim.triggerTokens,
2300
+ })
2301
+ }
2302
+
2303
+ private reserveTailTrimBoundaryAttempt(session: Session): boolean {
2304
+ const boundary = this.state.activeRequestBoundaries.get(session)
2305
+ if (boundary === undefined) return true
2306
+ if (this.state.tailTrimBoundaryAttempts.get(session) === boundary) return false
2307
+ this.state.tailTrimBoundaryAttempts.set(session, boundary)
2308
+ return true
2309
+ }
2310
+
2311
+ private uniqueAppendRoot(session: Session, seq: number): number | null {
2312
+ const events = sessionEvents(session)
2313
+ const pending: Array<{ seq: number; depth: number }> = [{ seq, depth: 0 }]
2314
+ const visited = new Set<number>()
2315
+ const roots = new Set<number>()
2316
+ while (pending.length > 0) {
2317
+ const next = pending.pop()
2318
+ if (next === undefined || next.depth > 64 || visited.has(next.seq)) continue
2319
+ visited.add(next.seq)
2320
+ if (visited.size > 64) return null
2321
+ const event = events[next.seq]
2322
+ if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
2323
+ if (event.surfaceOp === 'append') roots.add(event.seq)
2324
+ else if (typeof event.surfaceOp === 'object') {
2325
+ const sources = event.sourceEventSeqs
2326
+ if (sources === undefined || sources.length === 0) return null
2327
+ for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
2328
+ } else return null
2329
+ if (roots.size > 1) return null
2330
+ }
2331
+ return roots.size === 1 ? [...roots][0] ?? null : null
2332
+ }
2333
+
2334
+ private plan(
2335
+ candidate: SnapshotCandidate,
2336
+ content: ContentBlock[],
2337
+ sourceSeq: number,
2338
+ reducer: string,
2339
+ stage: PruneStage,
2340
+ component: CompressionAuditComponent,
2341
+ historyMode: HistoryMode | undefined,
2342
+ view: CompactionTokenView,
2343
+ options: { readonly noNetSavingsGuard?: boolean, readonly elidedLines?: number } = {},
2344
+ ): PlannedReplacement | null {
2345
+ const charsBefore = candidate.characterPressure
2346
+ const charsAfter = pressureCost(content)
2347
+ // Character proof replaces the exact-tokenizer precondition: a reduction
2348
+ // must shrink the decision surface regardless of the routed model id.
2349
+ if (charsAfter <= 0 || charsAfter >= charsBefore) return null
2350
+ // Tokens are telemetry only: exact when both sides share one bundled
2351
+ // tokenizer identity, otherwise derived from the character measurement.
2352
+ const countBefore = candidate.count
2353
+ const countAfter = countToolContent(content, view)
2354
+ const exact = countBefore.kind === 'exact-tokenizer'
2355
+ && countAfter.kind === 'exact-tokenizer'
2356
+ && countAfter.tokenizerId === countBefore.tokenizerId
2357
+ && countAfter.tokenizerRevision === countBefore.tokenizerRevision
2358
+ const tokensBefore = exact ? countBefore.tokens : charsToTokens(charsBefore)
2359
+ const tokensAfter = exact ? countAfter.tokens : charsToTokens(charsAfter)
2360
+ // TokenPilot-style no-net-savings: even when the exact tokenizer reports a
2361
+ // saving, a replacement whose text is not smaller than its original adds
2362
+ // noise without reclaiming context. Text-level because the placeholder
2363
+ // guidance lines (source refs, retrieval hints) must pay for themselves.
2364
+ if (options.noNetSavingsGuard === true) {
2365
+ const originalBlocks = onlyTextBlocks(candidate.event.data.message.content[0].content)
2366
+ const replacementBlocks = onlyTextBlocks(content)
2367
+ if (originalBlocks !== null && replacementBlocks !== null) {
2368
+ const originalChars = originalBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
2369
+ const replacementChars = replacementBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
2370
+ if (replacementChars >= originalChars) return null
2371
+ }
2372
+ }
2373
+ return {
2374
+ candidate,
2375
+ content,
2376
+ sourceSeq,
2377
+ reducer,
2378
+ stage,
2379
+ component,
2380
+ ...historyMode === undefined ? {} : { historyMode },
2381
+ charsBefore,
2382
+ charsAfter,
2383
+ tokensBefore,
2384
+ tokensAfter,
2385
+ measurementBasis: exact ? 'exact-tokenizer' : 'characters',
2386
+ tokenizerId: exact ? countBefore.tokenizerId : 'characters',
2387
+ tokenizerRevision: exact ? countBefore.tokenizerRevision : 'chars-per-token-4.0',
2388
+ ...options.elidedLines === undefined ? {} : { elidedLines: options.elidedLines },
2389
+ }
2390
+ }
2391
+
2392
+ private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
2393
+ const { candidate } = plan
2394
+ const result = candidate.event.data.message.content[0]
2395
+ const message = freezeMessage<ToolResultMessage>({
2396
+ ...candidate.event.data.message,
2397
+ content: [{ ...result, content: plan.content }] as [typeof result],
2398
+ })
2399
+ const manifest = session.append('compaction/prune', {
2400
+ shadowedRange: { start: SessionSeq(candidate.seq), end: SessionSeq(candidate.seq) },
2401
+ shadowedSeqs: [SessionSeq(candidate.seq)],
2402
+ shadowedTokenCount: candidate.shadowedHeuristicTokenCount,
2403
+ })
2404
+ let replacement: SessionEvent<'tool/result'>
2405
+ try {
2406
+ replacement = session.append('tool/result', {
2407
+ ...candidate.event.data,
2408
+ message,
2409
+ }, {
2410
+ surfaceOp: { op: 'replace', startSeq: SessionSeq(candidate.seq), endSeq: SessionSeq(candidate.seq) },
2411
+ sourceEventSeqs: [SessionSeq(candidate.seq)],
2412
+ })
2413
+ } catch (error) {
2414
+ this.auditPublicationFailure(
2415
+ session,
2416
+ plan.stage,
2417
+ plan.component,
2418
+ manifest.seq,
2419
+ error,
2420
+ )
2421
+ return null
2422
+ }
2423
+ emitCompressionAudit(this.ctx.logger, {
2424
+ schemaVersion: 1,
2425
+ kind: 'rewrite',
2426
+ sessionId: String(session.id),
2427
+ profile: this.activeSettings(session).profile,
2428
+ component: plan.component,
2429
+ stage: plan.stage,
2430
+ reducer: plan.reducer,
2431
+ ...plan.historyMode === undefined ? {} : { historyMode: plan.historyMode },
2432
+ manifestEventType: 'compaction/prune',
2433
+ manifestSeq: manifest.seq,
2434
+ replacementSeq: replacement.seq,
2435
+ sourceSeqs: [plan.sourceSeq],
2436
+ tokensBefore: plan.tokensBefore,
2437
+ tokensAfter: plan.tokensAfter,
2438
+ tokensRemoved: plan.tokensBefore - plan.tokensAfter,
2439
+ measurementBasis: plan.measurementBasis,
2440
+ tokenizerId: plan.tokenizerId,
2441
+ tokenizerRevision: plan.tokenizerRevision,
2442
+ // task_4c/G7 telemetry: original-event lines the reducer elided. Audit
2443
+ // record ONLY — the replacement content is untouched by this field.
2444
+ ...plan.elidedLines === undefined ? {} : { elidedLines: plan.elidedLines },
2445
+ })
2446
+ // 节省统计:已实现的削减才入账(tokensBefore−tokensAfter,审计同源同口径);
2447
+ // 原文哈希登记,供后续全文重读/retrieve 抵消配对。
2448
+ const pairedOriginal = originalTextForSavings(candidate)
2449
+ getSavingsLedger().recordSaving({
2450
+ sessionId: String(session.id),
2451
+ component: plan.component,
2452
+ tokensBefore: plan.tokensBefore,
2453
+ tokensAfter: plan.tokensAfter,
2454
+ basis: plan.measurementBasis,
2455
+ sourceSeq: plan.sourceSeq,
2456
+ ...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
2457
+ })
2458
+ return {
2459
+ originalSeq: candidate.seq,
2460
+ sourceSeq: plan.sourceSeq,
2461
+ replacementSeq: replacement.seq,
2462
+ callId: candidate.event.data.message.source.callId,
2463
+ reducer: plan.reducer,
2464
+ stage: plan.stage,
2465
+ charsBefore: plan.charsBefore,
2466
+ charsAfter: plan.charsAfter,
2467
+ tokensBefore: plan.tokensBefore,
2468
+ tokensAfter: plan.tokensAfter,
2469
+ }
2470
+ }
2471
+
2472
+ private landAll(session: Session, plans: readonly PlannedReplacement[]): PrunedEntry[] {
2473
+ if (plans.length === 0) return []
2474
+ if (!this.hasRecoveryTool(session)) {
2475
+ this.warnOnce(
2476
+ session,
2477
+ 'missing-context-retrieve',
2478
+ 'context-compression kept original tool results because context_compression_retrieve is unavailable',
2479
+ )
2480
+ return []
2481
+ }
2482
+ if (!hasOpenTurn(session)) {
2483
+ throw new Error('tool-result pruning cannot append a surface replacement outside any open turn')
2484
+ }
2485
+ const landed: PrunedEntry[] = []
2486
+ for (const plan of plans) {
2487
+ const entry = this.land(session, plan)
2488
+ if (entry === null) break
2489
+ landed.push(entry)
2490
+ }
2491
+ return landed
2492
+ }
2493
+
2494
+ private hasRecoveryTool(session: Session): boolean {
2495
+ const tools = this.ctx.get('tools')
2496
+ if (tools === undefined) return false
2497
+ const agent = this.ctx.get('agents')?.get(session.id)
2498
+ return tools.get('context_compression_retrieve', agent) !== undefined
2499
+ }
2500
+
2501
+ private auditHistoryEvaluation(
2502
+ session: Session,
2503
+ policy: CompressionPolicy,
2504
+ view: CompactionTokenView,
2505
+ allowed: boolean,
2506
+ outcome: HistoryPlanOutcome,
2507
+ ): void {
2508
+ if (policy.historyMode === 'disabled') {
2509
+ this.auditComponent(session, policy, 'history', 'pressure', 'disabled', 'profile-policy', {
2510
+ historyMode: policy.historyMode,
2511
+ })
2512
+ return
2513
+ }
2514
+ if (!allowed && outcome.kind === 'planned') {
2515
+ // The authority gate itself refused: below the frozen micro deadline
2516
+ // (capacity-pressure) or the adaptive cost estimate rejected the batch.
2517
+ const deadlineTrigger = policy.microDeadlineTokens
2518
+ const capacity = deadlineTrigger === undefined ? session.requestContext()?.contextWindow : undefined
2519
+ const capacityTrigger = deadlineTrigger !== undefined
2520
+ ? deadlineTrigger
2521
+ : Number.isSafeInteger(capacity) && capacity !== undefined && capacity > 0
2522
+ ? Math.floor(capacity * CAPACITY_PRESSURE_RATIO)
2523
+ : undefined
2524
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2525
+ policy.historyMode === 'capacity-pressure'
2526
+ ? 'below-micro-deadline' : 'adaptive-cost-rejected', {
2527
+ historyMode: policy.historyMode,
2528
+ measurementKind: 'characters',
2529
+ currentTokens: view.totalTokens,
2530
+ ...(capacityTrigger === undefined ? {} : { triggerTokens: capacityTrigger }),
2531
+ })
2532
+ return
2533
+ }
2534
+ const deadline = policy.microDeadlineTokens
2535
+ const lastChance = deadline !== undefined && view.totalTokens >= deadline
2536
+ const detail = (extra: Readonly<Record<string, number>> = {}): Readonly<{
2537
+ historyMode?: HistoryMode
2538
+ measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
2539
+ currentTokens?: number
2540
+ triggerTokens?: number
2541
+ reclaimTokens?: number
2542
+ requiredTokens?: number
2543
+ }> => ({
2544
+ historyMode: policy.historyMode,
2545
+ measurementKind: 'characters',
2546
+ currentTokens: view.totalTokens,
2547
+ ...(outcome.kind === 'insufficient-reclaim' || outcome.kind === 'cannot-reach-deadline-target'
2548
+ ? { reclaimTokens: outcome.reclaim, requiredTokens: outcome.required }
2549
+ : {}),
2550
+ ...extra,
2551
+ })
2552
+ switch (outcome.kind) {
2553
+ case 'below-profile-trigger':
2554
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2555
+ 'below-profile-trigger', detail({ triggerTokens: policy.historyTriggerTokens }))
2556
+ return
2557
+ case 'no-safe-candidates':
2558
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2559
+ 'no-safe-candidates', detail({ triggerTokens: policy.historyTriggerTokens }))
2560
+ return
2561
+ case 'protected-working-set':
2562
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2563
+ 'protected-working-set', detail({ triggerTokens: policy.historyTriggerTokens }))
2564
+ return
2565
+ case 'insufficient-reclaim':
2566
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2567
+ 'insufficient-reclaim', detail({ triggerTokens: policy.historyTriggerTokens }))
2568
+ return
2569
+ case 'cannot-reach-deadline-target':
2570
+ // Planning engaged through the full-request last-chance gate; the
2571
+ // routine trigger numbers below would misdescribe why nothing landed.
2572
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2573
+ 'cannot-reach-deadline-target', detail(lastChance ? { triggerTokens: deadline } : {}))
2574
+ return
2575
+ case 'planned':
2576
+ // A committed batch that landed nothing means the recovery tool was
2577
+ // unavailable at landing time; a degenerate empty commit reads as an
2578
+ // unreachable target instead.
2579
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2580
+ outcome.plans.length > 0 ? 'recovery-tool-unavailable' : 'insufficient-reclaim',
2581
+ detail({ triggerTokens: lastChance ? deadline : policy.historyTriggerTokens }))
2582
+ return
2583
+ /* v8 ignore next -- closed-union exhaustiveness guard */
2584
+ default:
2585
+ return assertNever(outcome, 'history plan outcome')
2586
+ }
2587
+ }
2588
+
2589
+ private auditComponent(
2590
+ session: Session,
2591
+ policy: CompressionPolicy,
2592
+ component: CompressionAuditComponent,
2593
+ stage: PruneStage,
2594
+ status: CompressionAuditEvaluationStatus,
2595
+ reason: string,
2596
+ detail: Readonly<{
2597
+ historyMode?: HistoryMode
2598
+ measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
2599
+ currentTokens?: number
2600
+ triggerTokens?: number
2601
+ targetTokens?: number
2602
+ reclaimTokens?: number
2603
+ requiredTokens?: number
2604
+ }> = {},
2605
+ ): void {
2606
+ emitCompressionAudit(this.ctx.logger, {
2607
+ schemaVersion: 1,
2608
+ kind: 'component-evaluation',
2609
+ sessionId: String(session.id),
2610
+ profile: policy.profile,
2611
+ component,
2612
+ stage,
2613
+ status,
2614
+ reason,
2615
+ ...detail,
2616
+ })
2617
+ }
2618
+
2619
+ /** Emit the native-auto-compact audit for one summary manifest, once. */
2620
+ private emitNativeSummaryAudit(
2621
+ session: Session,
2622
+ manifestSeq: number,
2623
+ data: { provider?: unknown, model?: unknown, shadowedTokenCount?: unknown },
2624
+ ): void {
2625
+ let audited = this.auditedNativeSummaries.get(session)
2626
+ if (audited === undefined) {
2627
+ audited = new Set()
2628
+ this.auditedNativeSummaries.set(session, audited)
2629
+ }
2630
+ if (audited.has(manifestSeq)) return
2631
+ audited.add(manifestSeq)
2632
+ emitCompressionAudit(this.ctx.logger, {
2633
+ schemaVersion: 1,
2634
+ kind: 'native-auto-compact',
2635
+ sessionId: String(session.id),
2636
+ manifestEventType: 'compaction/summary',
2637
+ manifestSeq,
2638
+ reducer: 'llm-summary',
2639
+ provider: data.provider === undefined ? 'unknown' : String(data.provider),
2640
+ model: data.model === undefined ? 'unknown' : String(data.model),
2641
+ tokensBefore: typeof data.shadowedTokenCount === 'number' ? data.shadowedTokenCount : null,
2642
+ tokensAfter: null,
2643
+ })
2644
+ }
2645
+
2646
+ /**
2647
+ * 0.1.5 commits Native auto-compact by reopening the Session with a seed
2648
+ * log; seed events never reach the `session/event` firehose, so scan the
2649
+ * snapshot for summary manifests the live listener could not observe.
2650
+ */
2651
+ private scanForSeededNativeSummary(session: Session): void {
2652
+ for (const event of sessionEvents(session)) {
2653
+ if (event.type === 'compaction/summary') {
2654
+ this.emitNativeSummaryAudit(session, event.seq, event.data)
2655
+ }
2656
+ }
2657
+ }
2658
+
2659
+ private auditFailure(
2660
+ session: Session,
2661
+ stage: PruneStage,
2662
+ operation:
2663
+ | 'request-boundary'
2664
+ | 'terminal-pass'
2665
+ | 'policy-resolution'
2666
+ | 'summary-locator'
2667
+ | 'publication',
2668
+ error: unknown,
2669
+ ): void {
2670
+ emitCompressionAudit(this.ctx.logger, {
2671
+ schemaVersion: 1,
2672
+ kind: 'failure',
2673
+ sessionId: String(session.id),
2674
+ stage,
2675
+ operation,
2676
+ errorName: error instanceof Error ? error.name : 'UnknownError',
2677
+ errorMessage: error instanceof Error ? error.message : String(error),
2678
+ })
2679
+ }
2680
+
2681
+ private auditPublicationFailure(
2682
+ session: Session,
2683
+ stage: PruneStage,
2684
+ component: CompressionAuditComponent,
2685
+ manifestSeq: number,
2686
+ error: unknown,
2687
+ ): void {
2688
+ emitCompressionAudit(this.ctx.logger, {
2689
+ schemaVersion: 1,
2690
+ kind: 'failure',
2691
+ sessionId: String(session.id),
2692
+ stage,
2693
+ operation: 'publication',
2694
+ component,
2695
+ manifestSeq,
2696
+ errorName: error instanceof Error ? error.name : 'UnknownError',
2697
+ errorMessage: 'surface replacement append failed after compaction/prune committed',
2698
+ })
2699
+ }
2700
+
2701
+ private warnExactUnavailable(
2702
+ session: Session,
2703
+ view: CompactionTokenView,
2704
+ gate: 'native' | 'fresh' | 'aggregate' | 'history' | 'tailtrim',
2705
+ ): void {
2706
+ const provider = view.providerRoute ?? 'unbound-provider'
2707
+ const model = view.modelId ?? 'unbound-model'
2708
+ this.warnOnce(
2709
+ session,
2710
+ `exact-tokenizer:${gate}:${provider}\0${model}`,
2711
+ 'context-compression %s is measuring on the character basis: exact tokenizer counts are unavailable for %s/%s',
2712
+ gate,
2713
+ provider,
2714
+ model,
2715
+ )
2716
+ }
2717
+
2718
+ private warnOnce(
2719
+ session: Session,
2720
+ key: string,
2721
+ message: string,
2722
+ ...args: unknown[]
2723
+ ): void {
2724
+ let warned = this.state.warnedFailures.get(session)
2725
+ if (warned === undefined) {
2726
+ warned = new Set()
2727
+ this.state.warnedFailures.set(session, warned)
2728
+ }
2729
+ if (warned.has(key)) return
2730
+ warned.add(key)
2731
+ this.ctx.logger.warn(message, ...args)
2732
+ }
2733
+
2734
+ }
2735
+
2736
+ export default ToolResultPruner