dsh-context-compression-improved 0.5.6 → 0.5.8

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 (183) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +323 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +163 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.d.ts +59 -0
  34. package/packages/selector/lib/client.js +1738 -10
  35. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  36. package/packages/selector/lib/index.d.ts +13 -1
  37. package/packages/selector/lib/index.js +295 -3
  38. package/packages/selector/lib/pruner.d.ts +65 -0
  39. package/packages/selector/lib/pruner.js +497 -262
  40. package/packages/selector/lib/style.css +88 -46
  41. package/packages/selector/package.json +114 -114
  42. package/packages/selector/screenshots.json +3 -3
  43. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  44. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  45. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  46. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  47. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  48. package/packages/selector/src/client/decode.ts +57 -49
  49. package/packages/selector/src/client/index.ts +240 -149
  50. package/packages/selector/src/client/locales/de.ts +141 -0
  51. package/packages/selector/src/client/locales/es.ts +141 -0
  52. package/packages/selector/src/client/locales/fr.ts +141 -0
  53. package/packages/selector/src/client/locales/it.ts +141 -0
  54. package/packages/selector/src/client/locales/ja.ts +141 -0
  55. package/packages/selector/src/client/locales/ko.ts +141 -0
  56. package/packages/selector/src/client/locales/ru.ts +141 -0
  57. package/packages/selector/src/client/locales.ts +282 -196
  58. package/packages/selector/src/client/monitor-fab.ts +336 -0
  59. package/packages/selector/src/client/preset-options.ts +88 -88
  60. package/packages/selector/src/client/savings-card.tsx +150 -0
  61. package/packages/selector/src/client/settings-section.tsx +140 -124
  62. package/packages/selector/src/css-modules.d.ts +6 -6
  63. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  64. package/packages/selector/src/estimator-catalog.ts +104 -104
  65. package/packages/selector/src/index.ts +673 -463
  66. package/packages/selector/src/invariant.ts +113 -113
  67. package/packages/selector/src/preset-overlay.ts +626 -626
  68. package/packages/selector/src/profiles.ts +431 -394
  69. package/packages/selector/src/pruner/content.ts +201 -201
  70. package/packages/selector/src/pruner/session.ts +94 -94
  71. package/packages/selector/src/pruner/state.ts +57 -50
  72. package/packages/selector/src/pruner/tuning.ts +23 -23
  73. package/packages/selector/src/pruner/types.ts +78 -78
  74. package/packages/selector/src/pruner.ts +2736 -2402
  75. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  76. package/packages/selector/src/runtime/audit.ts +303 -286
  77. package/packages/selector/src/runtime/config.ts +756 -706
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +436 -436
  82. package/packages/selector/src/runtime/monitor.ts +235 -0
  83. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  84. package/packages/selector/src/runtime/retrieve.ts +479 -457
  85. package/packages/selector/src/runtime/savings.ts +337 -0
  86. package/packages/selector/src/runtime/session-events.ts +30 -30
  87. package/packages/selector/src/runtime/summary-command.ts +127 -0
  88. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  89. package/packages/selector/src/runtime/token-count.ts +72 -72
  90. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  91. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  92. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  93. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  94. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  95. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  96. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  97. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  98. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  99. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  100. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  101. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  102. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  103. package/packages/selector/src/runtime/toolclass.ts +103 -103
  104. package/packages/selector/src/runtime/types.ts +365 -346
  105. package/packages/selector/src/runtime/value.ts +48 -48
  106. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  107. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  108. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  109. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  110. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -90
  111. package/packages/selector/tests/custom-contract.client.spec.ts +205 -204
  112. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  113. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  114. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  115. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  116. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  117. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -206
  118. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  119. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  120. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  121. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  122. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  123. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  124. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  125. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  126. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  127. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  128. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  129. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  130. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  131. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  132. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  133. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  134. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  135. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  136. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  137. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  138. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  139. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  140. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  141. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  142. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  143. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  144. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  145. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  146. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  147. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  148. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  149. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  150. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  151. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  152. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  153. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  154. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  155. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  156. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  157. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  158. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  159. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  160. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  161. package/packages/selector/tests/settings-seat.client.spec.ts +130 -118
  162. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  163. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  164. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  165. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  166. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  167. package/packages/selector/tsconfig.json +11 -11
  168. package/packages/selector/tsdown.client.config.ts +102 -102
  169. package/packages/selector/tsdown.config.ts +20 -20
  170. package/pnpm-workspace.yaml +66 -66
  171. package/scripts/capture-profile-baseline.mjs +42 -42
  172. package/scripts/generate-tokenizer-fixtures.py +81 -81
  173. package/scripts/generate-vision-fixtures.py +208 -208
  174. package/scripts/packed-components-smoke.mjs +732 -732
  175. package/scripts/packed-install-e2e.mjs +1273 -1273
  176. package/scripts/toolclass-corpus-replay.mjs +281 -281
  177. package/scripts/verify-release.mjs +318 -317
  178. package/tests/TEST_INVENTORY.md +41 -41
  179. package/tsconfig.base.json +18 -18
  180. package/tsconfig.json +7 -7
  181. package/tsconfig.tests.json +15 -15
  182. package/vitest.built.config.ts +9 -9
  183. package/vitest.config.ts +43 -43
@@ -1,706 +1,756 @@
1
- /** Configuration resolution for the mixed deterministic context-compression selector. */
2
-
3
- import z from '@deepseek-ai/schemastery'
4
- import type {
5
- AutoCompactSettings,
6
- CodeSkeletonSettings,
7
- CompressionPolicy,
8
- CompressionProfile,
9
- CustomCompressionPolicy,
10
- PresetOptions,
11
- PresetOptionsSettings,
12
- ContextCompressionSettings,
13
- ResolvedConfig,
14
- ToolResultPruneConfig,
15
- } from './types.ts'
16
- import { COMPRESSION_PROFILES } from './types.ts'
17
- import {
18
- CustomCompressionPolicySchema,
19
- DEFAULT_CUSTOM_COMPRESSION_POLICY,
20
- resolveCustomPolicy,
21
- type CustomPolicyResolutionOptions,
22
- } from './custom-policy.ts'
23
- import { deepFreeze } from './value.ts'
24
-
25
- /** Settings namespace shared by the Host service and browser selector. */
26
- export const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = 'context-compression'
27
-
28
- /** Fixed native fallback marker. */
29
- export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n'
30
-
31
- /**
32
- * The one Auto Compact threshold contract shared by the settings UI, the
33
- * persisted settings schema, and the runtime resolver. Every integer in the
34
- * range is valid and entered directly in the UI.
35
- */
36
- export const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
37
- min: 50,
38
- max: 90,
39
- step: 1,
40
- default: 80,
41
- } as const)
42
-
43
- /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
44
- export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
45
- return typeof value === 'number'
46
- && Number.isSafeInteger(value)
47
- && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
48
- && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
49
- }
50
-
51
- const AUTO_COMPACT_DEFAULT: AutoCompactSettings = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default })
52
-
53
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
54
- function isPlainRecord(value: unknown): value is Record<string, unknown> {
55
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
56
- const prototype = Object.getPrototypeOf(value) as object | null
57
- return prototype === Object.prototype || prototype === null
58
- }
59
-
60
- /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
61
- function assertPlainDataTree(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
62
- if (value === null || typeof value !== 'object') return
63
- if (seen.has(value)) return
64
- seen.add(value)
65
- if (Array.isArray(value)) {
66
- for (const entry of value) assertPlainDataTree(entry, seen)
67
- return
68
- }
69
- if (!isPlainRecord(value)) {
70
- throw new TypeError('Context-compression settings must contain only plain objects')
71
- }
72
- for (const entry of Object.values(value)) assertPlainDataTree(entry, seen)
73
- }
74
-
75
- /**
76
- * Strictly parse the persisted autoCompact section. Schemastery object
77
- * defaults silently absorb null, empty, and extra-key sections, so this stays
78
- * hand-validated beside the top-level unknown-key check.
79
- */
80
- function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
81
- if (value === undefined) return AUTO_COMPACT_DEFAULT
82
- if (!isPlainRecord(value)) {
83
- throw new TypeError('Context-compression autoCompact must be a plain object')
84
- }
85
- const keys = Object.keys(value)
86
- if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
87
- throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
88
- }
89
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
90
- if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
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)}`)
92
- }
93
- return { thresholdPercent }
94
- }
95
-
96
- /**
97
- * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
98
- * to every profile: absent inherits the lossless `false` default, while a
99
- * present-but-invalid section is an explicitly invalid document.
100
- */
101
- function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
102
- if (value === undefined) return { enabled: false }
103
- if (!isPlainRecord(value)) {
104
- throw new TypeError('Context-compression codeSkeleton must be a plain object')
105
- }
106
- const keys = Object.keys(value)
107
- if (keys.length !== 1 || keys[0] !== 'enabled') {
108
- throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
109
- }
110
- const enabled = (value as Record<string, unknown>).enabled
111
- if (typeof enabled !== 'boolean') {
112
- throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
113
- }
114
- return { enabled }
115
- }
116
-
117
- /**
118
- * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
119
- * inherits the preset defaults; present-but-invalid is rejected, mirroring the
120
- * codeSkeleton section semantics.
121
- */
122
- export function parsePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
123
- if (value === undefined) return undefined
124
- if (!isPlainRecord(value)) {
125
- throw new TypeError('Context-compression presetOptions must be a plain object')
126
- }
127
- const allowed = new Set([
128
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
129
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
130
- // Legacy keys of the retired human-gated review pipeline. They stay in the
131
- // ACCEPTED set on purpose: the keys are persisted in existing settings
132
- // documents, and rejecting them would make this plugin fail to load on an
133
- // upgrade. They are read by nothing — the gate they configured no longer
134
- // exists, and a reduction never blocks automatic processing.
135
- 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
136
- 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
137
- 'advisorMinTokens',
138
- ])
139
- const unknown = Object.keys(value).find(key => !allowed.has(key))
140
- if (unknown !== undefined) {
141
- throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`)
142
- }
143
- const booleans = ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const
144
- for (const key of booleans) {
145
- const entry = value[key]
146
- if (entry !== undefined && typeof entry !== 'boolean') {
147
- throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`)
148
- }
149
- }
150
- const estimatorMode = value.estimatorMode
151
- if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
152
- throw new TypeError('Context-compression presetOptions.estimatorMode must be "", "host", or "direct"')
153
- }
154
- const advisorMode = value.advisorMode
155
- if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
156
- throw new TypeError('Context-compression presetOptions.advisorMode must be "", "host", or "direct"')
157
- }
158
- const advisorTimeoutMs = value.advisorTimeoutMs
159
- if (advisorTimeoutMs !== undefined
160
- && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
161
- || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
162
- throw new TypeError('Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000')
163
- }
164
- const advisorRefreshTurns = value.advisorRefreshTurns
165
- if (advisorRefreshTurns !== undefined
166
- && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
167
- || advisorRefreshTurns < 1)) {
168
- throw new TypeError('Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1')
169
- }
170
- const advisorScoreThreshold = value.advisorScoreThreshold
171
- if (advisorScoreThreshold !== undefined
172
- && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
173
- || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
174
- throw new TypeError('Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1')
175
- }
176
- const advisorSampleLimit = value.advisorSampleLimit
177
- if (advisorSampleLimit !== undefined
178
- && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
179
- || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
180
- throw new TypeError('Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64')
181
- }
182
- const advisorMinTokens = value.advisorMinTokens
183
- if (advisorMinTokens !== undefined
184
- && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
185
- throw new TypeError('Context-compression presetOptions.advisorMinTokens must be a positive integer')
186
- }
187
- const estimatorTimeoutMs = value.estimatorTimeoutMs
188
- if (estimatorTimeoutMs !== undefined
189
- && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
190
- || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
191
- throw new TypeError('Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000')
192
- }
193
- for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
194
- const entry = value[key]
195
- if (entry !== undefined && typeof entry !== 'string') {
196
- throw new TypeError(`Context-compression presetOptions.${key} must be a string`)
197
- }
198
- }
199
- const result: {
200
- -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
201
- } = {}
202
- if (value.dedupeToolResults !== undefined) result.dedupeToolResults = value.dedupeToolResults as boolean
203
- if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
204
- if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
205
- if (value.readState !== undefined) result.readState = value.readState as boolean
206
- if (estimatorMode !== undefined) result.estimatorMode = estimatorMode as '' | 'host' | 'direct'
207
- if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
208
- if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
209
- if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
210
- if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
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
218
- return result
219
- }
220
-
221
- /** Settings schema used by the user-facing profile selector. */
222
- const contextCompressionSettingsInputSchema = z.object({
223
- profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
224
- custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
225
- })
226
-
227
- /**
228
- * Reject a section that is PRESENT but not a usable value. Schemastery
229
- * `.default(...)` silently substitutes null and undefined, which would turn a
230
- * hand-corrupted store into the (lossy) default policy; only genuinely absent
231
- * keys may inherit defaults, and that distinction must be made before any
232
- * default can fire.
233
- */
234
- function assertPresentSection(
235
- candidate: Record<string, unknown>,
236
- key: 'profile' | 'custom',
237
- valid: (value: unknown) => boolean,
238
- ): void {
239
- if (!Object.hasOwn(candidate, key)) return
240
- if (!valid(candidate[key])) {
241
- throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`)
242
- }
243
- }
244
-
245
- const isSupportedProfile = (value: unknown): boolean =>
246
- typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
247
-
248
- const isUsableCustomDocument = (value: unknown): boolean =>
249
- isPlainRecord(value)
250
-
251
- const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
252
- profile: 'balanced',
253
- custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
254
- autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
255
- codeSkeleton: { enabled: false },
256
- }
257
-
258
- /**
259
- * Parse one settings document with the persisted-section semantics: `undefined`
260
- * inherits the defaults (an absent section), while `null` is an explicitly
261
- * invalid document and must never silently become the default policy.
262
- */
263
- export function parseContextCompressionSettings(value: unknown): ContextCompressionSettings {
264
- if (!isPlainRecord(value)) {
265
- throw new TypeError('Context-compression settings must be a plain object')
266
- }
267
- const keys = Object.keys(value)
268
- // Documents surfaced by the settings service are always schema-resolved and
269
- // complete; anything thinner is a hand-edited store and must not silently
270
- // become a default (possibly lossy) policy.
271
- if (keys.length === 0 || !keys.includes('profile') || !keys.includes('custom')) {
272
- throw new TypeError('Context-compression settings document is missing its complete shape')
273
- }
274
- return ContextCompressionSettingsSchema(value as never)
275
- }
276
-
277
- /** Settings schema used by the user-facing profile selector. */
278
- export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z.transform(
279
- z.any().required(),
280
- (value: unknown): ContextCompressionSettings => {
281
- if (!isPlainRecord(value)) {
282
- throw new TypeError('Context-compression settings must be a plain object')
283
- }
284
- // Validate prototypes before cloning, then parse a detached mutable copy:
285
- // SettingsProvider returns frozen records, while structuredClone would
286
- // otherwise erase exotic prototypes before this boundary can reject them.
287
- assertPlainDataTree(value)
288
- const candidate = structuredClone(value)
289
- // Settings stored before the autoCompact or codeSkeleton sections existed
290
- // remain valid and inherit their defaults; the sections themselves stay
291
- // strictly shaped.
292
- const unknown = Object.keys(candidate).find(key =>
293
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'presetOptions')
294
- if (unknown !== undefined) {
295
- throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
296
- }
297
- // Present-but-invalid sections must never fall through to the Schemastery
298
- // defaults below: `profile: null` silently becoming the lossy `balanced`
299
- // default is exactly the corruption the lossless-off fallback exists for.
300
- // Only genuinely absent sections (internal partial fallbacks) may inherit.
301
- assertPresentSection(candidate, 'profile', isSupportedProfile)
302
- assertPresentSection(candidate, 'custom', isUsableCustomDocument)
303
- const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
304
- const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
305
- const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
306
- return {
307
- ...contextCompressionSettingsInputSchema(candidate),
308
- autoCompact,
309
- codeSkeleton,
310
- ...presetOptions === undefined ? {} : { presetOptions },
311
- }
312
- },
313
- ).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS) as z<ContextCompressionSettings>
314
-
315
- /** Low-friction defaults; token budgets live in resolved profile policy. */
316
- export const DEFAULTS: ResolvedConfig = deepFreeze({
317
- profile: 'balanced',
318
- headChars: 4096,
319
- tailChars: 1024,
320
- })
321
-
322
- const CONFIG_KEYS: ReadonlySet<string> = new Set([
323
- 'profile',
324
- 'headChars',
325
- 'tailChars',
326
- 'nativeTriggerTokens',
327
- 'nativeTargetTokens',
328
- 'freshTriggerTokens',
329
- 'freshTargetTokens',
330
- 'aggregateTriggerTokens',
331
- 'aggregateTargetTokens',
332
- 'historyTriggerTokens',
333
- 'historyKeepRecentToolCalls',
334
- 'historyKeepRecentTokens',
335
- 'historyMinReclaimTokens',
336
- 'readInputCapChars',
337
- 'autoCompactThresholdPercent',
338
- 'presetOptions',
339
- ])
340
-
341
- const LEGACY_GATE_REPLACEMENTS: Readonly<Record<string, string>> = Object.freeze({
342
- thresholdChars: 'nativeTriggerTokens',
343
- freshThresholdChars: 'freshTriggerTokens',
344
- freshTargetChars: 'freshTargetTokens',
345
- freshBatchTriggerChars: 'aggregateTriggerTokens',
346
- freshBatchTargetChars: 'aggregateTargetTokens',
347
- historyTriggerChars: 'historyTriggerTokens',
348
- historyKeepRecentChars: 'historyKeepRecentTokens',
349
- historyMinReclaimChars: 'historyMinReclaimTokens',
350
- historyKeepRecentTurns: 'historyKeepRecentToolCalls',
351
- })
352
-
353
- /**
354
- * Count Unicode code points without splitting surrogate pairs.
355
- * @param text - text whose code points are counted.
356
- * @returns the number of Unicode code points.
357
- */
358
- export function codePointLength(text: string): number {
359
- let length = 0
360
- for (const _point of text) length++
361
- return length
362
- }
363
-
364
- /**
365
- * Conservative upper bound on characters per token. Same convention the
366
- * readInputCapChars invariant already uses (see resolvePolicy): English
367
- * code runs approximately four characters per token at the upper bound.
368
- */
369
- export const CHARS_PER_TOKEN = 4.0
370
-
371
- /** Express one token-named policy gate on the character basis. */
372
- export function charsForTokens(tokens: number): number {
373
- return tokens * CHARS_PER_TOKEN
374
- }
375
-
376
- /** Derive the telemetry-only token figure from a character measurement. */
377
- export function charsToTokens(chars: number): number {
378
- if (!Number.isFinite(chars) || chars <= 0) return 0
379
- return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
380
- }
381
-
382
- /**
383
- * Test whether a settings value names a supported compression profile.
384
- * @param value - untrusted settings value.
385
- * @returns whether the value is a supported compression profile.
386
- */
387
- export function isCompressionProfile(value: unknown): value is CompressionProfile {
388
- return typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
389
- }
390
-
391
- /**
392
- * Resolve and validate plugin configuration.
393
- * @param config - optional composition overrides.
394
- * @returns a detached, deeply immutable configuration snapshot.
395
- */
396
- export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfig {
397
- for (const key of Object.keys(config)) {
398
- const replacement = LEGACY_GATE_REPLACEMENTS[key]
399
- if (replacement !== undefined) {
400
- throw new Error(
401
- `ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; `
402
- + `choose "${replacement}" manually in tokens (no character conversion is applied)`,
403
- )
404
- }
405
- if (!CONFIG_KEYS.has(key)) {
406
- throw new Error(`ToolResultPruneConfig: unknown key "${key}"`)
407
- }
408
- }
409
- const resolved: ResolvedConfig = {
410
- profile: config.profile ?? DEFAULTS.profile,
411
- headChars: config.headChars ?? DEFAULTS.headChars,
412
- tailChars: config.tailChars ?? DEFAULTS.tailChars,
413
- ...config.nativeTriggerTokens === undefined ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
414
- ...config.nativeTargetTokens === undefined ? {} : { nativeTargetTokens: config.nativeTargetTokens },
415
- ...config.freshTriggerTokens === undefined ? {} : { freshTriggerTokens: config.freshTriggerTokens },
416
- ...config.freshTargetTokens === undefined ? {} : { freshTargetTokens: config.freshTargetTokens },
417
- ...config.aggregateTriggerTokens === undefined ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
418
- ...config.aggregateTargetTokens === undefined ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
419
- ...config.historyTriggerTokens === undefined ? {} : { historyTriggerTokens: config.historyTriggerTokens },
420
- ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
421
- ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
422
- ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
423
- ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
424
- ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
425
- ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
426
- }
427
- if (!isCompressionProfile(resolved.profile)) {
428
- throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`)
429
- }
430
- assertNonNegativeInteger('headChars', resolved.headChars)
431
- assertNonNegativeInteger('tailChars', resolved.tailChars)
432
- for (const key of [
433
- 'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
434
- 'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
435
- 'historyMinReclaimTokens', 'readInputCapChars',
436
- ] as const) {
437
- const value = resolved[key]
438
- if (value !== undefined) assertPositiveInteger(key, value)
439
- }
440
- if (resolved.historyKeepRecentToolCalls !== undefined) {
441
- assertNonNegativeInteger('historyKeepRecentToolCalls', resolved.historyKeepRecentToolCalls)
442
- }
443
- if (resolved.historyKeepRecentTokens !== undefined) {
444
- assertNonNegativeInteger('historyKeepRecentTokens', resolved.historyKeepRecentTokens)
445
- }
446
- if (resolved.autoCompactThresholdPercent !== undefined
447
- && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) {
448
- throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
449
- }
450
- assertTargetBelowTrigger('native', resolved.nativeTargetTokens, resolved.nativeTriggerTokens)
451
- assertTargetBelowTrigger('fresh', resolved.freshTargetTokens, resolved.freshTriggerTokens)
452
- assertTargetBelowTrigger('aggregate', resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens)
453
- return deepFreeze(structuredClone(resolved))
454
- }
455
-
456
- /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
457
- const AUTO_COMPACT_HISTORY_RATIOS: Readonly<Record<string, Readonly<{
458
- trigger: number
459
- minReclaim: number
460
- keepRecentTokens: number
461
- }>>> = Object.freeze({
462
- balanced: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
463
- savings: Object.freeze({ trigger: 0.50, minReclaim: 0.16, keepRecentTokens: 0.08 }),
464
- 'cache-strict': Object.freeze({ trigger: 0.75, minReclaim: 0.16, keepRecentTokens: 0.08 }),
465
- adaptive: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
466
- 'tokenpilot-inspired': Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
467
- })
468
-
469
- /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
470
- const MICRO_DEADLINE_RATIO = 0.875
471
-
472
- /**
473
- * TokenPilot-inspired sub-capability defaults. Every capability is on except
474
- * the estimator, which requires an explicit endpoint channel (host or direct)
475
- * before any consumer may leave its rule-only fallback.
476
- */
477
- const PRESET_OPTION_DEFAULTS: PresetOptions = deepFreeze({
478
- noNetSavingsGuard: true,
479
- skipReductionRecovery: true,
480
- dedupeToolResults: true,
481
- summaryLocator: true,
482
- prefixStabilizer: true,
483
- readState: true,
484
- estimator: { mode: '' },
485
- // Advisory advisor ships off: statistics and suggestions only, never a gate.
486
- advisor: {
487
- mode: '',
488
- timeoutMs: 8_000,
489
- refreshTurns: 8,
490
- scoreThreshold: 0.35,
491
- sampleLimit: 16,
492
- minTokens: 250,
493
- },
494
- })
495
-
496
- /**
497
- * Merge persisted presetOptions overrides over the tokenpilot-inspired
498
- * defaults. Persisted booleans are three-state (undefined = inherit); the
499
- * estimator channel overrides the default empty mode wholesale.
500
- */
501
- function mergePresetOptions(overrides: PresetOptionsSettings | undefined): PresetOptions {
502
- if (overrides === undefined) return PRESET_OPTION_DEFAULTS
503
- return deepFreeze({
504
- noNetSavingsGuard: true,
505
- skipReductionRecovery: true,
506
- dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
507
- summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
508
- prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
509
- readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
510
- estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
511
- advisor: {
512
- mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
513
- timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
514
- refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
515
- scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
516
- sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
517
- minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens,
518
- },
519
- })
520
- }
521
-
522
- /**
523
- * Resolve the Auto-Compact-linked History watermarks for one standard profile.
524
- *
525
- * `A = floor(C × a)` is the Auto Compact token watermark for the routed
526
- * context window `C` and the user threshold `a = p / 100`; the History
527
- * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
528
- * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
529
- * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
530
- * preset numbers exactly. Custom stays manual and Off/Native run no History,
531
- * so none of them link.
532
- */
533
- function resolveAutoCompactLinkage(
534
- profile: CompressionProfile,
535
- options: CustomPolicyResolutionOptions,
536
- ): { autoCompactTokens: number, microDeadlineTokens: number, historyTriggerTokens: number,
537
- historyMinReclaimTokens: number, historyKeepRecentTokens: number } | undefined {
538
- const ratios = profile === 'custom' ? undefined : AUTO_COMPACT_HISTORY_RATIOS[profile]
539
- const contextWindow = options.contextWindowTokens
540
- const threshold = options.autoCompactThresholdPercent
541
- if (ratios === undefined) return undefined
542
- if (!isValidAutoCompactThresholdPercent(threshold)) return undefined
543
- if (!Number.isSafeInteger(contextWindow) || contextWindow === undefined || contextWindow <= 0) return undefined
544
- // Mirror compaction-basic's evaluation order exactly: it multiplies by the
545
- // generated ratio float (p / 100), and integer-first division differs by
546
- // one token on some window/percent pairs (200k x 57).
547
- const autoCompactTokens = Math.floor(contextWindow * (threshold / 100))
548
- if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return undefined
549
- const linked = {
550
- autoCompactTokens,
551
- microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
552
- historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
553
- historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
554
- historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens),
555
- }
556
- for (const value of Object.values(linked)) {
557
- if (!Number.isSafeInteger(value) || value <= 0) return undefined
558
- }
559
- return linked
560
- }
561
-
562
- /**
563
- * Resolve one public profile into a complete mixed-strategy policy.
564
- * @param config - validated composition configuration.
565
- * @param profile - profile frozen for the target Session.
566
- * @param custom - versioned Custom document used only by the `custom` profile.
567
- * @param options - routed capacity and the frozen Auto Compact threshold used
568
- * to resolve context-percent Custom values and standard-profile linkage.
569
- * @returns the effective deterministic compression policy.
570
- */
571
- export function resolvePolicy(
572
- config: ResolvedConfig,
573
- profile: CompressionProfile,
574
- custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
575
- options: CustomPolicyResolutionOptions = {},
576
- ): CompressionPolicy {
577
- if (profile === 'custom') return resolveCustomPolicy(custom, options)
578
- const presets: Record<Exclude<CompressionProfile, 'custom'>, Omit<CompressionPolicy, 'profile'>> = {
579
- off: {
580
- nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
581
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
582
- freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
583
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
584
- historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
585
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
586
- },
587
- native: {
588
- nativeToolResultEnabled: true, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
589
- nativeTriggerTokens: 4_096, nativeTargetTokens: 2_048,
590
- freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
591
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
592
- historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
593
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
594
- },
595
- balanced: {
596
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
597
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
598
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
599
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
600
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
601
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
602
- },
603
- 'cache-strict': {
604
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'capacity-pressure',
605
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
606
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
607
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
608
- historyTriggerTokens: 600_000, historyKeepRecentToolCalls: 10,
609
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
610
- },
611
- savings: {
612
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
613
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
614
- freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
615
- aggregateTriggerTokens: 16_384, aggregateTargetTokens: 4_096,
616
- historyTriggerTokens: 400_000, historyKeepRecentToolCalls: 10,
617
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
618
- },
619
- adaptive: {
620
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'adaptive',
621
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
622
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
623
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
624
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
625
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
626
- },
627
- 'tokenpilot-inspired': {
628
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
629
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
630
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
631
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
632
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
633
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
634
- },
635
- }
636
- const preset = presets[profile]
637
- const linkage = resolveAutoCompactLinkage(profile, options)
638
- const policy: CompressionPolicy = {
639
- profile,
640
- ...preset,
641
- nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
642
- nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
643
- freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
644
- freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
645
- aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
646
- aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
647
- historyTriggerTokens: config.historyTriggerTokens
648
- ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
649
- historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
650
- historyKeepRecentTokens: config.historyKeepRecentTokens
651
- ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
652
- historyMinReclaimTokens: config.historyMinReclaimTokens
653
- ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
654
- ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
655
- ...linkage === undefined ? {} : {
656
- autoCompactTokens: linkage.autoCompactTokens,
657
- microDeadlineTokens: linkage.microDeadlineTokens,
658
- },
659
- ...profile === 'tokenpilot-inspired' ? {
660
- presetOptions: mergePresetOptions(config.presetOptions),
661
- } : {},
662
- }
663
- if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
664
- throw new Error('context compression policy: native target must be below trigger')
665
- }
666
- if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
667
- throw new Error('context compression policy: fresh target must be below trigger')
668
- }
669
- if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
670
- throw new Error('context compression policy: aggregate target must be below trigger')
671
- }
672
- // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
673
- // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
674
- // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
675
- // read result below the trigger and silently silence the fresh path.
676
- if (policy.readInputCapChars !== undefined
677
- && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
678
- throw new Error('context compression policy: read input cap would silence the fresh path')
679
- }
680
- return deepFreeze(policy)
681
- }
682
-
683
- function assertTargetBelowTrigger(
684
- label: string,
685
- target: number | undefined,
686
- trigger: number | undefined,
687
- ): void {
688
- if ((target === undefined) !== (trigger === undefined)) {
689
- throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`)
690
- }
691
- if (target !== undefined && trigger !== undefined && target >= trigger) {
692
- throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`)
693
- }
694
- }
695
-
696
- function assertPositiveInteger(name: string, value: number): void {
697
- if (!Number.isSafeInteger(value) || value <= 0) {
698
- throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`)
699
- }
700
- }
701
-
702
- function assertNonNegativeInteger(name: string, value: number): void {
703
- if (!Number.isSafeInteger(value) || value < 0) {
704
- throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`)
705
- }
706
- }
1
+ /** Configuration resolution for the mixed deterministic context-compression selector. */
2
+
3
+ import z from '@deepseek-ai/schemastery'
4
+ import type {
5
+ AutoCompactSettings,
6
+ CodeSkeletonSettings,
7
+ CompressionPolicy,
8
+ IntentSummarySettings,
9
+ MonitorPanelSettings,
10
+ CompressionProfile,
11
+ CustomCompressionPolicy,
12
+ PresetOptions,
13
+ PresetOptionsSettings,
14
+ ContextCompressionSettings,
15
+ ResolvedConfig,
16
+ ToolResultPruneConfig,
17
+ } from './types.ts'
18
+ import { COMPRESSION_PROFILES } from './types.ts'
19
+ import {
20
+ CustomCompressionPolicySchema,
21
+ DEFAULT_CUSTOM_COMPRESSION_POLICY,
22
+ resolveCustomPolicy,
23
+ type CustomPolicyResolutionOptions,
24
+ } from './custom-policy.ts'
25
+ import { deepFreeze } from './value.ts'
26
+
27
+ /** Settings namespace shared by the Host service and browser selector. */
28
+ export const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = 'context-compression'
29
+
30
+ /** Fixed native fallback marker. */
31
+ export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n'
32
+
33
+ /**
34
+ * The one Auto Compact threshold contract shared by the settings UI, the
35
+ * persisted settings schema, and the runtime resolver. Every integer in the
36
+ * range is valid and entered directly in the UI.
37
+ */
38
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
39
+ min: 50,
40
+ max: 90,
41
+ step: 1,
42
+ default: 80,
43
+ } as const)
44
+
45
+ /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
46
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
47
+ return typeof value === 'number'
48
+ && Number.isSafeInteger(value)
49
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
50
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
51
+ }
52
+
53
+ const AUTO_COMPACT_DEFAULT: AutoCompactSettings = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default })
54
+
55
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
56
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
57
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
58
+ const prototype = Object.getPrototypeOf(value) as object | null
59
+ return prototype === Object.prototype || prototype === null
60
+ }
61
+
62
+ /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
63
+ function assertPlainDataTree(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
64
+ if (value === null || typeof value !== 'object') return
65
+ if (seen.has(value)) return
66
+ seen.add(value)
67
+ if (Array.isArray(value)) {
68
+ for (const entry of value) assertPlainDataTree(entry, seen)
69
+ return
70
+ }
71
+ if (!isPlainRecord(value)) {
72
+ throw new TypeError('Context-compression settings must contain only plain objects')
73
+ }
74
+ for (const entry of Object.values(value)) assertPlainDataTree(entry, seen)
75
+ }
76
+
77
+ /**
78
+ * Strictly parse the persisted autoCompact section. Schemastery object
79
+ * defaults silently absorb null, empty, and extra-key sections, so this stays
80
+ * hand-validated beside the top-level unknown-key check.
81
+ */
82
+ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
83
+ if (value === undefined) return AUTO_COMPACT_DEFAULT
84
+ if (!isPlainRecord(value)) {
85
+ throw new TypeError('Context-compression autoCompact must be a plain object')
86
+ }
87
+ const keys = Object.keys(value)
88
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
89
+ throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
90
+ }
91
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
92
+ if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
93
+ 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)}`)
94
+ }
95
+ return { thresholdPercent }
96
+ }
97
+
98
+ /**
99
+ * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
100
+ * to every profile: absent inherits the lossless `false` default, while a
101
+ * present-but-invalid section is an explicitly invalid document.
102
+ */
103
+ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
104
+ if (value === undefined) return { enabled: false }
105
+ if (!isPlainRecord(value)) {
106
+ throw new TypeError('Context-compression codeSkeleton must be a plain object')
107
+ }
108
+ const keys = Object.keys(value)
109
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
110
+ throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
111
+ }
112
+ const enabled = (value as Record<string, unknown>).enabled
113
+ if (typeof enabled !== 'boolean') {
114
+ throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
115
+ }
116
+ return { enabled }
117
+ }
118
+
119
+ /**
120
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
121
+ * section semantics: absent inherits the lossless `false` default, while a
122
+ * present-but-invalid section is an explicitly invalid document.
123
+ */
124
+ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
125
+ if (value === undefined) return { enabled: false }
126
+ if (!isPlainRecord(value)) {
127
+ throw new TypeError('Context-compression intentSummary must be a plain object')
128
+ }
129
+ const keys = Object.keys(value)
130
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
131
+ throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
132
+ }
133
+ const enabled = (value as Record<string, unknown>).enabled
134
+ if (typeof enabled !== 'boolean') {
135
+ throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
136
+ }
137
+ return { enabled }
138
+ }
139
+
140
+ /**
141
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
142
+ * section semantics: absent inherits the hidden default, while a
143
+ * present-but-invalid section is an explicitly invalid document.
144
+ */
145
+ function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
146
+ if (value === undefined) return { enabled: false }
147
+ if (!isPlainRecord(value)) {
148
+ throw new TypeError('Context-compression monitorPanel must be a plain object')
149
+ }
150
+ const keys = Object.keys(value)
151
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
152
+ throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
153
+ }
154
+ const enabled = (value as Record<string, unknown>).enabled
155
+ if (typeof enabled !== 'boolean') {
156
+ throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
157
+ }
158
+ return { enabled }
159
+ }
160
+
161
+ /**
162
+ * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
163
+ * inherits the preset defaults; present-but-invalid is rejected, mirroring the
164
+ * codeSkeleton section semantics.
165
+ */
166
+ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
167
+ if (value === undefined) return undefined
168
+ if (!isPlainRecord(value)) {
169
+ throw new TypeError('Context-compression presetOptions must be a plain object')
170
+ }
171
+ const allowed = new Set([
172
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
173
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
174
+ // Legacy keys of the retired human-gated review pipeline. They stay in the
175
+ // ACCEPTED set on purpose: the keys are persisted in existing settings
176
+ // documents, and rejecting them would make this plugin fail to load on an
177
+ // upgrade. They are read by nothing — the gate they configured no longer
178
+ // exists, and a reduction never blocks automatic processing.
179
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
180
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
181
+ 'advisorMinTokens',
182
+ ])
183
+ const unknown = Object.keys(value).find(key => !allowed.has(key))
184
+ if (unknown !== undefined) {
185
+ throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`)
186
+ }
187
+ const booleans = ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const
188
+ for (const key of booleans) {
189
+ const entry = value[key]
190
+ if (entry !== undefined && typeof entry !== 'boolean') {
191
+ throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`)
192
+ }
193
+ }
194
+ const estimatorMode = value.estimatorMode
195
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
196
+ throw new TypeError('Context-compression presetOptions.estimatorMode must be "", "host", or "direct"')
197
+ }
198
+ const advisorMode = value.advisorMode
199
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
200
+ throw new TypeError('Context-compression presetOptions.advisorMode must be "", "host", or "direct"')
201
+ }
202
+ const advisorTimeoutMs = value.advisorTimeoutMs
203
+ if (advisorTimeoutMs !== undefined
204
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
205
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
206
+ throw new TypeError('Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000')
207
+ }
208
+ const advisorRefreshTurns = value.advisorRefreshTurns
209
+ if (advisorRefreshTurns !== undefined
210
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
211
+ || advisorRefreshTurns < 1)) {
212
+ throw new TypeError('Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1')
213
+ }
214
+ const advisorScoreThreshold = value.advisorScoreThreshold
215
+ if (advisorScoreThreshold !== undefined
216
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
217
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
218
+ throw new TypeError('Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1')
219
+ }
220
+ const advisorSampleLimit = value.advisorSampleLimit
221
+ if (advisorSampleLimit !== undefined
222
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
223
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
224
+ throw new TypeError('Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64')
225
+ }
226
+ const advisorMinTokens = value.advisorMinTokens
227
+ if (advisorMinTokens !== undefined
228
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
229
+ throw new TypeError('Context-compression presetOptions.advisorMinTokens must be a positive integer')
230
+ }
231
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
232
+ if (estimatorTimeoutMs !== undefined
233
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
234
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
235
+ throw new TypeError('Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000')
236
+ }
237
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
238
+ const entry = value[key]
239
+ if (entry !== undefined && typeof entry !== 'string') {
240
+ throw new TypeError(`Context-compression presetOptions.${key} must be a string`)
241
+ }
242
+ }
243
+ const result: {
244
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
245
+ } = {}
246
+ if (value.dedupeToolResults !== undefined) result.dedupeToolResults = value.dedupeToolResults as boolean
247
+ if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
248
+ if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
249
+ if (value.readState !== undefined) result.readState = value.readState as boolean
250
+ if (estimatorMode !== undefined) result.estimatorMode = estimatorMode as '' | 'host' | 'direct'
251
+ if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
252
+ if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
253
+ if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
254
+ if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
255
+ if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs as number
256
+ if (advisorMode !== undefined) result.advisorMode = advisorMode as '' | 'host' | 'direct'
257
+ if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs as number
258
+ if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns as number
259
+ if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold as number
260
+ if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit as number
261
+ if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens as number
262
+ return result
263
+ }
264
+
265
+ /** Settings schema used by the user-facing profile selector. */
266
+ const contextCompressionSettingsInputSchema = z.object({
267
+ profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
268
+ custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
269
+ })
270
+
271
+ /**
272
+ * Reject a section that is PRESENT but not a usable value. Schemastery
273
+ * `.default(...)` silently substitutes null and undefined, which would turn a
274
+ * hand-corrupted store into the (lossy) default policy; only genuinely absent
275
+ * keys may inherit defaults, and that distinction must be made before any
276
+ * default can fire.
277
+ */
278
+ function assertPresentSection(
279
+ candidate: Record<string, unknown>,
280
+ key: 'profile' | 'custom',
281
+ valid: (value: unknown) => boolean,
282
+ ): void {
283
+ if (!Object.hasOwn(candidate, key)) return
284
+ if (!valid(candidate[key])) {
285
+ throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`)
286
+ }
287
+ }
288
+
289
+ const isSupportedProfile = (value: unknown): boolean =>
290
+ typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
291
+
292
+ const isUsableCustomDocument = (value: unknown): boolean =>
293
+ isPlainRecord(value)
294
+
295
+ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
296
+ profile: 'balanced',
297
+ custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
298
+ autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
299
+ codeSkeleton: { enabled: false },
300
+ intentSummary: { enabled: false },
301
+ monitorPanel: { enabled: false },
302
+ }
303
+
304
+ /**
305
+ * Parse one settings document with the persisted-section semantics: `undefined`
306
+ * inherits the defaults (an absent section), while `null` is an explicitly
307
+ * invalid document and must never silently become the default policy.
308
+ */
309
+ export function parseContextCompressionSettings(value: unknown): ContextCompressionSettings {
310
+ if (!isPlainRecord(value)) {
311
+ throw new TypeError('Context-compression settings must be a plain object')
312
+ }
313
+ const keys = Object.keys(value)
314
+ // Documents surfaced by the settings service are always schema-resolved and
315
+ // complete; anything thinner is a hand-edited store and must not silently
316
+ // become a default (possibly lossy) policy.
317
+ if (keys.length === 0 || !keys.includes('profile') || !keys.includes('custom')) {
318
+ throw new TypeError('Context-compression settings document is missing its complete shape')
319
+ }
320
+ return ContextCompressionSettingsSchema(value as never)
321
+ }
322
+
323
+ /** Settings schema used by the user-facing profile selector. */
324
+ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z.transform(
325
+ z.any().required(),
326
+ (value: unknown): ContextCompressionSettings => {
327
+ if (!isPlainRecord(value)) {
328
+ throw new TypeError('Context-compression settings must be a plain object')
329
+ }
330
+ // Validate prototypes before cloning, then parse a detached mutable copy:
331
+ // SettingsProvider returns frozen records, while structuredClone would
332
+ // otherwise erase exotic prototypes before this boundary can reject them.
333
+ assertPlainDataTree(value)
334
+ const candidate = structuredClone(value)
335
+ // Settings stored before the autoCompact or codeSkeleton sections existed
336
+ // remain valid and inherit their defaults; the sections themselves stay
337
+ // strictly shaped.
338
+ const unknown = Object.keys(candidate).find(key =>
339
+ key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
340
+ if (unknown !== undefined) {
341
+ throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
342
+ }
343
+ // Present-but-invalid sections must never fall through to the Schemastery
344
+ // defaults below: `profile: null` silently becoming the lossy `balanced`
345
+ // default is exactly the corruption the lossless-off fallback exists for.
346
+ // Only genuinely absent sections (internal partial fallbacks) may inherit.
347
+ assertPresentSection(candidate, 'profile', isSupportedProfile)
348
+ assertPresentSection(candidate, 'custom', isUsableCustomDocument)
349
+ const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
350
+ const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
351
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
352
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
353
+ const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
354
+ return {
355
+ ...contextCompressionSettingsInputSchema(candidate),
356
+ autoCompact,
357
+ codeSkeleton,
358
+ intentSummary,
359
+ monitorPanel,
360
+ ...presetOptions === undefined ? {} : { presetOptions },
361
+ }
362
+ },
363
+ ).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS) as z<ContextCompressionSettings>
364
+
365
+ /** Low-friction defaults; token budgets live in resolved profile policy. */
366
+ export const DEFAULTS: ResolvedConfig = deepFreeze({
367
+ profile: 'balanced',
368
+ headChars: 4096,
369
+ tailChars: 1024,
370
+ })
371
+
372
+ const CONFIG_KEYS: ReadonlySet<string> = new Set([
373
+ 'profile',
374
+ 'headChars',
375
+ 'tailChars',
376
+ 'nativeTriggerTokens',
377
+ 'nativeTargetTokens',
378
+ 'freshTriggerTokens',
379
+ 'freshTargetTokens',
380
+ 'aggregateTriggerTokens',
381
+ 'aggregateTargetTokens',
382
+ 'historyTriggerTokens',
383
+ 'historyKeepRecentToolCalls',
384
+ 'historyKeepRecentTokens',
385
+ 'historyMinReclaimTokens',
386
+ 'readInputCapChars',
387
+ 'autoCompactThresholdPercent',
388
+ 'presetOptions',
389
+ ])
390
+
391
+ const LEGACY_GATE_REPLACEMENTS: Readonly<Record<string, string>> = Object.freeze({
392
+ thresholdChars: 'nativeTriggerTokens',
393
+ freshThresholdChars: 'freshTriggerTokens',
394
+ freshTargetChars: 'freshTargetTokens',
395
+ freshBatchTriggerChars: 'aggregateTriggerTokens',
396
+ freshBatchTargetChars: 'aggregateTargetTokens',
397
+ historyTriggerChars: 'historyTriggerTokens',
398
+ historyKeepRecentChars: 'historyKeepRecentTokens',
399
+ historyMinReclaimChars: 'historyMinReclaimTokens',
400
+ historyKeepRecentTurns: 'historyKeepRecentToolCalls',
401
+ })
402
+
403
+ /**
404
+ * Count Unicode code points without splitting surrogate pairs.
405
+ * @param text - text whose code points are counted.
406
+ * @returns the number of Unicode code points.
407
+ */
408
+ export function codePointLength(text: string): number {
409
+ let length = 0
410
+ for (const _point of text) length++
411
+ return length
412
+ }
413
+
414
+ /**
415
+ * Conservative upper bound on characters per token. Same convention the
416
+ * readInputCapChars invariant already uses (see resolvePolicy): English
417
+ * code runs approximately four characters per token at the upper bound.
418
+ */
419
+ export const CHARS_PER_TOKEN = 4.0
420
+
421
+ /** Express one token-named policy gate on the character basis. */
422
+ export function charsForTokens(tokens: number): number {
423
+ return tokens * CHARS_PER_TOKEN
424
+ }
425
+
426
+ /** Derive the telemetry-only token figure from a character measurement. */
427
+ export function charsToTokens(chars: number): number {
428
+ if (!Number.isFinite(chars) || chars <= 0) return 0
429
+ return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
430
+ }
431
+
432
+ /**
433
+ * Test whether a settings value names a supported compression profile.
434
+ * @param value - untrusted settings value.
435
+ * @returns whether the value is a supported compression profile.
436
+ */
437
+ export function isCompressionProfile(value: unknown): value is CompressionProfile {
438
+ return typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
439
+ }
440
+
441
+ /**
442
+ * Resolve and validate plugin configuration.
443
+ * @param config - optional composition overrides.
444
+ * @returns a detached, deeply immutable configuration snapshot.
445
+ */
446
+ export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfig {
447
+ for (const key of Object.keys(config)) {
448
+ const replacement = LEGACY_GATE_REPLACEMENTS[key]
449
+ if (replacement !== undefined) {
450
+ throw new Error(
451
+ `ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; `
452
+ + `choose "${replacement}" manually in tokens (no character conversion is applied)`,
453
+ )
454
+ }
455
+ if (!CONFIG_KEYS.has(key)) {
456
+ throw new Error(`ToolResultPruneConfig: unknown key "${key}"`)
457
+ }
458
+ }
459
+ const resolved: ResolvedConfig = {
460
+ profile: config.profile ?? DEFAULTS.profile,
461
+ headChars: config.headChars ?? DEFAULTS.headChars,
462
+ tailChars: config.tailChars ?? DEFAULTS.tailChars,
463
+ ...config.nativeTriggerTokens === undefined ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
464
+ ...config.nativeTargetTokens === undefined ? {} : { nativeTargetTokens: config.nativeTargetTokens },
465
+ ...config.freshTriggerTokens === undefined ? {} : { freshTriggerTokens: config.freshTriggerTokens },
466
+ ...config.freshTargetTokens === undefined ? {} : { freshTargetTokens: config.freshTargetTokens },
467
+ ...config.aggregateTriggerTokens === undefined ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
468
+ ...config.aggregateTargetTokens === undefined ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
469
+ ...config.historyTriggerTokens === undefined ? {} : { historyTriggerTokens: config.historyTriggerTokens },
470
+ ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
471
+ ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
472
+ ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
473
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
474
+ ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
475
+ ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
476
+ }
477
+ if (!isCompressionProfile(resolved.profile)) {
478
+ throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`)
479
+ }
480
+ assertNonNegativeInteger('headChars', resolved.headChars)
481
+ assertNonNegativeInteger('tailChars', resolved.tailChars)
482
+ for (const key of [
483
+ 'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
484
+ 'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
485
+ 'historyMinReclaimTokens', 'readInputCapChars',
486
+ ] as const) {
487
+ const value = resolved[key]
488
+ if (value !== undefined) assertPositiveInteger(key, value)
489
+ }
490
+ if (resolved.historyKeepRecentToolCalls !== undefined) {
491
+ assertNonNegativeInteger('historyKeepRecentToolCalls', resolved.historyKeepRecentToolCalls)
492
+ }
493
+ if (resolved.historyKeepRecentTokens !== undefined) {
494
+ assertNonNegativeInteger('historyKeepRecentTokens', resolved.historyKeepRecentTokens)
495
+ }
496
+ if (resolved.autoCompactThresholdPercent !== undefined
497
+ && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) {
498
+ throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
499
+ }
500
+ assertTargetBelowTrigger('native', resolved.nativeTargetTokens, resolved.nativeTriggerTokens)
501
+ assertTargetBelowTrigger('fresh', resolved.freshTargetTokens, resolved.freshTriggerTokens)
502
+ assertTargetBelowTrigger('aggregate', resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens)
503
+ return deepFreeze(structuredClone(resolved))
504
+ }
505
+
506
+ /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
507
+ const AUTO_COMPACT_HISTORY_RATIOS: Readonly<Record<string, Readonly<{
508
+ trigger: number
509
+ minReclaim: number
510
+ keepRecentTokens: number
511
+ }>>> = Object.freeze({
512
+ balanced: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
513
+ savings: Object.freeze({ trigger: 0.50, minReclaim: 0.16, keepRecentTokens: 0.08 }),
514
+ 'cache-strict': Object.freeze({ trigger: 0.75, minReclaim: 0.16, keepRecentTokens: 0.08 }),
515
+ adaptive: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
516
+ 'tokenpilot-inspired': Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
517
+ })
518
+
519
+ /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
520
+ const MICRO_DEADLINE_RATIO = 0.875
521
+
522
+ /**
523
+ * TokenPilot-inspired sub-capability defaults. Every capability is on except
524
+ * the estimator, which requires an explicit endpoint channel (host or direct)
525
+ * before any consumer may leave its rule-only fallback.
526
+ */
527
+ const PRESET_OPTION_DEFAULTS: PresetOptions = deepFreeze({
528
+ noNetSavingsGuard: true,
529
+ skipReductionRecovery: true,
530
+ dedupeToolResults: true,
531
+ summaryLocator: true,
532
+ prefixStabilizer: true,
533
+ readState: true,
534
+ estimator: { mode: '' },
535
+ // Advisory advisor ships off: statistics and suggestions only, never a gate.
536
+ advisor: {
537
+ mode: '',
538
+ timeoutMs: 8_000,
539
+ refreshTurns: 8,
540
+ scoreThreshold: 0.35,
541
+ sampleLimit: 16,
542
+ minTokens: 250,
543
+ },
544
+ })
545
+
546
+ /**
547
+ * Merge persisted presetOptions overrides over the tokenpilot-inspired
548
+ * defaults. Persisted booleans are three-state (undefined = inherit); the
549
+ * estimator channel overrides the default empty mode wholesale.
550
+ */
551
+ function mergePresetOptions(overrides: PresetOptionsSettings | undefined): PresetOptions {
552
+ if (overrides === undefined) return PRESET_OPTION_DEFAULTS
553
+ return deepFreeze({
554
+ noNetSavingsGuard: true,
555
+ skipReductionRecovery: true,
556
+ dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
557
+ summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
558
+ prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
559
+ readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
560
+ estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
561
+ advisor: {
562
+ mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
563
+ timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
564
+ refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
565
+ scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
566
+ sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
567
+ minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens,
568
+ },
569
+ })
570
+ }
571
+
572
+ /**
573
+ * Resolve the Auto-Compact-linked History watermarks for one standard profile.
574
+ *
575
+ * `A = floor(C × a)` is the Auto Compact token watermark for the routed
576
+ * context window `C` and the user threshold `a = p / 100`; the History
577
+ * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
578
+ * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
579
+ * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
580
+ * preset numbers exactly. Custom stays manual and Off/Native run no History,
581
+ * so none of them link.
582
+ */
583
+ function resolveAutoCompactLinkage(
584
+ profile: CompressionProfile,
585
+ options: CustomPolicyResolutionOptions,
586
+ ): { autoCompactTokens: number, microDeadlineTokens: number, historyTriggerTokens: number,
587
+ historyMinReclaimTokens: number, historyKeepRecentTokens: number } | undefined {
588
+ const ratios = profile === 'custom' ? undefined : AUTO_COMPACT_HISTORY_RATIOS[profile]
589
+ const contextWindow = options.contextWindowTokens
590
+ const threshold = options.autoCompactThresholdPercent
591
+ if (ratios === undefined) return undefined
592
+ if (!isValidAutoCompactThresholdPercent(threshold)) return undefined
593
+ if (!Number.isSafeInteger(contextWindow) || contextWindow === undefined || contextWindow <= 0) return undefined
594
+ // Mirror compaction-basic's evaluation order exactly: it multiplies by the
595
+ // generated ratio float (p / 100), and integer-first division differs by
596
+ // one token on some window/percent pairs (200k x 57).
597
+ const autoCompactTokens = Math.floor(contextWindow * (threshold / 100))
598
+ if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return undefined
599
+ const linked = {
600
+ autoCompactTokens,
601
+ microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
602
+ historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
603
+ historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
604
+ historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens),
605
+ }
606
+ for (const value of Object.values(linked)) {
607
+ if (!Number.isSafeInteger(value) || value <= 0) return undefined
608
+ }
609
+ return linked
610
+ }
611
+
612
+ /**
613
+ * Resolve one public profile into a complete mixed-strategy policy.
614
+ * @param config - validated composition configuration.
615
+ * @param profile - profile frozen for the target Session.
616
+ * @param custom - versioned Custom document used only by the `custom` profile.
617
+ * @param options - routed capacity and the frozen Auto Compact threshold used
618
+ * to resolve context-percent Custom values and standard-profile linkage.
619
+ * @returns the effective deterministic compression policy.
620
+ */
621
+ export function resolvePolicy(
622
+ config: ResolvedConfig,
623
+ profile: CompressionProfile,
624
+ custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
625
+ options: CustomPolicyResolutionOptions = {},
626
+ ): CompressionPolicy {
627
+ if (profile === 'custom') return resolveCustomPolicy(custom, options)
628
+ const presets: Record<Exclude<CompressionProfile, 'custom'>, Omit<CompressionPolicy, 'profile'>> = {
629
+ off: {
630
+ nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
631
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
632
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
633
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
634
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
635
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
636
+ },
637
+ native: {
638
+ nativeToolResultEnabled: true, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
639
+ nativeTriggerTokens: 4_096, nativeTargetTokens: 2_048,
640
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
641
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
642
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
643
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
644
+ },
645
+ balanced: {
646
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
647
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
648
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
649
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
650
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
651
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
652
+ },
653
+ 'cache-strict': {
654
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'capacity-pressure',
655
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
656
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
657
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
658
+ historyTriggerTokens: 600_000, historyKeepRecentToolCalls: 10,
659
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
660
+ },
661
+ savings: {
662
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
663
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
664
+ freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
665
+ aggregateTriggerTokens: 16_384, aggregateTargetTokens: 4_096,
666
+ historyTriggerTokens: 400_000, historyKeepRecentToolCalls: 10,
667
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
668
+ },
669
+ adaptive: {
670
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'adaptive',
671
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
672
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
673
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
674
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
675
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
676
+ },
677
+ 'tokenpilot-inspired': {
678
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
679
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
680
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
681
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
682
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
683
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
684
+ },
685
+ }
686
+ const preset = presets[profile]
687
+ const linkage = resolveAutoCompactLinkage(profile, options)
688
+ const policy: CompressionPolicy = {
689
+ profile,
690
+ ...preset,
691
+ nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
692
+ nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
693
+ freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
694
+ freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
695
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
696
+ aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
697
+ historyTriggerTokens: config.historyTriggerTokens
698
+ ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
699
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
700
+ historyKeepRecentTokens: config.historyKeepRecentTokens
701
+ ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
702
+ historyMinReclaimTokens: config.historyMinReclaimTokens
703
+ ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
704
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
705
+ ...linkage === undefined ? {} : {
706
+ autoCompactTokens: linkage.autoCompactTokens,
707
+ microDeadlineTokens: linkage.microDeadlineTokens,
708
+ },
709
+ ...profile === 'tokenpilot-inspired' ? {
710
+ presetOptions: mergePresetOptions(config.presetOptions),
711
+ } : {},
712
+ }
713
+ if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
714
+ throw new Error('context compression policy: native target must be below trigger')
715
+ }
716
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
717
+ throw new Error('context compression policy: fresh target must be below trigger')
718
+ }
719
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
720
+ throw new Error('context compression policy: aggregate target must be below trigger')
721
+ }
722
+ // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
723
+ // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
724
+ // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
725
+ // read result below the trigger and silently silence the fresh path.
726
+ if (policy.readInputCapChars !== undefined
727
+ && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
728
+ throw new Error('context compression policy: read input cap would silence the fresh path')
729
+ }
730
+ return deepFreeze(policy)
731
+ }
732
+
733
+ function assertTargetBelowTrigger(
734
+ label: string,
735
+ target: number | undefined,
736
+ trigger: number | undefined,
737
+ ): void {
738
+ if ((target === undefined) !== (trigger === undefined)) {
739
+ throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`)
740
+ }
741
+ if (target !== undefined && trigger !== undefined && target >= trigger) {
742
+ throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`)
743
+ }
744
+ }
745
+
746
+ function assertPositiveInteger(name: string, value: number): void {
747
+ if (!Number.isSafeInteger(value) || value <= 0) {
748
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`)
749
+ }
750
+ }
751
+
752
+ function assertNonNegativeInteger(name: string, value: number): void {
753
+ if (!Number.isSafeInteger(value) || value < 0) {
754
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`)
755
+ }
756
+ }