dsh-context-compression-improved 0.5.5 → 0.5.7

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 (162) 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 +314 -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 -85
  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 +164 -160
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -21
  26. package/packages/selector/README.zh.md +24 -19
  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.js +733 -0
  34. package/packages/selector/lib/style.css +46 -46
  35. package/packages/selector/package.json +114 -114
  36. package/packages/selector/screenshots.json +3 -3
  37. package/packages/selector/src/client/CompressionProfileControls.tsx +226 -226
  38. package/packages/selector/src/client/CompressionProfileSelector.module.css +170 -170
  39. package/packages/selector/src/client/CompressionProfileSelector.tsx +83 -83
  40. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  41. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  42. package/packages/selector/src/client/decode.ts +49 -49
  43. package/packages/selector/src/client/index.ts +178 -149
  44. package/packages/selector/src/client/locales/de.ts +98 -0
  45. package/packages/selector/src/client/locales/es.ts +98 -0
  46. package/packages/selector/src/client/locales/fr.ts +98 -0
  47. package/packages/selector/src/client/locales/it.ts +98 -0
  48. package/packages/selector/src/client/locales/ja.ts +98 -0
  49. package/packages/selector/src/client/locales/ko.ts +98 -0
  50. package/packages/selector/src/client/locales/ru.ts +98 -0
  51. package/packages/selector/src/client/locales.ts +196 -196
  52. package/packages/selector/src/client/preset-options.ts +88 -88
  53. package/packages/selector/src/client/settings-section.tsx +124 -124
  54. package/packages/selector/src/css-modules.d.ts +6 -6
  55. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  56. package/packages/selector/src/estimator-catalog.ts +104 -104
  57. package/packages/selector/src/index.ts +463 -463
  58. package/packages/selector/src/invariant.ts +113 -113
  59. package/packages/selector/src/preset-overlay.ts +626 -626
  60. package/packages/selector/src/profiles.ts +394 -394
  61. package/packages/selector/src/pruner/content.ts +201 -201
  62. package/packages/selector/src/pruner/session.ts +94 -94
  63. package/packages/selector/src/pruner/state.ts +50 -50
  64. package/packages/selector/src/pruner/tuning.ts +23 -23
  65. package/packages/selector/src/pruner/types.ts +78 -78
  66. package/packages/selector/src/pruner.ts +2402 -2402
  67. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  68. package/packages/selector/src/runtime/audit.ts +286 -286
  69. package/packages/selector/src/runtime/config.ts +706 -706
  70. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  71. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  72. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  73. package/packages/selector/src/runtime/measurement.ts +436 -436
  74. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  75. package/packages/selector/src/runtime/retrieve.ts +457 -457
  76. package/packages/selector/src/runtime/session-events.ts +30 -30
  77. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  78. package/packages/selector/src/runtime/token-count.ts +72 -72
  79. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  80. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  81. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  82. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  83. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  84. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  85. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  86. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  87. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  88. package/packages/selector/src/runtime/toolclass.ts +103 -103
  89. package/packages/selector/src/runtime/types.ts +346 -346
  90. package/packages/selector/src/runtime/value.ts +48 -48
  91. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  92. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -213
  93. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  94. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +90 -90
  96. package/packages/selector/tests/custom-contract.client.spec.ts +204 -204
  97. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  98. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  99. package/packages/selector/tests/estimator-route-registration.host.spec.ts +188 -188
  100. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +206 -206
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  104. package/packages/selector/tests/profiles.client.spec.tsx +434 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  110. package/packages/selector/tests/runtime/audit.spec.ts +274 -274
  111. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  112. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  113. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  114. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  115. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  116. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  117. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  118. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  119. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  120. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  121. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  122. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  123. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  124. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  125. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  126. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  127. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  128. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  129. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  130. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  131. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  132. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  133. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  134. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  135. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  136. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  137. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  138. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  139. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  140. package/packages/selector/tests/settings-seat.client.spec.ts +118 -118
  141. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  142. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  143. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  144. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  145. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  146. package/packages/selector/tsconfig.json +11 -11
  147. package/packages/selector/tsdown.client.config.ts +102 -102
  148. package/packages/selector/tsdown.config.ts +20 -20
  149. package/pnpm-workspace.yaml +66 -66
  150. package/scripts/capture-profile-baseline.mjs +42 -42
  151. package/scripts/generate-tokenizer-fixtures.py +81 -81
  152. package/scripts/generate-vision-fixtures.py +208 -208
  153. package/scripts/packed-components-smoke.mjs +732 -732
  154. package/scripts/packed-install-e2e.mjs +1273 -1273
  155. package/scripts/toolclass-corpus-replay.mjs +281 -281
  156. package/scripts/verify-release.mjs +317 -317
  157. package/tests/TEST_INVENTORY.md +41 -41
  158. package/tsconfig.base.json +18 -18
  159. package/tsconfig.json +7 -7
  160. package/tsconfig.tests.json +15 -15
  161. package/vitest.built.config.ts +9 -9
  162. package/vitest.config.ts +43 -43
@@ -1,394 +1,394 @@
1
- /** Public context-compression choices shared by the Host schema and browser selector. */
2
- export const COMPRESSION_PROFILES = [
3
- 'off',
4
- 'native',
5
- 'balanced',
6
- 'cache-strict',
7
- 'savings',
8
- 'adaptive',
9
- 'tokenpilot-inspired',
10
- 'custom',
11
- ] as const
12
-
13
- /** One supported context-compression profile. */
14
- export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
-
16
- /** Single canonical unit stored by a version-1 browser Custom document. */
17
- export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
-
19
- /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
- export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
-
22
- /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
- export interface CustomCompressionBudget {
24
- enabled: boolean
25
- trigger: number
26
- target: number
27
- }
28
-
29
- /** Legacy browser representation of the Custom History working set. */
30
- export interface LegacyCustomHistoryPolicy {
31
- enabled: boolean
32
- trigger: number
33
- keepRecentTurns: number
34
- keepRecent: number
35
- minReclaim: number
36
- }
37
-
38
- /** Browser representation of Custom History tool-call and token-tail protection. */
39
- export interface CustomHistoryPolicy {
40
- enabled: boolean
41
- trigger: number
42
- keepRecentToolCalls: number
43
- keepRecentTokens: number
44
- minReclaim: number
45
- }
46
-
47
- /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
- export interface CustomTailTrimPolicy {
49
- enabled: boolean
50
- trigger: number
51
- }
52
-
53
- interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
- unit: CustomCompressionUnit
55
- fresh: CustomCompressionBudget
56
- aggregate: CustomCompressionBudget
57
- history: HistoryPolicy
58
- prefixPolicy: CustomPrefixPolicy
59
- }
60
-
61
- /** Legacy public Custom document; accepted and normalized before editing. */
62
- export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
- version: 1
64
- }
65
-
66
- /** Legacy Custom document with a default-disabled TailTrim stage. */
67
- export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
- version: 2
69
- tailTrim: CustomTailTrimPolicy
70
- }
71
-
72
- /** Public Custom document with tool-call working-set protection. */
73
- export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
- version: 3
75
- tailTrim: CustomTailTrimPolicy
76
- }
77
-
78
- /** Exact public Custom document accepted by the Host and browser boundary. */
79
- export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
-
81
- /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
- export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
- version: 3,
84
- unit: 'tokens',
85
- fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
- aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
- history: {
88
- enabled: true,
89
- trigger: 500_000,
90
- keepRecentToolCalls: 10,
91
- keepRecentTokens: 64_000,
92
- minReclaim: 96_000,
93
- },
94
- prefixPolicy: 'pressure-break',
95
- tailTrim: { enabled: false, trigger: 700_000 },
96
- }
97
-
98
- /** User-tunable Auto Compact coordination preferences. */
99
- export interface AutoCompactSettings {
100
- thresholdPercent: number
101
- }
102
-
103
- /**
104
- * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
- * runtime: independent of every profile, default off.
106
- */
107
- export interface CodeSkeletonSettings {
108
- enabled: boolean
109
- }
110
-
111
- /**
112
- * Decode the persisted codeSkeleton section with exactly the runtime schema's
113
- * strictness: absent means the lossless off default; present values must be a
114
- * plain object carrying only a boolean `enabled`. Anything else is invalid,
115
- * never silently coerced.
116
- */
117
- export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
118
- if (value === undefined) return { enabled: false }
119
- if (!isPlainRecord(value)) return undefined
120
- const keys = Object.keys(value)
121
- if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
122
- const enabled = (value as Record<string, unknown>).enabled
123
- return typeof enabled === 'boolean' ? { enabled } : undefined
124
- }
125
-
126
- /** Browser-safe mirror of the runtime presetOptions section. */
127
- export interface PresetOptionsSettings {
128
- readonly dedupeToolResults?: boolean
129
- readonly summaryLocator?: boolean
130
- readonly prefixStabilizer?: boolean
131
- readonly readState?: boolean
132
- readonly estimatorMode?: '' | 'host' | 'direct'
133
- readonly estimatorProvider?: string
134
- readonly estimatorModel?: string
135
- readonly estimatorBaseUrl?: string
136
- readonly estimatorApiKey?: string
137
- readonly estimatorTimeoutMs?: number
138
- /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
139
- readonly advisorMode?: '' | 'host' | 'direct'
140
- readonly advisorTimeoutMs?: number
141
- readonly advisorRefreshTurns?: number
142
- readonly advisorScoreThreshold?: number
143
- readonly advisorSampleLimit?: number
144
- readonly advisorMinTokens?: number
145
- }
146
-
147
- /**
148
- * Browser mirror of the runtime presetOptions section: absent inherits the
149
- * preset defaults (decodes to `undefined`); present values must be a plain
150
- * object carrying only the known keys with valid types.
151
- */
152
- export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
153
- if (value === undefined) return undefined
154
- if (!isPlainRecord(value)) return undefined
155
- const allowed = new Set([
156
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
157
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
158
- // Legacy keys of the retired review gate: still ACCEPTED so an existing
159
- // settings document keeps decoding (rejecting them would report the whole
160
- // card unreadable), and ignored — nothing reads them any more.
161
- 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
162
- 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
163
- 'advisorMinTokens',
164
- ])
165
- if (Object.keys(value).some(key => !allowed.has(key))) return undefined
166
- for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
167
- const entry = value[key]
168
- if (entry !== undefined && typeof entry !== 'boolean') return undefined
169
- }
170
- const estimatorMode = value.estimatorMode
171
- if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
172
- return undefined
173
- }
174
- const advisorMode = value.advisorMode
175
- if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
176
- return undefined
177
- }
178
- for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
179
- const entry = value[key]
180
- if (entry !== undefined && typeof entry !== 'string') return undefined
181
- }
182
- const estimatorTimeoutMs = value.estimatorTimeoutMs
183
- if (estimatorTimeoutMs !== undefined
184
- && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
185
- || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
186
- return undefined
187
- }
188
- const advisorTimeoutMs = value.advisorTimeoutMs
189
- if (advisorTimeoutMs !== undefined
190
- && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
191
- || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
192
- return undefined
193
- }
194
- const advisorRefreshTurns = value.advisorRefreshTurns
195
- if (advisorRefreshTurns !== undefined
196
- && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
197
- || advisorRefreshTurns < 1)) {
198
- return undefined
199
- }
200
- const advisorScoreThreshold = value.advisorScoreThreshold
201
- if (advisorScoreThreshold !== undefined
202
- && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
203
- || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
204
- return undefined
205
- }
206
- const advisorSampleLimit = value.advisorSampleLimit
207
- if (advisorSampleLimit !== undefined
208
- && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
209
- || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
210
- return undefined
211
- }
212
- const advisorMinTokens = value.advisorMinTokens
213
- if (advisorMinTokens !== undefined
214
- && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
215
- return undefined
216
- }
217
- const decoded: {
218
- -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
219
- } = {}
220
- if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
221
- if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
222
- if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
223
- if (value.readState !== undefined) decoded.readState = value.readState as boolean
224
- if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
225
- if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
226
- if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
227
- if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
228
- if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
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
236
- return decoded
237
- }
238
-
239
- /**
240
- * The one threshold contract shared by the UI, the persisted settings, and the
241
- * runtime resolver; mirrored browser-safe from the runtime package.
242
- */
243
- export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
244
- min: 50,
245
- max: 90,
246
- step: 1,
247
- default: 80,
248
- } as const)
249
-
250
- /** Narrow one unknown value to a valid Auto Compact threshold percent. */
251
- export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
252
- return typeof value === 'number'
253
- && Number.isSafeInteger(value)
254
- && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
255
- && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
256
- }
257
-
258
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
259
- export function isPlainRecord(value: unknown): value is Record<string, unknown> {
260
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
261
- const prototype = Object.getPrototypeOf(value) as object | null
262
- return prototype === Object.prototype || prototype === null
263
- }
264
-
265
- /**
266
- * Decode the persisted autoCompact section with exactly the runtime schema's
267
- * strictness: absent means the 80% default; present values must be a plain
268
- * object carrying only a valid `thresholdPercent`. Anything else is invalid,
269
- * never silently coerced.
270
- */
271
- export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
272
- if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
273
- if (!isPlainRecord(value)) return undefined
274
- const keys = Object.keys(value)
275
- if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
276
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
277
- return isValidAutoCompactThresholdPercent(thresholdPercent)
278
- ? { thresholdPercent }
279
- : undefined
280
- }
281
-
282
- /** Durable settings section owned by this package. */
283
- export interface ContextCompressionSettings {
284
- /** Default profile captured when each Session first reaches the pruner. */
285
- profile: CompressionProfile
286
- /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
287
- custom: CustomCompressionPolicy
288
- /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
289
- autoCompact: AutoCompactSettings
290
- /** Code-skeleton reducer gate captured independently of `profile`. */
291
- codeSkeleton: CodeSkeletonSettings
292
- /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
293
- presetOptions?: PresetOptionsSettings
294
- }
295
-
296
- /**
297
- * Narrow an unknown settings value to a complete supported Custom policy.
298
- * @param value - Candidate settings value received from the Host or edited locally.
299
- * @returns Whether the value is a relation-valid Custom policy.
300
- */
301
- export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
302
- if (!hasExactKeys(
303
- value,
304
- value !== null && typeof value === 'object' && 'version' in value && value.version === 1
305
- ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
306
- : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
307
- )) return false
308
- if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
309
- || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
310
- if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
311
- if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
312
- const modernHistory = value.version === 3
313
- if (!hasExactKeys(
314
- value.history,
315
- modernHistory
316
- ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
317
- : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
318
- )) return false
319
- if (typeof value.history.enabled !== 'boolean'
320
- || typeof value.history.trigger !== 'number'
321
- || typeof value.history.minReclaim !== 'number') return false
322
- const recent = modernHistory
323
- ? value.history.keepRecentTokens
324
- : value.history.keepRecent
325
- const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
326
- if (typeof recent !== 'number'
327
- || typeof calls !== 'number'
328
- || !Number.isSafeInteger(calls)
329
- || calls < 0) return false
330
- let tailTrimTrigger: number | undefined
331
- if (value.version !== 1) {
332
- const tailTrim = value.tailTrim
333
- if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
334
- || typeof tailTrim.enabled !== 'boolean'
335
- || typeof tailTrim.trigger !== 'number') return false
336
- tailTrimTrigger = tailTrim.trigger
337
- }
338
- const measured = [
339
- value.fresh.trigger, value.fresh.target,
340
- value.aggregate.trigger, value.aggregate.target,
341
- value.history.trigger, recent, value.history.minReclaim,
342
- ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
343
- ]
344
- if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
345
- if (value.fresh.trigger <= 0 || value.fresh.target <= 0
346
- || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
347
- || value.history.trigger <= 0 || recent < 0
348
- || value.history.minReclaim <= 0
349
- || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
350
- if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
351
- if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
352
- return value.fresh.target < value.fresh.trigger
353
- && value.aggregate.target < value.aggregate.trigger
354
- && value.history.minReclaim <= value.history.trigger
355
- }
356
-
357
- function isBudget(value: unknown): value is CustomCompressionBudget {
358
- return hasExactKeys(value, ['enabled', 'trigger', 'target'])
359
- && typeof value.enabled === 'boolean'
360
- && typeof value.trigger === 'number'
361
- && typeof value.target === 'number'
362
- }
363
-
364
- /**
365
- * Canonicalize one validated Custom document to version 3, mirroring the
366
- * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
367
- * boundaries hand the SAME complete document to the UI and the policy
368
- * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
369
- * and a v1 document gains the default-disabled TailTrim stage.
370
- */
371
- export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
372
- if (policy.version === 3) return structuredClone(policy)
373
- return {
374
- version: 3,
375
- unit: policy.unit,
376
- fresh: structuredClone(policy.fresh),
377
- aggregate: structuredClone(policy.aggregate),
378
- history: {
379
- enabled: policy.history.enabled,
380
- trigger: policy.history.trigger,
381
- keepRecentToolCalls: 10,
382
- keepRecentTokens: policy.history.keepRecent,
383
- minReclaim: policy.history.minReclaim,
384
- },
385
- prefixPolicy: policy.prefixPolicy,
386
- tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
387
- }
388
- }
389
-
390
- function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
391
- if (!isPlainRecord(value)) return false
392
- const keys = Object.keys(value)
393
- return keys.length === expected.length && keys.every(key => expected.includes(key))
394
- }
1
+ /** Public context-compression choices shared by the Host schema and browser selector. */
2
+ export const COMPRESSION_PROFILES = [
3
+ 'off',
4
+ 'native',
5
+ 'balanced',
6
+ 'cache-strict',
7
+ 'savings',
8
+ 'adaptive',
9
+ 'tokenpilot-inspired',
10
+ 'custom',
11
+ ] as const
12
+
13
+ /** One supported context-compression profile. */
14
+ export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
+
16
+ /** Single canonical unit stored by a version-1 browser Custom document. */
17
+ export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
+
19
+ /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
+ export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
+
22
+ /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
+ export interface CustomCompressionBudget {
24
+ enabled: boolean
25
+ trigger: number
26
+ target: number
27
+ }
28
+
29
+ /** Legacy browser representation of the Custom History working set. */
30
+ export interface LegacyCustomHistoryPolicy {
31
+ enabled: boolean
32
+ trigger: number
33
+ keepRecentTurns: number
34
+ keepRecent: number
35
+ minReclaim: number
36
+ }
37
+
38
+ /** Browser representation of Custom History tool-call and token-tail protection. */
39
+ export interface CustomHistoryPolicy {
40
+ enabled: boolean
41
+ trigger: number
42
+ keepRecentToolCalls: number
43
+ keepRecentTokens: number
44
+ minReclaim: number
45
+ }
46
+
47
+ /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
+ export interface CustomTailTrimPolicy {
49
+ enabled: boolean
50
+ trigger: number
51
+ }
52
+
53
+ interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
+ unit: CustomCompressionUnit
55
+ fresh: CustomCompressionBudget
56
+ aggregate: CustomCompressionBudget
57
+ history: HistoryPolicy
58
+ prefixPolicy: CustomPrefixPolicy
59
+ }
60
+
61
+ /** Legacy public Custom document; accepted and normalized before editing. */
62
+ export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
+ version: 1
64
+ }
65
+
66
+ /** Legacy Custom document with a default-disabled TailTrim stage. */
67
+ export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
+ version: 2
69
+ tailTrim: CustomTailTrimPolicy
70
+ }
71
+
72
+ /** Public Custom document with tool-call working-set protection. */
73
+ export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
+ version: 3
75
+ tailTrim: CustomTailTrimPolicy
76
+ }
77
+
78
+ /** Exact public Custom document accepted by the Host and browser boundary. */
79
+ export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
+
81
+ /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
+ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
+ version: 3,
84
+ unit: 'tokens',
85
+ fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
+ aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
+ history: {
88
+ enabled: true,
89
+ trigger: 500_000,
90
+ keepRecentToolCalls: 10,
91
+ keepRecentTokens: 64_000,
92
+ minReclaim: 96_000,
93
+ },
94
+ prefixPolicy: 'pressure-break',
95
+ tailTrim: { enabled: false, trigger: 700_000 },
96
+ }
97
+
98
+ /** User-tunable Auto Compact coordination preferences. */
99
+ export interface AutoCompactSettings {
100
+ thresholdPercent: number
101
+ }
102
+
103
+ /**
104
+ * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
+ * runtime: independent of every profile, default off.
106
+ */
107
+ export interface CodeSkeletonSettings {
108
+ enabled: boolean
109
+ }
110
+
111
+ /**
112
+ * Decode the persisted codeSkeleton section with exactly the runtime schema's
113
+ * strictness: absent means the lossless off default; present values must be a
114
+ * plain object carrying only a boolean `enabled`. Anything else is invalid,
115
+ * never silently coerced.
116
+ */
117
+ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
118
+ if (value === undefined) return { enabled: false }
119
+ if (!isPlainRecord(value)) return undefined
120
+ const keys = Object.keys(value)
121
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
122
+ const enabled = (value as Record<string, unknown>).enabled
123
+ return typeof enabled === 'boolean' ? { enabled } : undefined
124
+ }
125
+
126
+ /** Browser-safe mirror of the runtime presetOptions section. */
127
+ export interface PresetOptionsSettings {
128
+ readonly dedupeToolResults?: boolean
129
+ readonly summaryLocator?: boolean
130
+ readonly prefixStabilizer?: boolean
131
+ readonly readState?: boolean
132
+ readonly estimatorMode?: '' | 'host' | 'direct'
133
+ readonly estimatorProvider?: string
134
+ readonly estimatorModel?: string
135
+ readonly estimatorBaseUrl?: string
136
+ readonly estimatorApiKey?: string
137
+ readonly estimatorTimeoutMs?: number
138
+ /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
139
+ readonly advisorMode?: '' | 'host' | 'direct'
140
+ readonly advisorTimeoutMs?: number
141
+ readonly advisorRefreshTurns?: number
142
+ readonly advisorScoreThreshold?: number
143
+ readonly advisorSampleLimit?: number
144
+ readonly advisorMinTokens?: number
145
+ }
146
+
147
+ /**
148
+ * Browser mirror of the runtime presetOptions section: absent inherits the
149
+ * preset defaults (decodes to `undefined`); present values must be a plain
150
+ * object carrying only the known keys with valid types.
151
+ */
152
+ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
153
+ if (value === undefined) return undefined
154
+ if (!isPlainRecord(value)) return undefined
155
+ const allowed = new Set([
156
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
157
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
158
+ // Legacy keys of the retired review gate: still ACCEPTED so an existing
159
+ // settings document keeps decoding (rejecting them would report the whole
160
+ // card unreadable), and ignored — nothing reads them any more.
161
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
162
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
163
+ 'advisorMinTokens',
164
+ ])
165
+ if (Object.keys(value).some(key => !allowed.has(key))) return undefined
166
+ for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
167
+ const entry = value[key]
168
+ if (entry !== undefined && typeof entry !== 'boolean') return undefined
169
+ }
170
+ const estimatorMode = value.estimatorMode
171
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
172
+ return undefined
173
+ }
174
+ const advisorMode = value.advisorMode
175
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
176
+ return undefined
177
+ }
178
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
179
+ const entry = value[key]
180
+ if (entry !== undefined && typeof entry !== 'string') return undefined
181
+ }
182
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
183
+ if (estimatorTimeoutMs !== undefined
184
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
185
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
186
+ return undefined
187
+ }
188
+ const advisorTimeoutMs = value.advisorTimeoutMs
189
+ if (advisorTimeoutMs !== undefined
190
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
191
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
192
+ return undefined
193
+ }
194
+ const advisorRefreshTurns = value.advisorRefreshTurns
195
+ if (advisorRefreshTurns !== undefined
196
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
197
+ || advisorRefreshTurns < 1)) {
198
+ return undefined
199
+ }
200
+ const advisorScoreThreshold = value.advisorScoreThreshold
201
+ if (advisorScoreThreshold !== undefined
202
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
203
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
204
+ return undefined
205
+ }
206
+ const advisorSampleLimit = value.advisorSampleLimit
207
+ if (advisorSampleLimit !== undefined
208
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
209
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
210
+ return undefined
211
+ }
212
+ const advisorMinTokens = value.advisorMinTokens
213
+ if (advisorMinTokens !== undefined
214
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
215
+ return undefined
216
+ }
217
+ const decoded: {
218
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
219
+ } = {}
220
+ if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
221
+ if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
222
+ if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
223
+ if (value.readState !== undefined) decoded.readState = value.readState as boolean
224
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
225
+ if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
226
+ if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
227
+ if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
228
+ if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
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
236
+ return decoded
237
+ }
238
+
239
+ /**
240
+ * The one threshold contract shared by the UI, the persisted settings, and the
241
+ * runtime resolver; mirrored browser-safe from the runtime package.
242
+ */
243
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
244
+ min: 50,
245
+ max: 90,
246
+ step: 1,
247
+ default: 80,
248
+ } as const)
249
+
250
+ /** Narrow one unknown value to a valid Auto Compact threshold percent. */
251
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
252
+ return typeof value === 'number'
253
+ && Number.isSafeInteger(value)
254
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
255
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
256
+ }
257
+
258
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
259
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
260
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
261
+ const prototype = Object.getPrototypeOf(value) as object | null
262
+ return prototype === Object.prototype || prototype === null
263
+ }
264
+
265
+ /**
266
+ * Decode the persisted autoCompact section with exactly the runtime schema's
267
+ * strictness: absent means the 80% default; present values must be a plain
268
+ * object carrying only a valid `thresholdPercent`. Anything else is invalid,
269
+ * never silently coerced.
270
+ */
271
+ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
272
+ if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
273
+ if (!isPlainRecord(value)) return undefined
274
+ const keys = Object.keys(value)
275
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
276
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
277
+ return isValidAutoCompactThresholdPercent(thresholdPercent)
278
+ ? { thresholdPercent }
279
+ : undefined
280
+ }
281
+
282
+ /** Durable settings section owned by this package. */
283
+ export interface ContextCompressionSettings {
284
+ /** Default profile captured when each Session first reaches the pruner. */
285
+ profile: CompressionProfile
286
+ /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
287
+ custom: CustomCompressionPolicy
288
+ /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
289
+ autoCompact: AutoCompactSettings
290
+ /** Code-skeleton reducer gate captured independently of `profile`. */
291
+ codeSkeleton: CodeSkeletonSettings
292
+ /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
293
+ presetOptions?: PresetOptionsSettings
294
+ }
295
+
296
+ /**
297
+ * Narrow an unknown settings value to a complete supported Custom policy.
298
+ * @param value - Candidate settings value received from the Host or edited locally.
299
+ * @returns Whether the value is a relation-valid Custom policy.
300
+ */
301
+ export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
302
+ if (!hasExactKeys(
303
+ value,
304
+ value !== null && typeof value === 'object' && 'version' in value && value.version === 1
305
+ ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
306
+ : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
307
+ )) return false
308
+ if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
309
+ || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
310
+ if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
311
+ if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
312
+ const modernHistory = value.version === 3
313
+ if (!hasExactKeys(
314
+ value.history,
315
+ modernHistory
316
+ ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
317
+ : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
318
+ )) return false
319
+ if (typeof value.history.enabled !== 'boolean'
320
+ || typeof value.history.trigger !== 'number'
321
+ || typeof value.history.minReclaim !== 'number') return false
322
+ const recent = modernHistory
323
+ ? value.history.keepRecentTokens
324
+ : value.history.keepRecent
325
+ const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
326
+ if (typeof recent !== 'number'
327
+ || typeof calls !== 'number'
328
+ || !Number.isSafeInteger(calls)
329
+ || calls < 0) return false
330
+ let tailTrimTrigger: number | undefined
331
+ if (value.version !== 1) {
332
+ const tailTrim = value.tailTrim
333
+ if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
334
+ || typeof tailTrim.enabled !== 'boolean'
335
+ || typeof tailTrim.trigger !== 'number') return false
336
+ tailTrimTrigger = tailTrim.trigger
337
+ }
338
+ const measured = [
339
+ value.fresh.trigger, value.fresh.target,
340
+ value.aggregate.trigger, value.aggregate.target,
341
+ value.history.trigger, recent, value.history.minReclaim,
342
+ ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
343
+ ]
344
+ if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
345
+ if (value.fresh.trigger <= 0 || value.fresh.target <= 0
346
+ || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
347
+ || value.history.trigger <= 0 || recent < 0
348
+ || value.history.minReclaim <= 0
349
+ || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
350
+ if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
351
+ if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
352
+ return value.fresh.target < value.fresh.trigger
353
+ && value.aggregate.target < value.aggregate.trigger
354
+ && value.history.minReclaim <= value.history.trigger
355
+ }
356
+
357
+ function isBudget(value: unknown): value is CustomCompressionBudget {
358
+ return hasExactKeys(value, ['enabled', 'trigger', 'target'])
359
+ && typeof value.enabled === 'boolean'
360
+ && typeof value.trigger === 'number'
361
+ && typeof value.target === 'number'
362
+ }
363
+
364
+ /**
365
+ * Canonicalize one validated Custom document to version 3, mirroring the
366
+ * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
367
+ * boundaries hand the SAME complete document to the UI and the policy
368
+ * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
369
+ * and a v1 document gains the default-disabled TailTrim stage.
370
+ */
371
+ export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
372
+ if (policy.version === 3) return structuredClone(policy)
373
+ return {
374
+ version: 3,
375
+ unit: policy.unit,
376
+ fresh: structuredClone(policy.fresh),
377
+ aggregate: structuredClone(policy.aggregate),
378
+ history: {
379
+ enabled: policy.history.enabled,
380
+ trigger: policy.history.trigger,
381
+ keepRecentToolCalls: 10,
382
+ keepRecentTokens: policy.history.keepRecent,
383
+ minReclaim: policy.history.minReclaim,
384
+ },
385
+ prefixPolicy: policy.prefixPolicy,
386
+ tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
387
+ }
388
+ }
389
+
390
+ function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
391
+ if (!isPlainRecord(value)) return false
392
+ const keys = Object.keys(value)
393
+ return keys.length === expected.length && keys.every(key => expected.includes(key))
394
+ }