dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.3

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