dsh-context-compression-improved 0.2.3 → 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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  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 +94 -112
  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 +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  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 +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  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 +249 -111
  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/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,2144 +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
- TokenCount,
24
- } from './runtime/measurement.ts'
25
- import { measureForCompaction } from './runtime/measurement.ts'
26
- import { 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
- exactTokens,
43
- sameProviderMeasurementKey,
44
- unavailableCount,
45
- recoveryMarker,
46
- summarize,
47
- emptyResult,
48
- measureContent,
49
- pressureCost,
50
- nativePruneContent,
51
- } from './pruner/content.ts'
52
- import {
53
- hasOpenTurn,
54
- rootToolResultSeq,
55
- sourceRef as sourceRefFn,
56
- latestCompletedToolStep,
57
- routeAuditFact,
58
- tokenizerAuditFact,
59
- isError,
60
- historyOutcome,
61
- } from './pruner/session.ts'
62
- import { buildLocatorBlock, findCompactionTrace } from './runtime/tokenpilot/locator.ts'
63
- import { clusterOmittedLines, isSupersededRead, toolCallPath } from './runtime/tokenpilot/read-state.ts'
64
- import {
65
- Estimator,
66
- backoffCooldownMs,
67
- buildEstimatorSystemPrompt,
68
- buildEstimatorUserPrompt,
69
- isCoolingDown,
70
- parseEstimatorAnswer,
71
- type EstimatorFailures,
72
- type EstimatorSample,
73
- } from './runtime/tokenpilot/estimator.ts'
74
-
75
- import {
76
- DedupeTable,
77
- dedupeHash,
78
- dedupePlaceholder,
79
- flattenPlainText,
80
- } from './runtime/tokenpilot/dedup.ts'
81
- import {
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 exact = eligible.flatMap(candidate => candidate.count.kind === 'exact-tokenizer'
355
- ? [candidate.count.tokens] : [])
356
- this.auditComponent(session, policy, 'native-tool-result', 'pressure', 'skipped',
357
- exactUnavailable ? 'exact-tokenizer-unavailable'
358
- : exact.length === 0 ? 'no-tool-result-candidates'
359
- : Math.max(...exact) <= policy.nativeTriggerTokens ? 'at-or-below-trigger'
360
- : planned.length === 0 ? 'no-valid-reduction'
361
- : 'recovery-tool-unavailable', {
362
- measurementKind: exactUnavailable ? 'unavailable' : 'exact-tokenizer',
363
- ...(exact.length === 0 ? {} : { currentTokens: Math.max(...exact) }),
364
- triggerTokens: policy.nativeTriggerTokens,
365
- targetTokens: policy.nativeTargetTokens,
366
- })
367
- }
368
- return summarize(landed)
369
- }
370
-
371
- let historyOutcome: HistoryPlanOutcome = { kind: 'planned', plans: [] }
372
- let historyAllowed = false
373
- if (policy.historyMode === 'adaptive') {
374
- historyOutcome = this.planHistoricalAging(session, policy, view)
375
- // Adaptive cost authority is meaningful only after the structural
376
- // planner has formed a real batch. A planning skip keeps its own reason
377
- // (for example exact-tokenizer-unavailable) and never becomes a false
378
- // adaptive-cost-rejected decision merely because it has zero plans.
379
- if (historyOutcome.kind === 'planned') {
380
- const capacityPressure = this.capacityPressureActive(session, view, policy)
381
- historyAllowed = this.adaptiveHistoryAllowed(
382
- session,
383
- view,
384
- historyOutcome.plans,
385
- capacityPressure,
386
- )
387
- if (historyAllowed) {
388
- landed.push(...this.landAll(session, historyOutcome.plans))
389
- }
390
- }
391
- } else {
392
- historyAllowed = this.historyAllowed(session, policy, view)
393
- if (historyAllowed) {
394
- historyOutcome = this.planHistoricalAging(session, policy, view)
395
- if (historyOutcome.kind === 'planned') {
396
- landed.push(...this.landAll(session, historyOutcome.plans))
397
- }
398
- }
399
- }
400
- if (!landed.some(entry => entry.stage === 'pressure')) {
401
- this.auditHistoryEvaluation(session, policy, view, historyAllowed, historyOutcome)
402
- }
403
- if (policy.tailTrim?.enabled === true) {
404
- const tailView = measureForCompaction(this.ctx, session)
405
- this.landOldestTailTrimGroup(session, policy, tailView)
406
- } else {
407
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'disabled', 'profile-policy')
408
- }
409
- return summarize(landed)
410
- }
411
-
412
- private activeSettings(session: Session): ContextCompressionSettings {
413
- const frozen = this.state.sessionSettings.get(session)
414
- if (frozen !== undefined) return frozen
415
- // Harness 0.1.1 brands namespace values through a helper while 0.1.2
416
- // validates the same public literal at its SettingsProvider boundary.
417
- const settings = this.ctx.get('settings')?.get(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
418
- let resolved: ContextCompressionSettings
419
- let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
420
- ? 'plugin-config-fallback'
421
- : 'host-settings'
422
- let autoCompactThresholdSource: 'generation-config' | 'host-settings' | 'schema-default'
423
- = settings === undefined ? 'schema-default' : 'host-settings'
424
- let settingsInvalidFallback: 'lossless-off' | undefined
425
- try {
426
- resolved = settings === undefined
427
- ? ContextCompressionSettingsSchema({ profile: this.state.config.profile } as never)
428
- // Validate the Host value BEFORE cloning: structuredClone normalizes
429
- // class/exotic prototypes to Object.prototype and would otherwise
430
- // erase the very boundary the parser is responsible for enforcing.
431
- : parseContextCompressionSettings(settings)
432
- } catch (error: unknown) {
433
- // A malformed persisted document must fail open LOSSLESSLY: freezing the
434
- // deployment default could silently re-enable lossy compression the
435
- // user never chose (for example a stored `off` plus an unknown key), so
436
- // the session freezes effectively off and keeps every original result.
437
- const reason = error instanceof Error ? error.message : String(error)
438
- this.auditFailure(session, 'pressure', 'policy-resolution', error)
439
- this.warnOnce(
440
- session,
441
- `settings-invalid:${reason}`,
442
- 'context-compression froze this session effectively off because the stored settings document is invalid: %s',
443
- reason,
444
- )
445
- resolved = ContextCompressionSettingsSchema({ profile: 'off' } as never)
446
- settingsSource = 'plugin-config-fallback'
447
- autoCompactThresholdSource = 'schema-default'
448
- settingsInvalidFallback = 'lossless-off'
449
- }
450
- if (this.state.config.autoCompactThresholdPercent !== undefined) {
451
- // The preset overlay froze this generation's threshold into the
452
- // deployment config; it supersedes the live Host setting so Auto
453
- // Compact and micro compact can never split across two thresholds.
454
- resolved = {
455
- ...resolved,
456
- autoCompact: { thresholdPercent: this.state.config.autoCompactThresholdPercent },
457
- }
458
- autoCompactThresholdSource = 'generation-config'
459
- }
460
- const snapshot = deepFreeze(structuredClone(resolved))
461
- this.state.sessionSettings.set(session, snapshot)
462
- emitCompressionAudit(this.ctx.logger, {
463
- schemaVersion: 1,
464
- kind: 'policy-frozen',
465
- sessionId: String(session.id),
466
- settingsSource,
467
- autoCompactThresholdSource,
468
- ...settingsInvalidFallback === undefined ? {} : { settingsInvalidFallback },
469
- settings: snapshot,
470
- deploymentConfig: this.state.config,
471
- })
472
- return snapshot
473
- }
474
-
475
- /**
476
- * TokenPilot-inspired A2: replace the compaction summary checkpoint node
477
- * with the same summary plus an Exact Sources locator block. Fails open:
478
- * any unresolved shape (no trace, no checkpoint node, already annotated)
479
- * leaves the summary untouched.
480
- */
481
- private attachSummaryLocator(session: Session, compactionId: string): void {
482
- const policy = this.activePolicy(session)
483
- if (policy?.presetOptions?.summaryLocator !== true) return
484
- const events = sessionEvents(session)
485
- const trace = findCompactionTrace(events, compactionId)
486
- if (trace === undefined) return
487
- const located = buildLocatorBlock(events, trace.summaryShadowedRange)
488
- if (located === null) return
489
- const block = located.text
490
- // Locate the summary checkpoint surface node: the user/message replacement
491
- // carrying this compaction's checkpoint provenance. Newest match wins.
492
- let checkpointSeq: number | undefined
493
- for (const seq of [...session.surface.nodes].reverse()) {
494
- const event = events[seq]
495
- if (event === undefined || event.type !== 'user/message') continue
496
- const source = (event.data as { source?: { compactionId?: unknown } }).source
497
- if (source === undefined || source === null) continue
498
- if (source.compactionId !== compactionId) continue
499
- checkpointSeq = seq
500
- break
501
- }
502
- if (checkpointSeq === undefined) return
503
- const original = events[checkpointSeq]
504
- if (original?.type !== 'user/message') return
505
- const data = original.data as UserMessage & { source?: unknown }
506
- const content = data.content.map(block => ({ ...block })) as typeof data.content
507
- const textBlocks = content.filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text')
508
- const lastText = textBlocks.at(-1)
509
- const marker = '## Exact Sources (locators)'
510
- if (lastText === undefined) return
511
- if (lastText.text.includes(marker)) return
512
- lastText.text = `${lastText.text}\n\n${block}`
513
- // Drop the checkpoint provenance: this replacement is a plain plugin-source
514
- // user/message surface rewrite, not a new compaction checkpoint, and
515
- // carrying the marker would fail the host's closed-transaction validation.
516
- const replacement = createUserMessage({
517
- content,
518
- source: { kind: 'plugin', plugin: 'dsh-context-compression-improved-runtime' },
519
- })
520
- session.append('user/message', replacement, {
521
- surfaceOp: { op: 'replace', start: checkpointSeq, end: checkpointSeq },
522
- sourceEventSeqs: [checkpointSeq],
523
- })
524
- emitCompressionAudit(this.ctx.logger, {
525
- schemaVersion: 1,
526
- kind: 'summary-locator',
527
- sessionId: String(session.id),
528
- profile: policy.profile,
529
- checkpointSeq,
530
- summarySeq: trace.summarySeq,
531
- locatorChars: codePointLength(located.text),
532
- spillFiles: located.spillFiles,
533
- touchedFiles: located.touchedFiles,
534
- })
535
- }
536
-
537
- /**
538
- * TokenPilot-inspired E1: sample oversized historical reads and ask the
539
- * auxiliary estimator whether their file state is still likely to be
540
- * referenced. Fire-and-forget: never awaited on the pruning chain, failures
541
- * back off exponentially per Session, verdicts only extend the rule-only
542
- * superseded classification.
543
- */
544
- private async postflightEstimatorPass(session: Session, signal: AbortSignal): Promise<void> {
545
- const policy = this.activePolicy(session)
546
- const presetOptions = policy?.presetOptions
547
- if (policy === undefined || presetOptions?.readState !== true) return
548
- const estimatorMode = presetOptions.estimator?.mode ?? ''
549
- if (estimatorMode === '') return
550
- const failures = this.state.estimatorFailures.get(session)
551
- if (isCoolingDown(failures, Date.now())) return
552
-
553
- const events = sessionEvents(session)
554
- const samples: EstimatorSample[] = []
555
- const now = Date.now()
556
- for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
557
- if (samples.length >= 3) break
558
- if (candidate.event.data.turn === undefined) continue
559
- const tokens = exactTokens(candidate.count)
560
- if (tokens === undefined || tokens <= policy.freshTriggerTokens) continue
561
- const path = toolCallPath(candidate.call.arguments)
562
- if (path === undefined) continue
563
- if (isSupersededRead(events, candidate.seq, path)) continue
564
- if (this.state.estimatorVerdicts.get(session)?.has(candidate.seq) === true) continue
565
- samples.push({ seq: candidate.seq, path, turn: candidate.event.data.turn })
566
- }
567
- if (samples.length === 0) return
568
-
569
- const estimator = new Estimator(this.ctx, this.activeSettings(session).presetOptions ?? {})
570
- const answer = await estimator.ask(buildEstimatorSystemPrompt(), buildEstimatorUserPrompt(samples), signal)
571
- const latencyMs = Date.now() - now
572
- const ok = answer !== undefined && signal.aborted === false
573
- let expired = 0
574
- if (ok && answer !== undefined) {
575
- let verdicts = this.state.estimatorVerdicts.get(session)
576
- if (verdicts === undefined) {
577
- verdicts = new Map()
578
- this.state.estimatorVerdicts.set(session, verdicts)
579
- }
580
- for (const verdict of parseEstimatorAnswer(answer)) {
581
- if (verdicts.has(verdict.seq)) continue
582
- verdicts.set(verdict.seq, verdict.expired)
583
- if (verdict.expired) expired += 1
584
- }
585
- } else {
586
- const next: EstimatorFailures = {
587
- failures: (failures?.failures ?? 0) + 1,
588
- cooldownUntil: Date.now() + backoffCooldownMs((failures?.failures ?? 0) + 1),
589
- }
590
- this.state.estimatorFailures.set(session, next)
591
- }
592
- emitCompressionAudit(this.ctx.logger, {
593
- schemaVersion: 1,
594
- kind: 'estimator-outcome',
595
- sessionId: String(session.id),
596
- profile: policy.profile,
597
- channel: estimatorMode === 'host' ? 'host' : 'direct',
598
- sampled: samples.length,
599
- expired,
600
- latencyMs,
601
- ok,
602
- })
603
- }
604
-
605
- private activePolicy(
606
- session: Session,
607
- contextWindowTokens?: number,
608
- stage: PruneStage = 'pressure',
609
- ): CompressionPolicy | undefined {
610
- const settings = this.activeSettings(session)
611
- try {
612
- const policy = resolvePolicy(
613
- this.state.config,
614
- settings.profile,
615
- settings.custom,
616
- {
617
- ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
618
- autoCompactThresholdPercent: settings.autoCompact.thresholdPercent,
619
- },
620
- )
621
- // Route changes must produce a fresh audit record even when the policy
622
- // object is unchanged, or the dedupe would hide a mid-session reroute.
623
- const route = routeAuditFact(session)
624
- const auditKey = JSON.stringify({
625
- policy,
626
- contextWindowTokens: contextWindowTokens ?? null,
627
- route: route ?? null,
628
- })
629
- // Deduplicate only CONSECUTIVE identical resolutions: a permanent set
630
- // would hide an A -> B -> A reroute's third record.
631
- if (this.state.policyResolutionAudits.get(session) !== auditKey) {
632
- this.state.policyResolutionAudits.set(session, auditKey)
633
- // Deployment config overrides win over the Auto Compact linkage, so a
634
- // standard profile whose History watermarks were replaced must not
635
- // audit itself as purely linkage-derived.
636
- const overriddenLinkedFields = ([
637
- 'historyTriggerTokens',
638
- 'historyKeepRecentTokens',
639
- 'historyMinReclaimTokens',
640
- ] as const).filter(key => this.state.config[key] !== undefined).length
641
- emitCompressionAudit(this.ctx.logger, {
642
- schemaVersion: 1,
643
- kind: 'policy-resolved',
644
- sessionId: String(session.id),
645
- policy,
646
- ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
647
- coordination: {
648
- thresholdPercent: settings.autoCompact.thresholdPercent,
649
- ...policy.autoCompactTokens === undefined ? {} : { autoCompactTokens: policy.autoCompactTokens },
650
- ...policy.microDeadlineTokens === undefined ? {} : { microDeadlineTokens: policy.microDeadlineTokens },
651
- paramSource: settings.profile === 'custom'
652
- ? 'custom-manual'
653
- : overriddenLinkedFields === 3 ? 'deployment-override'
654
- : overriddenLinkedFields > 0 ? 'mixed'
655
- : policy.microDeadlineTokens === undefined ? 'fixed-preset' : 'auto-compact-linked',
656
- },
657
- ...route === undefined ? {} : { route },
658
- ...route === undefined ? {} : tokenizerAuditFact(route),
659
- })
660
- }
661
- return policy
662
- } catch (error: unknown) {
663
- const reason = error instanceof Error ? error.message : String(error)
664
- this.auditFailure(session, stage, 'policy-resolution', error)
665
- this.warnOnce(
666
- session,
667
- `custom-policy:${settings.profile}:${reason}`,
668
- 'context-compression kept original tool results because the Custom policy is not effective: %s',
669
- reason,
670
- )
671
- return undefined
672
- }
673
- }
674
-
675
-
676
-
677
- private contextWindowForRequest(
678
- session: Session,
679
- ): number | undefined {
680
- const settings = this.activeSettings(session)
681
- // History linkage needs routed capacity for standard profiles, and the
682
- // Custom percentage policy needs it for context-percent documents. Off and
683
- // Native never link, and token-unit Custom stays manual.
684
- if (settings.profile === 'off' || settings.profile === 'native') return undefined
685
- if (settings.profile === 'custom' && settings.custom.unit !== 'context-percent') return undefined
686
- const config = session.requestHeader()?.config
687
- const routed = session.requestContext()
688
- if (config === undefined || config.provider.length === 0 || config.model.length === 0 || routed === undefined) {
689
- return undefined
690
- }
691
- if (routed.provider !== config.provider || routed.model !== config.model) {
692
- this.warnOnce(
693
- session,
694
- `custom-context-window-route:${config.provider}\0${config.model}`,
695
- 'context-compression kept the context-linked policy inactive because durable route capacity belongs to %s/%s, not %s/%s',
696
- routed.provider,
697
- routed.model,
698
- config.provider,
699
- config.model,
700
- )
701
- return undefined
702
- }
703
- if (!Number.isSafeInteger(routed.contextWindow) || routed.contextWindow === undefined || routed.contextWindow <= 0) {
704
- this.warnOnce(
705
- session,
706
- `custom-context-window-capacity:${config.provider}\0${config.model}`,
707
- 'context-compression kept the context-linked policy inactive because %s/%s has no positive durable context capacity',
708
- config.provider,
709
- config.model,
710
- )
711
- return undefined
712
- }
713
- return routed.contextWindow
714
- }
715
-
716
- private runRequestBoundary(
717
- session: Session,
718
- turn: number,
719
- step: number,
720
- signal: AbortSignal,
721
- ): void {
722
- const contextWindowTokens = this.contextWindowForRequest(session)
723
- if (signal.aborted) return
724
- const policy = this.activePolicy(session, contextWindowTokens, 'fresh')
725
- if (policy === undefined) return
726
- const capacity = contextWindowTokens === undefined ? {} : { contextWindowTokens }
727
- this.pruneSession(session, { stage: 'fresh', freshTurn: turn, freshStep: step, ...capacity })
728
- if (policy.historyMode !== 'disabled' || policy.tailTrim?.enabled === true) {
729
- this.pruneSession(session, { stage: 'pressure', ...capacity })
730
- }
731
- }
732
-
733
- /** Resolve historical-aging authority without accepting caller-supplied elevation. */
734
- private historyAllowed(session: Session, policy: CompressionPolicy, view: CompactionTokenView): boolean {
735
- switch (policy.historyMode) {
736
- case 'disabled':
737
- return false
738
- case 'routine':
739
- return true
740
- case 'capacity-pressure':
741
- return this.capacityPressureActive(session, view, policy)
742
- case 'adaptive':
743
- return false
744
- /* v8 ignore next -- closed-union exhaustiveness guard */
745
- default:
746
- return assertNever(policy.historyMode, 'history mode')
747
- }
748
- }
749
-
750
- /**
751
- * Match the compaction-basic pressure gate using public durable data. The
752
- * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
753
- * fixed 0.7 ratio once the standard-profile linkage resolved; without
754
- * linkage the 0.7 ratio is the documented fallback and reproduces the
755
- * previous behavior.
756
- */
757
- private capacityPressureActive(
758
- session: Session,
759
- view: CompactionTokenView,
760
- policy: CompressionPolicy,
761
- ): boolean {
762
- const deadline = policy.microDeadlineTokens
763
- if (deadline !== undefined) return view.totalTokens >= deadline
764
- const header = session.requestHeader()?.config
765
- const routed = session.requestContext()
766
- const contextWindow = routed?.contextWindow
767
- if (header === undefined || routed === undefined
768
- || routed.provider !== header.provider
769
- || routed.model !== header.model
770
- || contextWindow === undefined
771
- || !Number.isSafeInteger(contextWindow)
772
- || contextWindow <= 0) return false
773
- return view.totalTokens >= Math.floor(contextWindow * CAPACITY_PRESSURE_RATIO)
774
- }
775
-
776
- /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
777
- private logAdaptivePostflight(session: Session, usage: ObservedPromptUsage): void {
778
- const attemptId = String(usage.attemptId)
779
- if (this.state.postflightDiagnostics.get(session) === attemptId) return
780
- this.state.postflightDiagnostics.set(session, attemptId)
781
-
782
- const key = usage.key
783
- let priceRecord: Readonly<Record<string, unknown>> | undefined
784
- let cost: ReturnType<typeof priceOfficialDeepSeekUsage> | { readonly kind: 'unpriced'; readonly reason: string }
785
- if (key === undefined) {
786
- cost = { kind: 'unpriced', reason: 'measurement key unavailable' }
787
- } else if (usage.responseModelId !== key.modelId) {
788
- cost = { kind: 'unpriced', reason: 'response model mismatch or unavailable' }
789
- } else if (usage.observedOutputTokens === undefined) {
790
- cost = { kind: 'unpriced', reason: 'output token count unavailable' }
791
- } else if (usage.cacheStatus !== 'complete'
792
- || usage.cacheReadTokens === undefined
793
- || usage.cacheMissTokens === undefined) {
794
- cost = { kind: 'unpriced', reason: 'complete cache split unavailable' }
795
- } else {
796
- const startedAt = new Date(usage.startedAtMs)
797
- const completedAt = new Date(usage.completedAtMs)
798
- const resolution = resolveOfficialDeepSeekPrice({
799
- provider: key.provider,
800
- baseUrlClass: key.baseUrlClass,
801
- apiRoute: key.apiRoute,
802
- modelId: key.modelId,
803
- currency: 'USD',
804
- at: startedAt,
805
- })
806
- if (resolution.kind === 'priced') {
807
- priceRecord = {
808
- catalogVersion: resolution.record.catalogVersion,
809
- checkedAt: resolution.record.checkedAt,
810
- sourceUrl: resolution.record.sourceUrl,
811
- currency: resolution.record.currency,
812
- modelId: resolution.record.modelId,
813
- apiRoute: resolution.record.apiRoute,
814
- startBand: resolution.record.band,
815
- }
816
- }
817
- cost = priceOfficialDeepSeekUsage({
818
- provider: key.provider,
819
- baseUrlClass: key.baseUrlClass,
820
- apiRoute: key.apiRoute,
821
- modelId: key.modelId,
822
- currency: 'USD',
823
- startedAt,
824
- completedAt,
825
- usage: {
826
- cacheReadTokens: usage.cacheReadTokens,
827
- cacheMissTokens: usage.cacheMissTokens,
828
- outputTokens: usage.observedOutputTokens,
829
- },
830
- })
831
- }
832
-
833
- this.ctx.logger.debug(`context-compression adaptive postflight ${JSON.stringify({
834
- sessionId: String(session.id),
835
- providerRequestOrdinal: Number(usage.providerRequestOrdinal),
836
- attemptId,
837
- startedAtMs: usage.startedAtMs,
838
- completedAtMs: usage.completedAtMs,
839
- measurementKind: usage.measurement.kind,
840
- catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
841
- ...(priceRecord === undefined ? {} : { priceRecord }),
842
- usage: {
843
- promptTokens: usage.observedPromptTokens,
844
- ...(usage.observedOutputTokens === undefined ? {} : { outputTokens: usage.observedOutputTokens }),
845
- cacheStatus: usage.cacheStatus ?? 'unknown',
846
- ...(usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens }),
847
- ...(usage.cacheMissTokens === undefined ? {} : { cacheMissTokens: usage.cacheMissTokens }),
848
- },
849
- cost,
850
- })}`)
851
- }
852
-
853
- /** Decide one already-planned History batch from adjacent request-level facts only. */
854
- private adaptiveHistoryAllowed(
855
- session: Session,
856
- view: CompactionTokenView,
857
- plans: readonly PlannedReplacement[],
858
- capacityPressure: boolean,
859
- ): boolean {
860
- const log = (
861
- allowHistory: boolean,
862
- reason: string,
863
- detail: Readonly<Record<string, unknown>> = {},
864
- ): boolean => {
865
- this.ctx.logger.debug(`context-compression adaptive ${JSON.stringify({
866
- sessionId: String(session.id),
867
- allowHistory,
868
- reason,
869
- catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
870
- ...detail,
871
- })}`)
872
- return allowHistory
873
- }
874
- const usage = view.lastCompletedUsage
875
- if (usage !== undefined) this.logAdaptivePostflight(session, usage)
876
- if (plans.length === 0) return false
877
- if (capacityPressure) return log(true, 'capacity-override')
878
-
879
- const currentKey = view.latestEnvelopeKey
880
- if (usage === undefined) return log(false, 'usage-unavailable')
881
- if (usage.key === undefined || currentKey === undefined) {
882
- return log(false, 'measurement-key-unavailable')
883
- }
884
- if (!sameProviderMeasurementKey(usage.key, currentKey)) {
885
- return log(false, 'measurement-key-mismatch')
886
- }
887
- if (usage.responseModelId !== usage.key.modelId) {
888
- return log(false, 'response-model-mismatch-or-unavailable')
889
- }
890
- if (usage.cacheStatus !== 'complete'
891
- || usage.cacheReadTokens === undefined
892
- || usage.cacheMissTokens === undefined) {
893
- return log(false, 'cache-split-incomplete')
894
- }
895
-
896
- const price = resolveOfficialDeepSeekPrice({
897
- provider: usage.key.provider,
898
- baseUrlClass: usage.key.baseUrlClass,
899
- apiRoute: usage.key.apiRoute,
900
- modelId: usage.key.modelId,
901
- currency: 'USD',
902
- at: new Date(),
903
- })
904
- if (price.kind === 'unpriced') return log(false, `adaptive-unknown-price:${price.reason}`)
905
-
906
- const exactReclaimedTokens = plans.reduce(
907
- (sum, plan) => sum + plan.tokensBefore - plan.tokensAfter,
908
- 0,
909
- )
910
- const earliestChangedSeq = Math.min(...plans.map(plan => plan.candidate.seq))
911
- const bounds = deriveAdaptiveTokenBounds({
912
- exactReclaimedTokens,
913
- earliestChangedSeq,
914
- previousPromptTokens: usage.observedPromptTokens,
915
- expectedTokenizerRevision: usage.key.tokenizerRevision,
916
- previousRequestMeasurement: usage.measurement,
917
- measuredNodes: view.measuredNodes,
918
- })
919
- const decision = decideConservativeAdaptive({
920
- capacityPressure: false,
921
- bounds,
922
- inputCacheHitRate: price.record.inputCacheHit,
923
- inputCacheMissRate: price.record.inputCacheMiss,
924
- observedCacheReadTokens: usage.cacheReadTokens,
925
- })
926
- return log(decision.allowHistory, decision.reason, {
927
- priceBand: price.record.band,
928
- observedPromptTokens: usage.observedPromptTokens,
929
- observedCacheReadTokens: usage.cacheReadTokens,
930
- bounds,
931
- ...'minimumRemovalValue' in decision
932
- ? { minimumRemovalValue: decision.minimumRemovalValue }
933
- : {},
934
- ...'maximumCacheLossPenalty' in decision
935
- ? { maximumCacheLossPenalty: decision.maximumCacheLossPenalty }
936
- : {},
937
- })
938
- }
939
-
940
- private decisions(session: Session): Set<number> {
941
- let decisions = this.state.firstExposure.get(session)
942
- if (decisions === undefined) {
943
- decisions = new Set()
944
- this.state.firstExposure.set(session, decisions)
945
- }
946
- return decisions
947
- }
948
-
949
- /**
950
- * TokenPilot-style skipReduction: recovery tool output is permanently exempt
951
- * from every reduction pass so retrieved content can never enter a
952
- * compress-restore-oscillation loop. A call-name match covers the built-in
953
- * recovery tool; the per-session set admits future recovery paths.
954
- */
955
- private isRecoveryExempt(session: Session, candidate: SnapshotCandidate): boolean {
956
- if (candidate.call.name === 'context_compression_retrieve') return true
957
- return this.state.recoveryExemptions.get(session)?.has(candidate.seq) ?? false
958
- }
959
-
960
- /** Register a result seq as permanently exempt from further reduction. */
961
- private grantRecoveryExemption(session: Session, seq: number): void {
962
- let exemptions = this.state.recoveryExemptions.get(session)
963
- if (exemptions === undefined) {
964
- exemptions = new Set()
965
- this.state.recoveryExemptions.set(session, exemptions)
966
- }
967
- exemptions.add(seq)
968
- }
969
-
970
- private decideFreshStep(
971
- session: Session,
972
- options: PruneSessionOptions,
973
- policy: CompressionPolicy,
974
- view: CompactionTokenView,
975
- ): PruneResult {
976
- if (options.freshTurn === undefined || options.freshStep === undefined) {
977
- this.auditComponent(session, policy, 'fresh', 'fresh',
978
- policy.freshEnabled ? 'skipped' : 'disabled',
979
- policy.freshEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
980
- this.auditComponent(session, policy, 'aggregate', 'fresh',
981
- policy.aggregateEnabled ? 'skipped' : 'disabled',
982
- policy.aggregateEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
983
- return emptyResult()
984
- }
985
- const decisions = this.decisions(session)
986
- const candidates = this.snapshot(session, view).filter(candidate =>
987
- typeof candidate.event.surfaceOp !== 'object'
988
- && candidate.event.data.turn === options.freshTurn
989
- && candidate.event.data.step === options.freshStep
990
- && !decisions.has(candidate.seq))
991
- if (candidates.length === 0) {
992
- this.auditComponent(session, policy, 'fresh', 'fresh',
993
- policy.freshEnabled ? 'skipped' : 'disabled',
994
- policy.freshEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
995
- this.auditComponent(session, policy, 'aggregate', 'fresh',
996
- policy.aggregateEnabled ? 'skipped' : 'disabled',
997
- policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
998
- return emptyResult()
999
- }
1000
-
1001
- const plans = new Map<number, PlannedReplacement>()
1002
- let freshPlanned = 0
1003
- const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
1004
- const exactCandidateTokens = candidates.map(candidate => exactTokens(candidate.count))
1005
- const exactAvailable = exactCandidateTokens.every(tokens => tokens !== undefined)
1006
- const maxCandidateTokens = exactAvailable
1007
- ? Math.max(...exactCandidateTokens as number[])
1008
- : undefined
1009
- if (policy.freshEnabled) {
1010
- if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
1011
- && candidate.count.kind !== 'exact-tokenizer')) {
1012
- this.warnExactUnavailable(session, view, 'fresh')
1013
- }
1014
- for (const candidate of candidates) {
1015
- if (this.isRecoveryExempt(session, candidate)) continue
1016
- if (dedupeEnabled) {
1017
- const dedupePlan = this.planDedupe(candidate, session, policy, view)
1018
- if (dedupePlan !== null) {
1019
- plans.set(candidate.seq, dedupePlan)
1020
- continue
1021
- }
1022
- }
1023
- const plan = this.planFresh(candidate, session, policy, view)
1024
- if (plan !== null) {
1025
- plans.set(candidate.seq, plan)
1026
- freshPlanned += 1
1027
- }
1028
- }
1029
- }
1030
- let aggregateInputTokens: number | undefined
1031
- let aggregatePlanned = 0
1032
- if (policy.aggregateEnabled) {
1033
- const aggregateAvailable = exactAvailable
1034
- if (!aggregateAvailable) this.warnExactUnavailable(session, view, 'aggregate')
1035
- let total = aggregateAvailable
1036
- ? candidates.reduce((sum, candidate) => sum + (plans.get(candidate.seq)?.tokensAfter
1037
- ?? exactTokens(candidate.count) ?? 0), 0)
1038
- : 0
1039
- if (aggregateAvailable) aggregateInputTokens = total
1040
- if (aggregateAvailable && total > policy.aggregateTriggerTokens) {
1041
- const remaining = candidates
1042
- .filter(candidate => !this.isRecoveryExempt(session, candidate))
1043
- .sort((a, b) => Number(isError(a)) - Number(isError(b))
1044
- || (plans.get(b.seq)?.tokensAfter ?? exactTokens(b.count) ?? 0)
1045
- - (plans.get(a.seq)?.tokensAfter ?? exactTokens(a.count) ?? 0))
1046
- for (const candidate of remaining) {
1047
- const previous = plans.get(candidate.seq)
1048
- const plan = this.planAggregate(candidate, session, view)
1049
- const previousTokens = previous?.tokensAfter ?? exactTokens(candidate.count) ?? 0
1050
- if (plan === null || plan.tokensAfter >= previousTokens) continue
1051
- plans.set(candidate.seq, plan)
1052
- aggregatePlanned += 1
1053
- total -= previousTokens - plan.tokensAfter
1054
- if (total <= policy.aggregateTargetTokens) break
1055
- }
1056
- if (total > policy.aggregateTargetTokens) {
1057
- this.ctx.logger.warn(
1058
- 'context-compression fresh aggregate residual: %d tokens exceed target %d',
1059
- total,
1060
- policy.aggregateTargetTokens,
1061
- )
1062
- }
1063
- }
1064
- }
1065
-
1066
- const landed = this.landAll(session, candidates
1067
- .map(candidate => plans.get(candidate.seq))
1068
- .filter((plan): plan is PlannedReplacement => plan !== undefined))
1069
- const freshLanded = landed.some(entry => entry.stage === 'fresh'
1070
- && plans.get(entry.originalSeq)?.component === 'fresh')
1071
- const aggregateLanded = landed.some(entry => entry.stage === 'fresh'
1072
- && plans.get(entry.originalSeq)?.component === 'aggregate')
1073
- if (!freshLanded) {
1074
- this.auditComponent(session, policy, 'fresh', 'fresh',
1075
- policy.freshEnabled ? 'skipped' : 'disabled',
1076
- !policy.freshEnabled ? 'profile-policy'
1077
- : !exactAvailable ? 'exact-tokenizer-unavailable'
1078
- : (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? 'at-or-below-trigger'
1079
- : freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
1080
- : freshPlanned === 0 ? 'no-valid-reduction'
1081
- : 'recovery-tool-unavailable', {
1082
- measurementKind: exactAvailable ? 'exact-tokenizer' : 'unavailable',
1083
- ...(maxCandidateTokens === undefined ? {} : { currentTokens: maxCandidateTokens }),
1084
- triggerTokens: policy.freshTriggerTokens,
1085
- targetTokens: policy.freshTargetTokens,
1086
- })
1087
- }
1088
- if (!aggregateLanded) {
1089
- this.auditComponent(session, policy, 'aggregate', 'fresh',
1090
- policy.aggregateEnabled ? 'skipped' : 'disabled',
1091
- !policy.aggregateEnabled ? 'profile-policy'
1092
- : !exactAvailable ? 'exact-tokenizer-unavailable'
1093
- : (aggregateInputTokens ?? 0) <= policy.aggregateTriggerTokens ? 'at-or-below-trigger'
1094
- : aggregatePlanned === 0 ? 'no-valid-reduction'
1095
- : 'recovery-tool-unavailable', {
1096
- measurementKind: exactAvailable ? 'exact-tokenizer' : 'unavailable',
1097
- ...(aggregateInputTokens === undefined ? {} : { currentTokens: aggregateInputTokens }),
1098
- triggerTokens: policy.aggregateTriggerTokens,
1099
- targetTokens: policy.aggregateTargetTokens,
1100
- })
1101
- }
1102
- for (const candidate of candidates) decisions.add(candidate.seq)
1103
- return summarize(landed)
1104
- }
1105
-
1106
- private snapshot(session: Session, view: CompactionTokenView): SnapshotCandidate[] {
1107
- const events = sessionEvents(session)
1108
- const calls = new Map<string, ToolCallInfo>()
1109
- for (const event of events) {
1110
- if (event.type === 'tool/call') {
1111
- calls.set(event.data.callId, { name: event.data.name, arguments: event.data.arguments })
1112
- }
1113
- }
1114
- const candidates: SnapshotCandidate[] = []
1115
- const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1116
- const projectionPrices = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1117
- for (const seq of [...session.surface.nodes]) {
1118
- const event = events[seq]
1119
- if (event?.type !== 'tool/result') continue
1120
- const shadowedHeuristicTokenCount = projectionPrices.get(seq)
1121
- if (shadowedHeuristicTokenCount === undefined) {
1122
- throw new Error(`surface node ${String(seq)} is absent from the atomic legacy projection`)
1123
- }
1124
- const content = event.data.message.content[0].content
1125
- candidates.push({
1126
- seq,
1127
- event,
1128
- call: calls.get(event.data.message.source.callId) ?? { name: 'unknown', arguments: '{}' },
1129
- count: onlyTextBlocks(content) === null
1130
- ? unavailableCount(`surface node ${String(seq)} contains unsupported rich tool-result content`)
1131
- : measured.get(seq) ?? unavailableCount(`surface node ${String(seq)} is absent from the atomic token view`),
1132
- shadowedHeuristicTokenCount,
1133
- characterPressure: pressureCost(content),
1134
- })
1135
- }
1136
- return candidates
1137
- }
1138
-
1139
- private planNative(
1140
- candidate: SnapshotCandidate,
1141
- session: Session,
1142
- stage: PruneStage,
1143
- policy: CompressionPolicy,
1144
- view: CompactionTokenView,
1145
- ): PlannedReplacement | null {
1146
- if (this.isRecoveryExempt(session, candidate)) return null
1147
- const tokensBefore = exactTokens(candidate.count)
1148
- if (tokensBefore === undefined || tokensBefore <= policy.nativeTriggerTokens) return null
1149
- const result = candidate.event.data.message.content[0]
1150
- if (onlyTextBlocks(result.content) === null) return null
1151
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1152
- const marker = recoveryMarker(sourceRefFn(session, sourceSeq), 'tool result middle pruned')
1153
- let head = this.state.config.headChars
1154
- let tail = this.state.config.tailChars
1155
- for (let attempt = 0; attempt < 10; attempt += 1) {
1156
- const threshold = head + codePointLength(marker) + tail
1157
- const content = nativePruneContent(result.content, threshold, head, tail, marker)
1158
- if (content !== null) {
1159
- const plan = this.plan(
1160
- candidate,
1161
- content,
1162
- sourceSeq,
1163
- 'native-head-tail',
1164
- stage,
1165
- 'native-tool-result',
1166
- undefined,
1167
- view,
1168
- )
1169
- if (plan !== null && plan.tokensAfter <= policy.nativeTargetTokens) return plan
1170
- }
1171
- if (head === 0 && tail === 0) break
1172
- head = Math.floor(head / 2)
1173
- tail = Math.floor(tail / 2)
1174
- }
1175
- return this.planAggregate(
1176
- candidate,
1177
- session,
1178
- view,
1179
- 'native-whole-result',
1180
- stage,
1181
- policy.nativeTargetTokens,
1182
- 'native-tool-result',
1183
- )
1184
- }
1185
-
1186
- /**
1187
- * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
1188
- * oversized tool result with a pointer to its first occurrence. The first
1189
- * occurrence's hash is always recorded so later repeats can point at the
1190
- * append-only original event even after the surface copy is reduced.
1191
- */
1192
- private planDedupe(
1193
- candidate: SnapshotCandidate,
1194
- session: Session,
1195
- policy: CompressionPolicy,
1196
- view: CompactionTokenView,
1197
- ): PlannedReplacement | null {
1198
- if (typeof candidate.event.surfaceOp === 'object') return null
1199
- const result = candidate.event.data.message.content[0]
1200
- const text = flattenPlainText(result.content)
1201
- if (text === undefined) return null
1202
- const tokensBefore = exactTokens(candidate.count)
1203
- if (tokensBefore === undefined || tokensBefore <= policy.freshTriggerTokens) return null
1204
- let table = this.state.dedupeTables.get(session)
1205
- if (table === undefined) {
1206
- table = new DedupeTable()
1207
- this.state.dedupeTables.set(session, table)
1208
- }
1209
- const hash = dedupeHash(text, 'trim-eol')
1210
- const entry = table.get(hash)
1211
- if (entry !== undefined && entry.seq !== candidate.seq) {
1212
- const placeholder = dedupePlaceholder(entry, codePointLength(text))
1213
- const plan = this.plan(
1214
- candidate,
1215
- [{ type: 'text', text: placeholder }],
1216
- entry.seq,
1217
- 'dedupe-pointer',
1218
- 'fresh',
1219
- 'fresh',
1220
- undefined,
1221
- view,
1222
- { noNetSavingsGuard: true },
1223
- )
1224
- if (plan !== null) return plan
1225
- return null
1226
- }
1227
- if (entry === undefined) {
1228
- table.record(hash, {
1229
- seq: candidate.seq,
1230
- sourceRef: sourceRefFn(session, candidate.seq),
1231
- toolName: candidate.call.name,
1232
- originalChars: codePointLength(text),
1233
- })
1234
- }
1235
- return null
1236
- }
1237
-
1238
- private planFresh(
1239
- candidate: SnapshotCandidate,
1240
- session: Session,
1241
- policy: CompressionPolicy,
1242
- view: CompactionTokenView,
1243
- ): PlannedReplacement | null {
1244
- // A replace event already reflects one frozen first-exposure decision. The
1245
- // pre-step coordinate filter prevents previously-kept originals from ever
1246
- // being reconsidered after their first request.
1247
- if (typeof candidate.event.surfaceOp === 'object') return null
1248
- const result = candidate.event.data.message.content[0]
1249
- const tokensBefore = exactTokens(candidate.count)
1250
- if (tokensBefore === undefined || tokensBefore <= policy.freshTriggerTokens) return null
1251
- const sourceSeq = candidate.seq
1252
- const sourceRef = sourceRefFn(session, sourceSeq)
1253
- const textBlock = onlyTextBlock(result.content)
1254
- if (textBlock !== null) {
1255
- let budgetChars = Math.max(1, Math.floor(codePointLength(textBlock.text) * 0.75))
1256
- const codeSkeleton = this.activeSettings(session).codeSkeleton.enabled
1257
- for (let attempt = 0; attempt < 10; attempt += 1) {
1258
- const output = reduceFreshToolResult({
1259
- toolName: candidate.call.name,
1260
- argumentsText: candidate.call.arguments,
1261
- text: textBlock.text,
1262
- budgetChars,
1263
- sourceRef,
1264
- isError: result.isError === true || candidate.event.data.error !== undefined,
1265
- codeSkeleton,
1266
- })
1267
- if (output !== null) {
1268
- const plan = this.plan(
1269
- candidate,
1270
- [{ ...textBlock, text: output.text }],
1271
- sourceSeq,
1272
- output.reducer,
1273
- 'fresh',
1274
- 'fresh',
1275
- undefined,
1276
- view,
1277
- { noNetSavingsGuard: policy.presetOptions?.noNetSavingsGuard === true },
1278
- )
1279
- if (plan !== null && plan.tokensAfter <= policy.freshTargetTokens) return plan
1280
- }
1281
- if (budgetChars === 1) break
1282
- budgetChars = Math.max(1, Math.floor(budgetChars / 2))
1283
- }
1284
- }
1285
-
1286
- return this.planAggregate(
1287
- candidate,
1288
- session,
1289
- view,
1290
- 'fresh-whole-result',
1291
- 'fresh',
1292
- policy.freshTargetTokens,
1293
- 'fresh',
1294
- )
1295
- }
1296
-
1297
- private planAggregate(
1298
- candidate: SnapshotCandidate,
1299
- session: Session,
1300
- view: CompactionTokenView,
1301
- reducer = 'fresh-step-aggregate',
1302
- stage: PruneStage = 'fresh',
1303
- targetTokens?: number,
1304
- component: CompressionAuditComponent = 'aggregate',
1305
- historyMode?: HistoryMode,
1306
- ): PlannedReplacement | null {
1307
- if (isError(candidate)) {
1308
- return this.planErrorEvidence(
1309
- candidate,
1310
- session,
1311
- view,
1312
- stage,
1313
- targetTokens,
1314
- component,
1315
- historyMode,
1316
- )
1317
- }
1318
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1319
- const sourceRef = sourceRefFn(session, sourceSeq)
1320
- const text = [
1321
- '[Tool result reduced to satisfy the completed-step aggregate budget]',
1322
- `tool: ${candidate.call.name}`,
1323
- `source: ${sourceRef}`,
1324
- 'Use context_compression_retrieve with this source if the omitted evidence is necessary.',
1325
- ].join('\n')
1326
- const plan = this.plan(
1327
- candidate,
1328
- [{ type: 'text', text }],
1329
- sourceSeq,
1330
- reducer,
1331
- stage,
1332
- component,
1333
- historyMode,
1334
- view,
1335
- )
1336
- return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1337
- ? plan
1338
- : null
1339
- }
1340
-
1341
- /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
1342
- private planErrorEvidence(
1343
- candidate: SnapshotCandidate,
1344
- session: Session,
1345
- view: CompactionTokenView,
1346
- stage: PruneStage,
1347
- targetTokens?: number,
1348
- component: CompressionAuditComponent = 'aggregate',
1349
- historyMode?: HistoryMode,
1350
- ): PlannedReplacement | null {
1351
- if (!isError(candidate)) return null
1352
- const result = candidate.event.data.message.content[0]
1353
- const blocks = onlyTextBlocks(result.content)
1354
- if (blocks === null) return null
1355
- const text = blocks.map(block => block.text).join('\n')
1356
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1357
- const sourceRef = sourceRefFn(session, sourceSeq)
1358
- const output = historicalPlaceholder({
1359
- toolName: candidate.call.name,
1360
- sourceRef,
1361
- charsBefore: codePointLength(text),
1362
- isError: true,
1363
- text,
1364
- compact: false,
1365
- })
1366
- const input = {
1367
- toolName: candidate.call.name,
1368
- argumentsText: candidate.call.arguments,
1369
- text,
1370
- budgetChars: 1_200,
1371
- sourceRef,
1372
- isError: true,
1373
- }
1374
- if (!verifyReduction(input, output)) return null
1375
- const plan = this.plan(
1376
- candidate,
1377
- [{ type: 'text', text: output.text }],
1378
- sourceSeq,
1379
- 'error-evidence-placeholder',
1380
- stage,
1381
- component,
1382
- historyMode,
1383
- view,
1384
- )
1385
- return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1386
- ? plan
1387
- : null
1388
- }
1389
-
1390
- private planHistoricalAging(
1391
- session: Session,
1392
- policy: CompressionPolicy,
1393
- view: CompactionTokenView,
1394
- ): HistoryPlanOutcome {
1395
- const candidates = this.snapshot(session, view)
1396
- const events = sessionEvents(session)
1397
- const exact: number[] = []
1398
- for (const candidate of candidates) {
1399
- const tokens = exactTokens(candidate.count)
1400
- if (tokens === undefined) {
1401
- this.warnExactUnavailable(session, view, 'history')
1402
- return { kind: 'exact-tokenizer-unavailable' }
1403
- }
1404
- exact.push(tokens)
1405
- }
1406
- const total = exact.reduce((sum, tokens) => sum + tokens, 0)
1407
- const trigger = policy.historyTriggerTokens
1408
- // Full-request last chance: ordinary prose, images, prompts, or schemas can
1409
- // push the complete request past the Auto Compact deadline before the tool
1410
- // results alone cross the profile trigger.
1411
- const deadline = policy.microDeadlineTokens
1412
- const lastChance = deadline !== undefined && view.totalTokens >= deadline
1413
- if (total <= trigger && !lastChance) return { kind: 'below-profile-trigger' }
1414
-
1415
- const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
1416
- const isUnsafe = (candidate: SnapshotCandidate): boolean => {
1417
- if (this.isRecoveryExempt(session, candidate)) return true
1418
- const result = candidate.event.data.message.content[0]
1419
- const block = onlyTextBlock(result.content)
1420
- return block?.text.includes('[Old tool result content cleared from active context]') === true
1421
- }
1422
- // Distinguish "nothing safe to touch" (recovery tool output or already
1423
- // cleared) from "everything left is inside the protected working set":
1424
- // both skip, but they are different operational facts.
1425
- const safe = candidates.filter(candidate => !isUnsafe(candidate))
1426
- const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1427
- if (eligible.length === 0) {
1428
- return safe.length === 0
1429
- ? { kind: 'no-safe-candidates' }
1430
- : { kind: 'protected-working-set' }
1431
- }
1432
- const planned: PlannedReplacement[] = []
1433
- let reclaim = 0
1434
- // With a frozen Auto Compact deadline, microTarget = max(0, D - M) and one
1435
- // batch must justify its cache break by pulling the complete request back
1436
- // below the deadline. Without linkage (Custom manual, or no resolved
1437
- // routed capacity) the loop keeps its traditional target and the batch
1438
- // still commits once it reaches the minimum reclaim.
1439
- const microTarget = deadline === undefined ? undefined : Math.max(0, deadline - policy.historyMinReclaimTokens)
1440
- const required = Math.max(
1441
- policy.historyMinReclaimTokens,
1442
- total - trigger,
1443
- ...(microTarget === undefined ? [] : [view.totalTokens - microTarget]),
1444
- )
1445
- const batchTarget = microTarget === undefined
1446
- ? policy.historyMinReclaimTokens
1447
- : required
1448
- for (const candidate of eligible) {
1449
- const result = candidate.event.data.message.content[0]
1450
- const block = onlyTextBlock(result.content)
1451
- // TokenPilot-inspired R2: a read output whose file was later mutated is
1452
- // superseded — its text can no longer match the file — so it takes the
1453
- // small whole-result placeholder before the ordinary reducer runs.
1454
- if (policy.presetOptions?.readState === true && block !== null) {
1455
- const readPath = toolCallPath(candidate.call.arguments)
1456
- const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
1457
- if (readPath !== undefined
1458
- && (isSupersededRead(events, candidate.seq, readPath) || estimatorExpired)) {
1459
- const plan = this.planAggregate(
1460
- candidate,
1461
- session,
1462
- view,
1463
- 'superseded-read-whole-result',
1464
- 'pressure',
1465
- undefined,
1466
- 'history',
1467
- policy.historyMode,
1468
- )
1469
- if (plan === null) continue
1470
- planned.push(plan)
1471
- reclaim += plan.tokensBefore - plan.tokensAfter
1472
- if (reclaim >= required) break
1473
- continue
1474
- }
1475
- }
1476
- const sourceSeq = rootToolResultSeq(session, candidate.seq)
1477
- if (block === null) {
1478
- const plan = this.planAggregate(
1479
- candidate,
1480
- session,
1481
- view,
1482
- 'historical-rich-whole-result',
1483
- 'pressure',
1484
- undefined,
1485
- 'history',
1486
- policy.historyMode,
1487
- )
1488
- if (plan === null) continue
1489
- planned.push(plan)
1490
- reclaim += plan.tokensBefore - plan.tokensAfter
1491
- if (reclaim >= required) break
1492
- continue
1493
- }
1494
- const output = historicalPlaceholder({
1495
- toolName: candidate.call.name,
1496
- sourceRef: sourceRefFn(session, sourceSeq),
1497
- charsBefore: codePointLength(block.text),
1498
- isError: result.isError === true || candidate.event.data.error !== undefined,
1499
- text: block.text,
1500
- compact: false,
1501
- })
1502
- const verifyInput = {
1503
- toolName: candidate.call.name,
1504
- argumentsText: candidate.call.arguments,
1505
- text: block.text,
1506
- budgetChars: 1_200,
1507
- sourceRef: sourceRefFn(session, sourceSeq),
1508
- isError: result.isError === true || candidate.event.data.error !== undefined,
1509
- }
1510
- if (!verifyReduction(verifyInput, output)) continue
1511
- // TokenPilot-inspired R3: when read-state semantics are on, append an
1512
- // error/warn/info census of the omitted lines so the model keeps
1513
- // meta-knowledge about what was dropped.
1514
- let replacementText = output.text
1515
- if (policy.presetOptions?.readState === true) {
1516
- const omitted = countOmittedLines(block.text, output.text)
1517
- const census = omitted === undefined ? undefined : clusterOmittedLines(block.text, omitted)
1518
- if (census !== undefined) replacementText = `${output.text}
1519
- [... ${census} ...]`
1520
- }
1521
- const plan = this.plan(
1522
- candidate,
1523
- [{ ...block, text: replacementText }],
1524
- sourceSeq,
1525
- output.reducer,
1526
- 'pressure',
1527
- 'history',
1528
- policy.historyMode,
1529
- view,
1530
- )
1531
- if (plan === null) continue
1532
- planned.push(plan)
1533
- reclaim += plan.tokensBefore - plan.tokensAfter
1534
- if (reclaim >= required) break
1535
- }
1536
- // Linked batches must reach the deadline target; unlinked batches keep
1537
- // the traditional minimum-reclaim commit threshold.
1538
- if (reclaim >= batchTarget && planned.length > 0) return historyOutcome(planned)
1539
- return lastChance
1540
- ? { kind: 'cannot-reach-deadline-target', reclaim, required }
1541
- : { kind: 'insufficient-reclaim', reclaim, required }
1542
- }
1543
-
1544
- private protectedHistoryResultSeqs(
1545
- session: Session,
1546
- policy: CompressionPolicy,
1547
- view: CompactionTokenView,
1548
- ): Set<number> | null {
1549
- const candidates = this.snapshot(session, view)
1550
- if (candidates.some(candidate => exactTokens(candidate.count) === undefined)) return null
1551
- return this.protectedHistoryCandidateSeqs(candidates, policy)
1552
- }
1553
-
1554
- /** Select the newest completed tool calls and token tail for History-derived stages. */
1555
- private protectedHistoryCandidateSeqs(
1556
- candidates: readonly SnapshotCandidate[],
1557
- policy: CompressionPolicy,
1558
- ): Set<number> {
1559
- const protectedSeqs = new Set<number>()
1560
- for (let index = candidates.length - 1;
1561
- index >= 0 && candidates.length - index <= policy.historyKeepRecentToolCalls;
1562
- index--) {
1563
- const candidate = candidates[index]
1564
- if (candidate !== undefined) protectedSeqs.add(candidate.seq)
1565
- }
1566
- let recentTokens = 0
1567
- for (let index = candidates.length - 1;
1568
- index >= 0 && recentTokens < policy.historyKeepRecentTokens;
1569
- index--) {
1570
- const candidate = candidates[index]
1571
- if (candidate === undefined) continue
1572
- protectedSeqs.add(candidate.seq)
1573
- recentTokens += exactTokens(candidate.count) ?? 0
1574
- }
1575
- return protectedSeqs
1576
- }
1577
-
1578
- /** Atomically replace at most one oldest safe completed tool-call group. */
1579
- private landOldestTailTrimGroup(
1580
- session: Session,
1581
- policy: CompressionPolicy,
1582
- view: CompactionTokenView,
1583
- ): void {
1584
- const tailTrim = policy.tailTrim
1585
- if (tailTrim?.enabled !== true) return
1586
- const events = sessionEvents(session)
1587
- if (view.currentSurface.kind !== 'exact-tokenizer'
1588
- || view.currentSurface.tokens <= tailTrim.triggerTokens) {
1589
- if (view.currentSurface.kind !== 'exact-tokenizer') this.warnExactUnavailable(session, view, 'tailtrim')
1590
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1591
- view.currentSurface.kind !== 'exact-tokenizer'
1592
- ? 'exact-tokenizer-unavailable' : 'at-or-below-trigger', {
1593
- measurementKind: view.currentSurface.kind,
1594
- ...(view.currentSurface.kind === 'exact-tokenizer'
1595
- ? { currentTokens: view.currentSurface.tokens }
1596
- : {}),
1597
- triggerTokens: tailTrim.triggerTokens,
1598
- })
1599
- return
1600
- }
1601
- const surfaceCount = view.currentSurface
1602
- if (!this.hasRecoveryTool(session)) {
1603
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1604
- 'recovery-tool-unavailable', {
1605
- measurementKind: 'exact-tokenizer',
1606
- currentTokens: surfaceCount.tokens,
1607
- triggerTokens: tailTrim.triggerTokens,
1608
- })
1609
- return
1610
- }
1611
- if (!hasOpenTurn(session)) {
1612
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1613
- 'no-open-turn', {
1614
- measurementKind: 'exact-tokenizer',
1615
- currentTokens: surfaceCount.tokens,
1616
- triggerTokens: tailTrim.triggerTokens,
1617
- })
1618
- return
1619
- }
1620
- const protectedResults = this.protectedHistoryResultSeqs(session, policy, view)
1621
- if (protectedResults === null) {
1622
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1623
- 'exact-tokenizer-unavailable-in-protected-set', {
1624
- measurementKind: 'unavailable',
1625
- currentTokens: surfaceCount.tokens,
1626
- triggerTokens: tailTrim.triggerTokens,
1627
- })
1628
- return
1629
- }
1630
- const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1631
- const heuristic = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1632
- const completedTurns = new Set<number>()
1633
- const completedSteps = new Set<string>()
1634
- for (const event of events) {
1635
- if (event.type === 'turn/end') completedTurns.add(event.data.turn)
1636
- else if (event.type === 'step/end') completedSteps.add(`${String(event.data.turn)}:${String(event.data.step)}`)
1637
- }
1638
- const firstCompletedSurfaceTurn = session.surface.nodes
1639
- .map(seq => events[seq])
1640
- .filter((event): event is SessionEvent<'assistant/message'> | SessionEvent<'tool/result'> =>
1641
- (event?.type === 'assistant/message' || event?.type === 'tool/result')
1642
- && completedTurns.has(event.data.turn))
1643
- .reduce<number | undefined>(
1644
- (first, event) => first === undefined ? event.data.turn : Math.min(first, event.data.turn),
1645
- undefined,
1646
- )
1647
- const nodes = [...session.surface.nodes]
1648
- for (let index = 0; index < nodes.length; index++) {
1649
- const assistantSeq = nodes[index]
1650
- if (assistantSeq === undefined) continue
1651
- const assistant = events[assistantSeq]
1652
- if (assistant?.type !== 'assistant/message'
1653
- || assistant.data.interrupted === true
1654
- || assistant.data.message.content.length === 0
1655
- || assistant.data.message.content.some(block => block.type !== 'tool-call')
1656
- || assistant.data.turn === firstCompletedSurfaceTurn
1657
- || !completedTurns.has(assistant.data.turn)
1658
- || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue
1659
- const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
1660
- if (calls.some(call => call.name === 'context_compression_retrieve')) continue
1661
- const callIds = calls.map(call => String(call.id))
1662
- if (new Set(callIds).size !== callIds.length) continue
1663
- const resultSeqs = nodes.slice(index + 1, index + 1 + calls.length)
1664
- if (resultSeqs.length !== calls.length || resultSeqs.some(seq => protectedResults.has(seq))) continue
1665
- const results = resultSeqs.map(seq => events[seq])
1666
- if (results.some((event): boolean => {
1667
- if (event?.type !== 'tool/result'
1668
- || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
1669
- || event.data.error !== undefined) return true
1670
- const block = event.data.message.content[0]
1671
- if (block.isError === true) return true
1672
- // Images and other rich inner blocks stay fail-open: a TailTrim stub
1673
- // would silently delete them from the active context.
1674
- return block.content.some(contentBlock => contentBlock.type !== 'text')
1675
- })) continue
1676
- const next = events[nodes[index + 1 + calls.length] ?? -1]
1677
- if (next?.type === 'tool/result'
1678
- && next.data.turn === assistant.data.turn
1679
- && next.data.step === assistant.data.step) continue
1680
- const resultIds = results.map(event => event?.type === 'tool/result'
1681
- ? String(event.data.message.source.callId) : '')
1682
- if (new Set(resultIds).size !== resultIds.length
1683
- || resultIds.some((id, resultIndex) => id !== callIds[resultIndex])) continue
1684
- const shadowedSeqs = [assistantSeq, ...resultSeqs]
1685
- const roots = shadowedSeqs.map(seq => this.uniqueAppendRoot(session, seq))
1686
- if (roots.some(root => root === null)) continue
1687
- const sourceEventSeqs = roots as number[]
1688
- if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) continue
1689
- const counts = shadowedSeqs.map(seq => measured.get(seq))
1690
- if (counts.some(count => count?.kind !== 'exact-tokenizer')) continue
1691
- const exactCounts = counts as Extract<TokenCount, { kind: 'exact-tokenizer' }>[]
1692
- if (exactCounts.some(count => count.tokenizerId !== surfaceCount.tokenizerId
1693
- || count.tokenizerRevision !== surfaceCount.tokenizerRevision)) continue
1694
- const tokensBefore = exactCounts.reduce((sum, count) => sum + count.tokens, 0)
1695
- const manifestSeq = events.length
1696
- const ref = tailTrimRef(String(session.id), manifestSeq)
1697
- const stub = tailTrimStub(ref, calls.map(call => call.name), sourceEventSeqs)
1698
- if (stub === null) continue
1699
- const stubCount = countExactCanonicalTextFields(
1700
- [stub],
1701
- candidate => view.countCanonicalText(candidate),
1702
- 'TailTrim group stub',
1703
- )
1704
- if (stubCount.kind !== 'exact-tokenizer'
1705
- || stubCount.tokenizerId !== surfaceCount.tokenizerId
1706
- || stubCount.tokenizerRevision !== surfaceCount.tokenizerRevision
1707
- || stubCount.tokens <= 0
1708
- || tokensBefore - stubCount.tokens < policy.historyMinReclaimTokens) continue
1709
- const heuristicTokens = shadowedSeqs.reduce((sum, seq) => sum + (heuristic.get(seq) ?? 0), 0)
1710
- const range = { start: assistantSeq, end: resultSeqs.at(-1) ?? assistantSeq }
1711
- if (!this.reserveTailTrimBoundaryAttempt(session)) {
1712
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1713
- 'already-attempted-at-request-boundary', {
1714
- measurementKind: 'exact-tokenizer',
1715
- currentTokens: surfaceCount.tokens,
1716
- triggerTokens: tailTrim.triggerTokens,
1717
- })
1718
- return
1719
- }
1720
- const manifest = session.append('compaction/prune', {
1721
- shadowedRange: range,
1722
- shadowedSeqs,
1723
- shadowedTokenCount: heuristicTokens,
1724
- })
1725
- let replacement: SessionEvent<'user/message'>
1726
- try {
1727
- replacement = session.append('user/message', tailTrimMessage(stub), {
1728
- surfaceOp: { op: 'replace', ...range },
1729
- sourceEventSeqs: [manifest.seq, ...shadowedSeqs],
1730
- })
1731
- } catch (error) {
1732
- this.auditPublicationFailure(
1733
- session,
1734
- 'pressure',
1735
- 'tail-trim',
1736
- manifest.seq,
1737
- error,
1738
- )
1739
- return
1740
- }
1741
- emitCompressionAudit(this.ctx.logger, {
1742
- schemaVersion: 1,
1743
- kind: 'rewrite',
1744
- sessionId: String(session.id),
1745
- profile: policy.profile,
1746
- component: 'tail-trim',
1747
- stage: 'pressure',
1748
- reducer: 'pair-preserving-tail-trim',
1749
- manifestEventType: 'compaction/prune',
1750
- manifestSeq: manifest.seq,
1751
- replacementSeq: replacement.seq,
1752
- sourceSeqs: sourceEventSeqs,
1753
- tokensBefore,
1754
- tokensAfter: stubCount.tokens,
1755
- tokensRemoved: tokensBefore - stubCount.tokens,
1756
- tokenizerId: stubCount.tokenizerId,
1757
- tokenizerRevision: stubCount.tokenizerRevision,
1758
- })
1759
- return
1760
- }
1761
- this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
1762
- 'no-safe-eligible-tool-group', {
1763
- measurementKind: 'exact-tokenizer',
1764
- currentTokens: surfaceCount.tokens,
1765
- triggerTokens: tailTrim.triggerTokens,
1766
- })
1767
- }
1768
-
1769
- private reserveTailTrimBoundaryAttempt(session: Session): boolean {
1770
- const boundary = this.state.activeRequestBoundaries.get(session)
1771
- if (boundary === undefined) return true
1772
- if (this.state.tailTrimBoundaryAttempts.get(session) === boundary) return false
1773
- this.state.tailTrimBoundaryAttempts.set(session, boundary)
1774
- return true
1775
- }
1776
-
1777
- private uniqueAppendRoot(session: Session, seq: number): number | null {
1778
- const events = sessionEvents(session)
1779
- const pending: Array<{ seq: number; depth: number }> = [{ seq, depth: 0 }]
1780
- const visited = new Set<number>()
1781
- const roots = new Set<number>()
1782
- while (pending.length > 0) {
1783
- const next = pending.pop()
1784
- if (next === undefined || next.depth > 64 || visited.has(next.seq)) continue
1785
- visited.add(next.seq)
1786
- if (visited.size > 64) return null
1787
- const event = events[next.seq]
1788
- if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
1789
- if (event.surfaceOp === 'append') roots.add(event.seq)
1790
- else if (typeof event.surfaceOp === 'object') {
1791
- const sources = event.sourceEventSeqs
1792
- if (sources === undefined || sources.length === 0) return null
1793
- for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
1794
- } else return null
1795
- if (roots.size > 1) return null
1796
- }
1797
- return roots.size === 1 ? [...roots][0] ?? null : null
1798
- }
1799
-
1800
- private plan(
1801
- candidate: SnapshotCandidate,
1802
- content: ContentBlock[],
1803
- sourceSeq: number,
1804
- reducer: string,
1805
- stage: PruneStage,
1806
- component: CompressionAuditComponent,
1807
- historyMode: HistoryMode | undefined,
1808
- view: CompactionTokenView,
1809
- options: { readonly noNetSavingsGuard?: boolean } = {},
1810
- ): PlannedReplacement | null {
1811
- const countBefore = candidate.count
1812
- if (countBefore.kind !== 'exact-tokenizer') return null
1813
- const countAfter = countToolContent(content, view)
1814
- if (countAfter.kind !== 'exact-tokenizer'
1815
- || countAfter.tokenizerId !== countBefore.tokenizerId
1816
- || countAfter.tokenizerRevision !== countBefore.tokenizerRevision) return null
1817
- const tokensBefore = countBefore.tokens
1818
- const tokensAfter = countAfter.tokens
1819
- if (tokensAfter <= 0 || tokensAfter >= tokensBefore) return null
1820
- // TokenPilot-style no-net-savings: even when the exact tokenizer reports a
1821
- // saving, a replacement whose text is not smaller than its original adds
1822
- // noise without reclaiming context. Text-level because the placeholder
1823
- // guidance lines (source refs, retrieval hints) must pay for themselves.
1824
- if (options.noNetSavingsGuard === true) {
1825
- const originalBlocks = onlyTextBlocks(candidate.event.data.message.content[0].content)
1826
- const replacementBlocks = onlyTextBlocks(content)
1827
- if (originalBlocks !== null && replacementBlocks !== null) {
1828
- const originalChars = originalBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
1829
- const replacementChars = replacementBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
1830
- if (replacementChars >= originalChars) return null
1831
- }
1832
- }
1833
- const charsBefore = candidate.characterPressure
1834
- const charsAfter = pressureCost(content)
1835
- return {
1836
- candidate,
1837
- content,
1838
- sourceSeq,
1839
- reducer,
1840
- stage,
1841
- component,
1842
- ...historyMode === undefined ? {} : { historyMode },
1843
- charsBefore,
1844
- charsAfter,
1845
- tokensBefore,
1846
- tokensAfter,
1847
- tokenizerId: countBefore.tokenizerId,
1848
- tokenizerRevision: countBefore.tokenizerRevision,
1849
- }
1850
- }
1851
-
1852
- private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
1853
- const { candidate } = plan
1854
- const result = candidate.event.data.message.content[0]
1855
- const message = freezeMessage<ToolResultMessage>({
1856
- ...candidate.event.data.message,
1857
- content: [{ ...result, content: plan.content }] as [typeof result],
1858
- })
1859
- const manifest = session.append('compaction/prune', {
1860
- shadowedRange: { start: candidate.seq, end: candidate.seq },
1861
- shadowedSeqs: [candidate.seq],
1862
- shadowedTokenCount: candidate.shadowedHeuristicTokenCount,
1863
- })
1864
- let replacement: SessionEvent<'tool/result'>
1865
- try {
1866
- replacement = session.append('tool/result', {
1867
- ...candidate.event.data,
1868
- message,
1869
- }, {
1870
- surfaceOp: { op: 'replace', start: candidate.seq, end: candidate.seq },
1871
- sourceEventSeqs: [candidate.seq],
1872
- })
1873
- } catch (error) {
1874
- this.auditPublicationFailure(
1875
- session,
1876
- plan.stage,
1877
- plan.component,
1878
- manifest.seq,
1879
- error,
1880
- )
1881
- return null
1882
- }
1883
- emitCompressionAudit(this.ctx.logger, {
1884
- schemaVersion: 1,
1885
- kind: 'rewrite',
1886
- sessionId: String(session.id),
1887
- profile: this.activeSettings(session).profile,
1888
- component: plan.component,
1889
- stage: plan.stage,
1890
- reducer: plan.reducer,
1891
- ...plan.historyMode === undefined ? {} : { historyMode: plan.historyMode },
1892
- manifestEventType: 'compaction/prune',
1893
- manifestSeq: manifest.seq,
1894
- replacementSeq: replacement.seq,
1895
- sourceSeqs: [plan.sourceSeq],
1896
- tokensBefore: plan.tokensBefore,
1897
- tokensAfter: plan.tokensAfter,
1898
- tokensRemoved: plan.tokensBefore - plan.tokensAfter,
1899
- tokenizerId: plan.tokenizerId,
1900
- tokenizerRevision: plan.tokenizerRevision,
1901
- })
1902
- return {
1903
- originalSeq: candidate.seq,
1904
- sourceSeq: plan.sourceSeq,
1905
- replacementSeq: replacement.seq,
1906
- callId: candidate.event.data.message.source.callId,
1907
- reducer: plan.reducer,
1908
- stage: plan.stage,
1909
- charsBefore: plan.charsBefore,
1910
- charsAfter: plan.charsAfter,
1911
- tokensBefore: plan.tokensBefore,
1912
- tokensAfter: plan.tokensAfter,
1913
- }
1914
- }
1915
-
1916
- private landAll(session: Session, plans: readonly PlannedReplacement[]): PrunedEntry[] {
1917
- if (plans.length === 0) return []
1918
- if (!this.hasRecoveryTool(session)) {
1919
- this.warnOnce(
1920
- session,
1921
- 'missing-context-retrieve',
1922
- 'context-compression kept original tool results because context_compression_retrieve is unavailable',
1923
- )
1924
- return []
1925
- }
1926
- if (!hasOpenTurn(session)) {
1927
- throw new Error('tool-result pruning cannot append a surface replacement outside any open turn')
1928
- }
1929
- const landed: PrunedEntry[] = []
1930
- for (const plan of plans) {
1931
- const entry = this.land(session, plan)
1932
- if (entry === null) break
1933
- landed.push(entry)
1934
- }
1935
- return landed
1936
- }
1937
-
1938
- private hasRecoveryTool(session: Session): boolean {
1939
- const tools = this.ctx.get('tools')
1940
- if (tools === undefined) return false
1941
- const agent = this.ctx.get('agents')?.get(session.id)
1942
- return tools.get('context_compression_retrieve', agent) !== undefined
1943
- }
1944
-
1945
- private auditHistoryEvaluation(
1946
- session: Session,
1947
- policy: CompressionPolicy,
1948
- view: CompactionTokenView,
1949
- allowed: boolean,
1950
- outcome: HistoryPlanOutcome,
1951
- ): void {
1952
- if (policy.historyMode === 'disabled') {
1953
- this.auditComponent(session, policy, 'history', 'pressure', 'disabled', 'profile-policy', {
1954
- historyMode: policy.historyMode,
1955
- })
1956
- return
1957
- }
1958
- if (!allowed && outcome.kind === 'planned') {
1959
- // The authority gate itself refused: below the frozen micro deadline
1960
- // (capacity-pressure) or the adaptive cost estimate rejected the batch.
1961
- const deadlineTrigger = policy.microDeadlineTokens
1962
- const capacity = deadlineTrigger === undefined ? session.requestContext()?.contextWindow : undefined
1963
- const capacityTrigger = deadlineTrigger !== undefined
1964
- ? deadlineTrigger
1965
- : Number.isSafeInteger(capacity) && capacity !== undefined && capacity > 0
1966
- ? Math.floor(capacity * CAPACITY_PRESSURE_RATIO)
1967
- : undefined
1968
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
1969
- policy.historyMode === 'capacity-pressure'
1970
- ? 'below-micro-deadline' : 'adaptive-cost-rejected', {
1971
- historyMode: policy.historyMode,
1972
- measurementKind: view.currentSurface.kind,
1973
- currentTokens: view.totalTokens,
1974
- ...(capacityTrigger === undefined ? {} : { triggerTokens: capacityTrigger }),
1975
- })
1976
- return
1977
- }
1978
- const deadline = policy.microDeadlineTokens
1979
- const lastChance = deadline !== undefined && view.totalTokens >= deadline
1980
- const detail = (extra: Readonly<Record<string, number>> = {}): Readonly<{
1981
- historyMode?: HistoryMode
1982
- measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'unavailable'
1983
- currentTokens?: number
1984
- triggerTokens?: number
1985
- reclaimTokens?: number
1986
- requiredTokens?: number
1987
- }> => ({
1988
- historyMode: policy.historyMode,
1989
- measurementKind: outcome.kind === 'exact-tokenizer-unavailable' ? 'unavailable' : 'exact-tokenizer',
1990
- currentTokens: view.totalTokens,
1991
- ...(outcome.kind === 'insufficient-reclaim' || outcome.kind === 'cannot-reach-deadline-target'
1992
- ? { reclaimTokens: outcome.reclaim, requiredTokens: outcome.required }
1993
- : {}),
1994
- ...extra,
1995
- })
1996
- switch (outcome.kind) {
1997
- case 'exact-tokenizer-unavailable':
1998
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
1999
- 'exact-tokenizer-unavailable', detail({ triggerTokens: policy.historyTriggerTokens }))
2000
- return
2001
- case 'below-profile-trigger':
2002
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2003
- 'below-profile-trigger', detail({ triggerTokens: policy.historyTriggerTokens }))
2004
- return
2005
- case 'no-safe-candidates':
2006
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2007
- 'no-safe-candidates', detail({ triggerTokens: policy.historyTriggerTokens }))
2008
- return
2009
- case 'protected-working-set':
2010
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2011
- 'protected-working-set', detail({ triggerTokens: policy.historyTriggerTokens }))
2012
- return
2013
- case 'insufficient-reclaim':
2014
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2015
- 'insufficient-reclaim', detail({ triggerTokens: policy.historyTriggerTokens }))
2016
- return
2017
- case 'cannot-reach-deadline-target':
2018
- // Planning engaged through the full-request last-chance gate; the
2019
- // routine trigger numbers below would misdescribe why nothing landed.
2020
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2021
- 'cannot-reach-deadline-target', detail(lastChance ? { triggerTokens: deadline } : {}))
2022
- return
2023
- case 'planned':
2024
- // A committed batch that landed nothing means the recovery tool was
2025
- // unavailable at landing time; a degenerate empty commit reads as an
2026
- // unreachable target instead.
2027
- this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2028
- outcome.plans.length > 0 ? 'recovery-tool-unavailable' : 'insufficient-reclaim',
2029
- detail({ triggerTokens: lastChance ? deadline : policy.historyTriggerTokens }))
2030
- return
2031
- /* v8 ignore next -- closed-union exhaustiveness guard */
2032
- default:
2033
- return assertNever(outcome, 'history plan outcome')
2034
- }
2035
- }
2036
-
2037
- private auditComponent(
2038
- session: Session,
2039
- policy: CompressionPolicy,
2040
- component: CompressionAuditComponent,
2041
- stage: PruneStage,
2042
- status: CompressionAuditEvaluationStatus,
2043
- reason: string,
2044
- detail: Readonly<{
2045
- historyMode?: HistoryMode
2046
- measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'unavailable'
2047
- currentTokens?: number
2048
- triggerTokens?: number
2049
- targetTokens?: number
2050
- reclaimTokens?: number
2051
- requiredTokens?: number
2052
- }> = {},
2053
- ): void {
2054
- emitCompressionAudit(this.ctx.logger, {
2055
- schemaVersion: 1,
2056
- kind: 'component-evaluation',
2057
- sessionId: String(session.id),
2058
- profile: policy.profile,
2059
- component,
2060
- stage,
2061
- status,
2062
- reason,
2063
- ...detail,
2064
- })
2065
- }
2066
-
2067
- private auditFailure(
2068
- session: Session,
2069
- stage: PruneStage,
2070
- operation:
2071
- | 'request-boundary'
2072
- | 'terminal-pass'
2073
- | 'policy-resolution'
2074
- | 'summary-locator'
2075
- | 'publication',
2076
- error: unknown,
2077
- ): void {
2078
- emitCompressionAudit(this.ctx.logger, {
2079
- schemaVersion: 1,
2080
- kind: 'failure',
2081
- sessionId: String(session.id),
2082
- stage,
2083
- operation,
2084
- errorName: error instanceof Error ? error.name : 'UnknownError',
2085
- errorMessage: error instanceof Error ? error.message : String(error),
2086
- })
2087
- }
2088
-
2089
- private auditPublicationFailure(
2090
- session: Session,
2091
- stage: PruneStage,
2092
- component: CompressionAuditComponent,
2093
- manifestSeq: number,
2094
- error: unknown,
2095
- ): void {
2096
- emitCompressionAudit(this.ctx.logger, {
2097
- schemaVersion: 1,
2098
- kind: 'failure',
2099
- sessionId: String(session.id),
2100
- stage,
2101
- operation: 'publication',
2102
- component,
2103
- manifestSeq,
2104
- errorName: error instanceof Error ? error.name : 'UnknownError',
2105
- errorMessage: 'surface replacement append failed after compaction/prune committed',
2106
- })
2107
- }
2108
-
2109
- private warnExactUnavailable(
2110
- session: Session,
2111
- view: CompactionTokenView,
2112
- gate: 'native' | 'fresh' | 'aggregate' | 'history' | 'tailtrim',
2113
- ): void {
2114
- const provider = view.providerRoute ?? 'unbound-provider'
2115
- const model = view.modelId ?? 'unbound-model'
2116
- this.warnOnce(
2117
- session,
2118
- `exact-tokenizer:${gate}:${provider}\0${model}`,
2119
- 'context-compression %s kept original tool results because exact tokenizer counts are unavailable for %s/%s',
2120
- gate,
2121
- provider,
2122
- model,
2123
- )
2124
- }
2125
-
2126
- private warnOnce(
2127
- session: Session,
2128
- key: string,
2129
- message: string,
2130
- ...args: unknown[]
2131
- ): void {
2132
- let warned = this.state.warnedFailures.get(session)
2133
- if (warned === undefined) {
2134
- warned = new Set()
2135
- this.state.warnedFailures.set(session, warned)
2136
- }
2137
- if (warned.has(key)) return
2138
- warned.add(key)
2139
- this.ctx.logger.warn(message, ...args)
2140
- }
2141
-
2142
- }
2143
-
2144
- 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