dsh-context-compression-improved 0.7.0-beta.1 → 0.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.de.md +539 -0
  2. package/CHANGELOG.es.md +547 -0
  3. package/CHANGELOG.fr.md +534 -0
  4. package/CHANGELOG.it.md +536 -0
  5. package/CHANGELOG.ja.md +226 -220
  6. package/CHANGELOG.ko.md +220 -214
  7. package/CHANGELOG.md +372 -376
  8. package/CHANGELOG.ru.md +517 -0
  9. package/CHANGELOG.zh.md +204 -199
  10. package/README.de.md +98 -0
  11. package/README.es.md +98 -0
  12. package/README.fr.md +98 -0
  13. package/README.it.md +98 -0
  14. package/README.ja.md +85 -85
  15. package/README.ko.md +85 -85
  16. package/README.md +98 -97
  17. package/README.ru.md +98 -0
  18. package/README.zh.md +85 -86
  19. package/docs/installation.de.md +104 -0
  20. package/docs/installation.es.md +104 -0
  21. package/docs/installation.fr.md +104 -0
  22. package/docs/installation.it.md +104 -0
  23. package/docs/installation.ja.md +78 -78
  24. package/docs/installation.ko.md +78 -78
  25. package/docs/installation.md +103 -103
  26. package/docs/installation.ru.md +104 -0
  27. package/docs/installation.zh.md +100 -100
  28. package/eslint.config.js +30 -76
  29. package/package.json +69 -70
  30. package/packages/selector/dsh.plugin.json +2 -2
  31. package/packages/selector/lib/{intent-gate.js → advisor-state.js} +3 -91
  32. package/packages/selector/lib/client.js +736 -14
  33. package/packages/selector/lib/index.js +1 -92
  34. package/packages/selector/lib/profiles.d.ts +0 -9
  35. package/packages/selector/lib/pruner.d.ts +0 -59
  36. package/packages/selector/lib/pruner.js +7 -410
  37. package/packages/selector/lib/style.css +46 -46
  38. package/packages/selector/package.json +114 -114
  39. package/packages/selector/src/client/decode.ts +2 -6
  40. package/packages/selector/src/client/index.ts +244 -213
  41. package/packages/selector/src/client/locales/de.ts +98 -0
  42. package/packages/selector/src/client/locales/es.ts +98 -0
  43. package/packages/selector/src/client/locales/fr.ts +98 -0
  44. package/packages/selector/src/client/locales/it.ts +98 -0
  45. package/packages/selector/src/client/locales/ja.ts +98 -0
  46. package/packages/selector/src/client/locales/ko.ts +98 -0
  47. package/packages/selector/src/client/locales/ru.ts +98 -0
  48. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  49. package/packages/selector/src/index.ts +411 -418
  50. package/packages/selector/src/preset-overlay.ts +0 -3
  51. package/packages/selector/src/profiles.ts +10 -30
  52. package/packages/selector/src/pruner/content.ts +1 -1
  53. package/packages/selector/src/pruner/state.ts +0 -7
  54. package/packages/selector/src/pruner.ts +9 -253
  55. package/packages/selector/src/runtime/audit.ts +0 -17
  56. package/packages/selector/src/runtime/config.ts +11 -36
  57. package/packages/selector/src/runtime/reducers.ts +1 -1
  58. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +1 -46
  59. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -55
  60. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  61. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +1 -4
  62. package/packages/selector/src/runtime/types.ts +0 -12
  63. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -214
  64. package/packages/selector/tests/built/client-artifact.spec.ts +59 -61
  65. package/packages/selector/tests/code-skeleton.client.spec.ts +93 -94
  66. package/packages/selector/tests/custom-contract.client.spec.ts +222 -223
  67. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
  69. package/packages/selector/tests/preset-options-write.client.spec.ts +187 -188
  70. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
  71. package/packages/selector/tests/profiles.client.spec.tsx +434 -436
  72. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  73. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
  74. package/packages/selector/tests/runtime/audit.spec.ts +274 -275
  75. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  76. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  77. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2731 -2736
  78. package/packages/selector/tests/standing-generation.host.spec.ts +724 -704
  79. package/pnpm-workspace.yaml +66 -66
  80. package/scripts/packed-components-smoke.mjs +0 -2
  81. package/scripts/packed-install-e2e.mjs +5 -7
  82. package/scripts/verify-release.mjs +2 -3
  83. package/tests/TEST_INVENTORY.md +41 -41
  84. package/tsconfig.tests.json +1 -3
  85. package/vitest.config.ts +0 -14
  86. package/packages/selector/src/runtime/summary-command.ts +0 -133
  87. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  88. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  89. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  90. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  91. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  92. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  93. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
@@ -575,9 +575,6 @@ function installAgentPresetsDecoration(
575
575
  /** Capture callable methods and whether each was inherited or owned. */
576
576
  function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
577
577
  return (['resolve', 'mount', 'recompose', 'standingKeyFor'] as const).map((name) => {
578
- // Capture is detached by design: every apply/restore site re-binds via
579
- // Reflect.apply(..., presets, args), so this read never escapes its `this`.
580
- // eslint-disable-next-line @typescript-eslint/unbound-method
581
578
  const original = presets[name]
582
579
  if (typeof original !== 'function') {
583
580
  throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
@@ -108,14 +108,6 @@ export interface CodeSkeletonSettings {
108
108
  enabled: boolean
109
109
  }
110
110
 
111
- /**
112
- * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
113
- * runtime: independent of every profile, default off.
114
- */
115
- export interface IntentSummarySettings {
116
- enabled: boolean
117
- }
118
-
119
111
  /**
120
112
  * Decode the persisted codeSkeleton section with exactly the runtime schema's
121
113
  * strictness: absent means the lossless off default; present values must be a
@@ -127,17 +119,7 @@ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings
127
119
  if (!isPlainRecord(value)) return undefined
128
120
  const keys = Object.keys(value)
129
121
  if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
130
- const enabled = (value).enabled
131
- return typeof enabled === 'boolean' ? { enabled } : undefined
132
- }
133
-
134
- /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
135
- export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
136
- if (value === undefined) return { enabled: false }
137
- if (!isPlainRecord(value)) return undefined
138
- const keys = Object.keys(value)
139
- if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
140
- const enabled = (value).enabled
122
+ const enabled = (value as Record<string, unknown>).enabled
141
123
  return typeof enabled === 'boolean' ? { enabled } : undefined
142
124
  }
143
125
 
@@ -239,18 +221,18 @@ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettin
239
221
  if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
240
222
  if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
241
223
  if (value.readState !== undefined) decoded.readState = value.readState as boolean
242
- if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode
224
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
243
225
  if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
244
226
  if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
245
227
  if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
246
228
  if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
247
- if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs
248
- if (advisorMode !== undefined) decoded.advisorMode = advisorMode
249
- if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs
250
- if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns
251
- if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold
252
- if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit
253
- if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens
229
+ if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
230
+ if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
231
+ if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
232
+ if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
233
+ if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
234
+ if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
235
+ if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
254
236
  return decoded
255
237
  }
256
238
 
@@ -291,7 +273,7 @@ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings |
291
273
  if (!isPlainRecord(value)) return undefined
292
274
  const keys = Object.keys(value)
293
275
  if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
294
- const thresholdPercent = (value).thresholdPercent
276
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
295
277
  return isValidAutoCompactThresholdPercent(thresholdPercent)
296
278
  ? { thresholdPercent }
297
279
  : undefined
@@ -307,8 +289,6 @@ export interface ContextCompressionSettings {
307
289
  autoCompact: AutoCompactSettings
308
290
  /** Code-skeleton reducer gate captured independently of `profile`. */
309
291
  codeSkeleton: CodeSkeletonSettings
310
- /** Turn-tail intent-summary gate captured independently of `profile`. */
311
- intentSummary: IntentSummarySettings
312
292
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
313
293
  presetOptions?: PresetOptionsSettings
314
294
  }
@@ -156,7 +156,7 @@ function nativePruneContent(
156
156
  const headText = points.slice(0, headEnd).join('')
157
157
  const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
158
158
  ? marker(1 + newlinesBefore + headText.split('\n').length - 1)
159
- : intersectsRemoved && !markerInserted && typeof marker === 'string' ? marker : ''
159
+ : intersectsRemoved && !markerInserted ? marker : ''
160
160
  if (insertion !== '') markerInserted = true
161
161
  const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
162
162
  if (text !== '') pruned.push({ ...block, text })
@@ -9,7 +9,6 @@ import type { Session } from '@deepseek-ai/dsh-session'
9
9
  import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
10
10
  import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
11
11
  import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
12
- import type { PendingIntentFold } from '../runtime/tokenpilot/intent-fold.ts'
13
12
  import type {
14
13
  ContextCompressionSettings,
15
14
  ResolvedConfig,
@@ -48,10 +47,4 @@ export interface PrunerState {
48
47
  readonly estimatorRemainingTurns: WeakMap<Session, number>
49
48
  /** Per-session advisor side channel, constructed once with the advisor overrides. */
50
49
  readonly advisorChannels: WeakMap<Session, SideChannel>
51
- /** Staged intent fold awaiting the next pressure round (at most one per session). */
52
- readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
53
- /** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
54
- readonly intentFoldedSeqs: WeakMap<Session, Set<number>>
55
- /** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
56
- readonly intentBaselines: WeakMap<Session, number>
57
50
  }
@@ -91,12 +91,6 @@ import {
91
91
  runSessionAdvisorPass,
92
92
  } from './runtime/tokenpilot/advisor.ts'
93
93
  import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
94
- import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
95
- import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
96
- import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
97
- import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
98
- import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
99
- import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
100
94
 
101
95
  import {
102
96
  DedupeTable,
@@ -253,9 +247,6 @@ export class ToolResultPruner extends Service {
253
247
  turnClocks: new WeakMap(),
254
248
  estimatorRemainingTurns: new WeakMap(),
255
249
  advisorChannels: new WeakMap(),
256
- pendingIntentFolds: new WeakMap(),
257
- intentFoldedSeqs: new WeakMap(),
258
- intentBaselines: new WeakMap(),
259
250
  }
260
251
 
261
252
  ctx.on('session/event', (session, event) => {
@@ -325,9 +316,6 @@ export class ToolResultPruner extends Service {
325
316
  // summaries, scores, and decay figure never touch any decision path.
326
317
  // Strictly fire-and-forget, with its own backoff state.
327
318
  void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
328
- // Turn-tail intent summary: strictly fire-and-forget like the advisor;
329
- // the growth gate inside decides whether a summary call is even spent.
330
- void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
331
319
  })
332
320
  }
333
321
 
@@ -748,200 +736,6 @@ export class ToolResultPruner extends Service {
748
736
  }
749
737
  }
750
738
 
751
- // ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
752
-
753
- /**
754
- * Fire-and-forget postflight: evaluate the growth gate, and only when it
755
- * passes, select the consumed increment OUTSIDE the protected working set,
756
- * mask it to semantic-role records, and spend ONE summary-writer call. The
757
- * verdict stages as a pending fold that the NEXT pressure round lands via
758
- * the ordinary plan/apply machinery — the synchronous decision path never
759
- * waits on an LLM.
760
- */
761
- private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
762
- const started = Date.now()
763
- const sessionId = String(session.id)
764
- const policy = this.activePolicy(session)
765
- const settings = this.activeSettings(session)
766
- const intentEnabled = settings.intentSummary.enabled
767
- const override = getSummaryOverride(sessionId)
768
- observeIntentEnabled(sessionId, intentEnabled)
769
- if (policy === undefined) return
770
- if (this.state.pendingIntentFolds.has(session)) return
771
- const advisorState = getAdvisorState(session)
772
- if (advisorState.inFlight) return
773
- if (isCoolingDown(advisorState.failures, Date.now())) return
774
-
775
- const view = measureForCompaction(this.ctx, session)
776
- // The window is the Auto Compact linkage input: policy.autoCompactTokens
777
- // == floor(window * threshold/100); invert for the gate floor.
778
- const thresholdPercent = settings.autoCompact.thresholdPercent
779
- const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
780
- ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
781
- : undefined
782
- const gate = evaluateIntentGate({
783
- enabled: intentEnabled,
784
- override,
785
- liveTokens: view.totalTokens,
786
- contextWindow,
787
- baselineTokens: this.state.intentBaselines.get(session) ?? 0,
788
- })
789
- if (!gate.decision) return
790
-
791
- const settingsPreset = settings.presetOptions
792
- if (settingsPreset === undefined) return
793
- if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
794
- || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
795
- emitCompressionAudit(this.ctx.logger, {
796
- schemaVersion: 1,
797
- kind: 'intent-summary-outcome',
798
- sessionId,
799
- ok: false,
800
- reason: 'no-direct-endpoint',
801
- turnIndex: turn,
802
- latencyMs: Date.now() - started,
803
- })
804
- return
805
- }
806
-
807
- const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
808
- const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
809
- const range = computeIntentRange({
810
- candidates,
811
- protectedSeqs,
812
- foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
813
- maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
814
- })
815
- if (range.seqs.length === 0) return
816
-
817
- const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
818
- const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
819
- const errorLines = new Set<string>()
820
- for (const seq of range.seqs) {
821
- const candidate = bySeq.get(seq)
822
- if (candidate === undefined) continue
823
- const result = candidate.event.data.message
824
- const text = onlyTextBlock(result.content)?.text ?? ''
825
- const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
826
- records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
827
- for (const line of extractErrorLines(text)) errorLines.add(line)
828
- }
829
- if (records.length === 0) return
830
-
831
- const events = sessionEvents(session)
832
- const task = collectTaskSemantics(events)
833
- let channel = this.state.advisorChannels.get(session)
834
- if (channel === undefined) {
835
- channel = new SideChannel(this.ctx, settingsPreset, {
836
- mode: 'direct',
837
- timeoutMs: 30_000,
838
- maxTokens: 512,
839
- })
840
- this.state.advisorChannels.set(session, channel)
841
- }
842
-
843
- const answer = await channel.ask({
844
- system: buildIntentSummarySystemPrompt(),
845
- user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
846
- signal,
847
- })
848
- const summaryCallChars = answer?.length ?? 0
849
- const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
850
- if (parsed === undefined) {
851
- const failures = (advisorState.failures?.failures ?? 0) + 1
852
- advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
853
- emitCompressionAudit(this.ctx.logger, {
854
- schemaVersion: 1,
855
- kind: 'intent-summary-outcome',
856
- sessionId,
857
- ok: false,
858
- reason: answer === undefined ? 'ask-failed' : 'parse-failed',
859
- turnIndex: turn,
860
- foldedCount: records.length,
861
- summaryCallChars,
862
- latencyMs: Date.now() - started,
863
- })
864
- return
865
- }
866
- this.state.pendingIntentFolds.set(session, {
867
- createdAt: Date.now(),
868
- turn,
869
- startSeq: range.seqs[0]!,
870
- endSeq: range.seqs[range.seqs.length - 1]!,
871
- summary: parsed.summary,
872
- errorLines: [...errorLines],
873
- records,
874
- summaryCallChars,
875
- })
876
- emitCompressionAudit(this.ctx.logger, {
877
- schemaVersion: 1,
878
- kind: 'intent-summary-outcome',
879
- sessionId,
880
- ok: true,
881
- reason: 'staged',
882
- turnIndex: turn,
883
- foldedCount: records.length,
884
- summaryCallChars,
885
- latencyMs: Date.now() - started,
886
- })
887
- }
888
-
889
- /**
890
- * Convert a staged pending fold into per-candidate planned replacements
891
- * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
892
- * rich-content, or no longer exists keeps its original text. Returns
893
- * `undefined` when there is nothing (or no longer anything) to fold.
894
- */
895
- private applyPendingIntentFold(
896
- session: Session,
897
- policy: CompressionPolicy,
898
- view: CompactionTokenView,
899
- eligible: readonly SnapshotCandidate[],
900
- ): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
901
- const pending = this.state.pendingIntentFolds.get(session)
902
- if (pending === undefined) return undefined
903
- const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
904
- const foldable = pending.records
905
- .map(record => record.seq)
906
- .filter(seq => bySeq.has(seq))
907
- .sort((a, b) => a - b)
908
- if (foldable.length === 0) {
909
- this.state.pendingIntentFolds.delete(session)
910
- return undefined
911
- }
912
- const plans: PlannedReplacement[] = []
913
- const foldedSeqs = new Set<number>()
914
- let reclaim = 0
915
- let charsBefore = 0
916
- let charsAfter = 0
917
- for (const seq of foldable) {
918
- const candidate = bySeq.get(seq)!
919
- const result = candidate.event.data.message
920
- const block = onlyTextBlock(result.content)
921
- if (block === null) continue
922
- const text = renderIntentFoldBlock(pending, seq)
923
- const plan = this.plan(
924
- candidate,
925
- [{ ...block, text }],
926
- rootToolResultSeq(session, candidate.seq),
927
- 'intent-summary',
928
- 'pressure',
929
- 'history',
930
- policy.historyMode,
931
- view,
932
- )
933
- if (plan === null || plan.charsAfter >= plan.charsBefore) continue
934
- plans.push(plan)
935
- foldedSeqs.add(seq)
936
- reclaim += plan.charsBefore - plan.charsAfter
937
- charsBefore += plan.charsBefore
938
- charsAfter += plan.charsAfter
939
- }
940
- if (plans.length === 0) return undefined
941
- this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
942
- return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
943
- }
944
-
945
739
  // ─────────── Advisory benefit model (statistics & suggestions only) ───────────
946
740
 
947
741
  /**
@@ -1564,7 +1358,7 @@ export class ToolResultPruner extends Service {
1564
1358
  ): PlannedReplacement | null {
1565
1359
  if (this.isRecoveryExempt(session, candidate)) return null
1566
1360
  if (candidate.characterPressure <= charsForTokens(policy.nativeTriggerTokens)) return null
1567
- const result = candidate.event.data.message
1361
+ const result = candidate.event.data.message as ToolResultMessage
1568
1362
  if (onlyTextBlocks(result.content) === null) return null
1569
1363
  const sourceSeq = rootToolResultSeq(session, candidate.seq)
1570
1364
  // R9b site: the marker's retrieve hint starts at the event line right
@@ -1616,7 +1410,7 @@ export class ToolResultPruner extends Service {
1616
1410
  view: CompactionTokenView,
1617
1411
  ): PlannedReplacement | null {
1618
1412
  if (typeof candidate.event.surfaceOp === 'object') return null
1619
- const result = candidate.event.data.message
1413
+ const result = candidate.event.data.message as ToolResultMessage
1620
1414
  const text = flattenPlainText(result.content)
1621
1415
  if (text === undefined) return null
1622
1416
  if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
@@ -1664,7 +1458,7 @@ export class ToolResultPruner extends Service {
1664
1458
  // pre-step coordinate filter prevents previously-kept originals from ever
1665
1459
  // being reconsidered after their first request.
1666
1460
  if (typeof candidate.event.surfaceOp === 'object') return null
1667
- const result = candidate.event.data.message
1461
+ const result = candidate.event.data.message as ToolResultMessage
1668
1462
  if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1669
1463
  const sourceSeq = candidate.seq
1670
1464
  const sourceRef = sourceRefFn(session, sourceSeq)
@@ -1742,7 +1536,7 @@ export class ToolResultPruner extends Service {
1742
1536
  // example one carrying an image) must never reach it. The character basis
1743
1537
  // no longer inherits the exact-tokenizer precondition that used to reject
1744
1538
  // this path implicitly, so the guard has to be explicit.
1745
- const redacted = candidate.event.data.message
1539
+ const redacted = candidate.event.data.message as ToolResultMessage
1746
1540
  if (onlyTextBlocks(redacted.content) === null) return null
1747
1541
  const text = [
1748
1542
  '[Tool result reduced to satisfy the completed-step aggregate budget]',
@@ -1776,7 +1570,7 @@ export class ToolResultPruner extends Service {
1776
1570
  historyMode?: HistoryMode,
1777
1571
  ): PlannedReplacement | null {
1778
1572
  if (!isError(candidate)) return null
1779
- const result = candidate.event.data.message
1573
+ const result = candidate.event.data.message as ToolResultMessage
1780
1574
  const blocks = onlyTextBlocks(result.content)
1781
1575
  if (blocks === null) return null
1782
1576
  const text = blocks.map(block => block.text).join('\n')
@@ -1834,17 +1628,15 @@ export class ToolResultPruner extends Service {
1834
1628
  const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
1835
1629
  const isUnsafe = (candidate: SnapshotCandidate): boolean => {
1836
1630
  if (this.isRecoveryExempt(session, candidate)) return true
1837
- const result = candidate.event.data.message
1631
+ const result = candidate.event.data.message as ToolResultMessage
1838
1632
  const block = onlyTextBlock(result.content)
1839
- // Fold-once: an already-folded intent block is never re-candidated.
1840
- if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
1841
1633
  return block?.text.includes('[Old tool result content cleared from active context]') === true
1842
1634
  }
1843
1635
  // Distinguish "nothing safe to touch" (recovery tool output or already
1844
1636
  // cleared) from "everything left is inside the protected working set":
1845
1637
  // both skip, but they are different operational facts.
1846
1638
  const safe = candidates.filter(candidate => !isUnsafe(candidate))
1847
- const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1639
+ const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1848
1640
  if (eligible.length === 0) {
1849
1641
  return safe.length === 0
1850
1642
  ? { kind: 'no-safe-candidates' }
@@ -1852,38 +1644,6 @@ export class ToolResultPruner extends Service {
1852
1644
  }
1853
1645
  const planned: PlannedReplacement[] = []
1854
1646
  let reclaim = 0
1855
- // Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
1856
- // postflight lands FIRST, through the same plan pipeline as every other
1857
- // reducer; its reclaim counts toward the batch target and its seqs are
1858
- // removed from the ordinary loop (fold-once).
1859
- const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
1860
- if (intentApplied !== undefined) {
1861
- planned.push(...intentApplied.plans)
1862
- reclaim += intentApplied.reclaim
1863
- this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
1864
- this.state.pendingIntentFolds.delete(session)
1865
- this.state.intentBaselines.set(session, view.totalTokens)
1866
- recordIntentFold(String(session.id), {
1867
- turn: intentApplied.turn,
1868
- startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
1869
- endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
1870
- liveTokensBefore: view.totalTokens,
1871
- at: Date.now(),
1872
- })
1873
- emitCompressionAudit(this.ctx.logger, {
1874
- schemaVersion: 1,
1875
- kind: 'intent-summary-outcome',
1876
- sessionId: String(session.id),
1877
- ok: true,
1878
- reason: 'landed',
1879
- foldedCount: intentApplied.plans.length,
1880
- ...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
1881
- summaryCallChars: intentApplied.summaryCallChars,
1882
- })
1883
- for (let index = eligible.length - 1; index >= 0; index -= 1) {
1884
- if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
1885
- }
1886
- }
1887
1647
  // Linked batches must reach the deadline target; unlinked batches keep
1888
1648
  // the traditional minimum-reclaim commit threshold. All arithmetic runs on
1889
1649
  // the character basis: token-named thresholds enter via charsForTokens.
@@ -1898,7 +1658,7 @@ export class ToolResultPruner extends Service {
1898
1658
  ? minReclaimChars
1899
1659
  : required
1900
1660
  for (const candidate of eligible) {
1901
- const result = candidate.event.data.message
1661
+ const result = candidate.event.data.message as ToolResultMessage
1902
1662
  const block = onlyTextBlock(result.content)
1903
1663
  // TokenPilot-inspired R2: a read output whose file was later mutated is
1904
1664
  // superseded — its text can no longer match the file — so it takes the
@@ -2107,7 +1867,7 @@ export class ToolResultPruner extends Service {
2107
1867
  if (event?.type !== 'tool/result'
2108
1868
  || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
2109
1869
  || event.data.error !== undefined) return true
2110
- const block = event.data.message
1870
+ const block = event.data.message as ToolResultMessage
2111
1871
  if (block.isError === true) return true
2112
1872
  // Images and other rich inner blocks stay fail-open: a TailTrim stub
2113
1873
  // would silently delete them from the active context.
@@ -2561,11 +2321,7 @@ export class ToolResultPruner extends Service {
2561
2321
  manifestEventType: 'compaction/summary',
2562
2322
  manifestSeq,
2563
2323
  reducer: 'llm-summary',
2564
- // Legacy manifest fields were written as free-form scalars; String() is
2565
- // the intentional best-effort coercion of whatever the host stored.
2566
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
2567
2324
  provider: data.provider === undefined ? 'unknown' : String(data.provider),
2568
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
2569
2325
  model: data.model === undefined ? 'unknown' : String(data.model),
2570
2326
  tokensBefore: typeof data.shadowedTokenCount === 'number' ? data.shadowedTokenCount : null,
2571
2327
  tokensAfter: null,
@@ -205,22 +205,6 @@ export interface AdvisorOutcomeAuditRecord extends CompressionAuditBase {
205
205
  readonly latencyMs: number
206
206
  }
207
207
 
208
- /** One turn-tail intent-summary pass: gate decision, ask outcome, or landing. Numeric metadata only. */
209
- export interface IntentSummaryOutcomeAuditRecord extends CompressionAuditBase {
210
- readonly kind: 'intent-summary-outcome'
211
- readonly ok: boolean
212
- /** Aligned decision/reason code (gate reason, 'parse-failed', 'landed', 'expired'...). */
213
- readonly reason: string
214
- readonly turnIndex?: number
215
- /** Folded candidate count when a range was selected or landed. */
216
- readonly foldedCount?: number
217
- /** Aggregate retention ratio of the landed batch (charsAfter / charsBefore). */
218
- readonly retentionRatio?: number
219
- /** Characters spent on the summary-writer call itself (credit accounting). */
220
- readonly summaryCallChars?: number
221
- readonly latencyMs?: number
222
- }
223
-
224
208
  /**
225
209
  * One advisory benefit-model label for a batch that LANDED. The retired review
226
210
  * gate used these bands to withhold a batch; a reduction must never block
@@ -263,7 +247,6 @@ export type CompressionAuditRecord =
263
247
  | SummaryLocatorAuditRecord
264
248
  | EstimatorOutcomeAuditRecord
265
249
  | AdvisorOutcomeAuditRecord
266
- | IntentSummaryOutcomeAuditRecord
267
250
  | ReductionAdviceAuditRecord
268
251
 
269
252
  /** Minimal logger method consumed by the audit publisher. */
@@ -5,7 +5,6 @@ import type {
5
5
  AutoCompactSettings,
6
6
  CodeSkeletonSettings,
7
7
  CompressionPolicy,
8
- IntentSummarySettings,
9
8
  CompressionProfile,
10
9
  CustomCompressionPolicy,
11
10
  PresetOptions,
@@ -87,7 +86,7 @@ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
87
86
  if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
88
87
  throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
89
88
  }
90
- const thresholdPercent = (value).thresholdPercent
89
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
91
90
  if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
92
91
  throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
93
92
  }
@@ -108,34 +107,13 @@ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
108
107
  if (keys.length !== 1 || keys[0] !== 'enabled') {
109
108
  throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
110
109
  }
111
- const enabled = (value).enabled
110
+ const enabled = (value as Record<string, unknown>).enabled
112
111
  if (typeof enabled !== 'boolean') {
113
112
  throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
114
113
  }
115
114
  return { enabled }
116
115
  }
117
116
 
118
- /**
119
- * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
120
- * section semantics: absent inherits the lossless `false` default, while a
121
- * present-but-invalid section is an explicitly invalid document.
122
- */
123
- function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
124
- if (value === undefined) return { enabled: false }
125
- if (!isPlainRecord(value)) {
126
- throw new TypeError('Context-compression intentSummary must be a plain object')
127
- }
128
- const keys = Object.keys(value)
129
- if (keys.length !== 1 || keys[0] !== 'enabled') {
130
- throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
131
- }
132
- const enabled = (value).enabled
133
- if (typeof enabled !== 'boolean') {
134
- throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
135
- }
136
- return { enabled }
137
- }
138
-
139
117
  /**
140
118
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
141
119
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
@@ -225,18 +203,18 @@ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSetting
225
203
  if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
226
204
  if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
227
205
  if (value.readState !== undefined) result.readState = value.readState as boolean
228
- if (estimatorMode !== undefined) result.estimatorMode = estimatorMode
206
+ if (estimatorMode !== undefined) result.estimatorMode = estimatorMode as '' | 'host' | 'direct'
229
207
  if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
230
208
  if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
231
209
  if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
232
210
  if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
233
- if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs
234
- if (advisorMode !== undefined) result.advisorMode = advisorMode
235
- if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs
236
- if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns
237
- if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold
238
- if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit
239
- if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens
211
+ if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs as number
212
+ if (advisorMode !== undefined) result.advisorMode = advisorMode as '' | 'host' | 'direct'
213
+ if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs as number
214
+ if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns as number
215
+ if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold as number
216
+ if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit as number
217
+ if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens as number
240
218
  return result
241
219
  }
242
220
 
@@ -275,7 +253,6 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
275
253
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
276
254
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
277
255
  codeSkeleton: { enabled: false },
278
- intentSummary: { enabled: false },
279
256
  }
280
257
 
281
258
  /**
@@ -313,7 +290,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
313
290
  // remain valid and inherit their defaults; the sections themselves stay
314
291
  // strictly shaped.
315
292
  const unknown = Object.keys(candidate).find(key =>
316
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')
293
+ key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'presetOptions')
317
294
  if (unknown !== undefined) {
318
295
  throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
319
296
  }
@@ -325,13 +302,11 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
325
302
  assertPresentSection(candidate, 'custom', isUsableCustomDocument)
326
303
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
327
304
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
328
- const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
329
305
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
330
306
  return {
331
307
  ...contextCompressionSettingsInputSchema(candidate),
332
308
  autoCompact,
333
309
  codeSkeleton,
334
- intentSummary,
335
310
  ...presetOptions === undefined ? {} : { presetOptions },
336
311
  }
337
312
  },
@@ -80,7 +80,7 @@ export function documentSectionSummaries(text: string): readonly { readonly id:
80
80
  const headings: { id: string, level: number, line: number }[] = []
81
81
  for (let index = 0; index < lines.length; index++) {
82
82
  const match = /^#{1,6}\s+(.*)$/.exec(lines[index] ?? '')
83
- if (match !== null) headings.push({ id: match[1]!.trim(), level: (lines[index]!.match(/^#+/) ?? ['#'])[0].length, line: index })
83
+ if (match !== null) headings.push({ id: match[1]!.trim(), level: (lines[index]!.match(/^#+/) ?? ['#'])[0]!.length, line: index })
84
84
  }
85
85
  return headings.map((heading, position) => {
86
86
  const from = heading.line + 1