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

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 (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -1,205 +1,205 @@
1
- /** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
2
-
3
- import { createHash } from 'node:crypto'
4
- import { readFileSync } from 'node:fs'
5
- import { Tokenizer } from '@huggingface/tokenizers'
6
- import type { ExactTokenizerTokenCount } from './runtime/token-count.ts'
7
-
8
- const TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Pro'
9
- const TOKENIZER_REVISION = '0e1a0e5e52aea73055f50fef6f2423db370265b6'
10
- const TOKENIZER_SHA256 = '8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf'
11
- const CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
12
- const VISION_TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp'
13
- const VISION_TOKENIZER_REVISION = '6821d6ad3681a4b137b066b76094fa82ebd0a380'
14
- const VISION_TOKENIZER_SHA256 = 'c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b'
15
- const VISION_CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
16
-
17
- /** Auditable origin and compatibility mapping for one bundled tokenizer. */
18
- export interface DeepSeekTokenizerArtifactOrigin {
19
- /** Hugging Face repository the assets were pinned from. */
20
- readonly repository: string
21
- /** Immutable commit revision the assets were pinned from. */
22
- readonly revision: string
23
- /** Upstream license of the repository. */
24
- readonly license: string
25
- /** Exact API wire model ids served by this artifact. */
26
- readonly modelIds: readonly string[]
27
- readonly tokenizerSha256: string
28
- readonly tokenizerConfigSha256: string
29
- }
30
-
31
- /** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
32
- export const DEEPSEEK_V4_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
33
- repository: TOKENIZER_ID,
34
- revision: TOKENIZER_REVISION,
35
- license: 'MIT',
36
- tokenizerSha256: TOKENIZER_SHA256,
37
- tokenizerConfigSha256: CONFIG_SHA256,
38
- modelIds: Object.freeze(['deepseek-v4-flash', 'deepseek-v4-pro']),
39
- })
40
-
41
- /**
42
- * Auditable origin and compatibility mapping for the bundled V4 Flash Vision
43
- * tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
44
- * the `<|deepseek_image|>` special token), so the vision model must never be
45
- * mapped onto the V4 Pro tokenizer as an alias.
46
- */
47
- export const DEEPSEEK_VISION_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
48
- repository: VISION_TOKENIZER_ID,
49
- revision: VISION_TOKENIZER_REVISION,
50
- license: 'MIT',
51
- tokenizerSha256: VISION_TOKENIZER_SHA256,
52
- tokenizerConfigSha256: VISION_CONFIG_SHA256,
53
- modelIds: Object.freeze(['deepseek-v4-flash-vision-exp']),
54
- })
55
-
56
- /** Synchronous exact counter backed only by the verified local V4 artifacts. */
57
- export interface DeepSeekV4TextTokenizer {
58
- /** Count one fully determined text value with the official tokenizer. */
59
- countText(text: string): ExactTokenizerTokenCount
60
- }
61
-
62
- /** Integrity tuple for one tokenizer JSON asset. @internal */
63
- export interface DeepSeekV4TokenizerAssetDescriptor {
64
- readonly bytes: number
65
- readonly sha256: string
66
- }
67
-
68
- /** Injectable integrity manifest used by negative loader tests. @internal */
69
- export interface DeepSeekV4TokenizerAssetIntegrity {
70
- readonly tokenizer: DeepSeekV4TokenizerAssetDescriptor
71
- readonly config: DeepSeekV4TokenizerAssetDescriptor
72
- }
73
-
74
- interface TokenizerArtifact {
75
- readonly origin: DeepSeekTokenizerArtifactOrigin
76
- readonly assetRoot: URL
77
- readonly integrity: DeepSeekV4TokenizerAssetIntegrity
78
- }
79
-
80
- /**
81
- * Every bundled artifact is registered with independent asset roots, integrity
82
- * manifests, and cache entries: one corrupted artifact must never disable the
83
- * tokenizer serving the other model family.
84
- */
85
- const ARTIFACTS: readonly TokenizerArtifact[] = Object.freeze([
86
- Object.freeze({
87
- origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
88
- assetRoot: new URL('../assets/deepseek-v4/', import.meta.url),
89
- integrity: Object.freeze({
90
- tokenizer: Object.freeze({ bytes: 6_367_146, sha256: TOKENIZER_SHA256 }),
91
- config: Object.freeze({ bytes: 801, sha256: CONFIG_SHA256 }),
92
- }),
93
- }),
94
- Object.freeze({
95
- origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
96
- assetRoot: new URL('../assets/deepseek-v4-vision-exp/', import.meta.url),
97
- integrity: Object.freeze({
98
- tokenizer: Object.freeze({ bytes: 6_367_257, sha256: VISION_TOKENIZER_SHA256 }),
99
- config: Object.freeze({ bytes: 801, sha256: VISION_CONFIG_SHA256 }),
100
- }),
101
- }),
102
- ])
103
-
104
- interface ArtifactCacheEntry {
105
- readonly tokenizer?: DeepSeekV4TextTokenizer
106
- readonly failure?: string
107
- }
108
-
109
- const registryCache = new Map<DeepSeekTokenizerArtifactOrigin, ArtifactCacheEntry>()
110
-
111
- function artifactForModel(modelId: string): TokenizerArtifact | undefined {
112
- return ARTIFACTS.find(artifact => (artifact.origin.modelIds).includes(modelId))
113
- }
114
-
115
- /**
116
- * Resolve the shared offline tokenizer for one compatible API model.
117
- * Unknown models and a cached asset/runtime failure return `undefined`; callers
118
- * must report unavailable instead of manufacturing a character estimate.
119
- * @param modelId - exact DeepSeek API wire model id.
120
- * @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
121
- */
122
- export function deepSeekV4TokenizerForModel(modelId: string): DeepSeekV4TextTokenizer | undefined {
123
- const artifact = artifactForModel(modelId)
124
- if (artifact === undefined) return undefined
125
- const cached = registryCache.get(artifact.origin)
126
- if (cached !== undefined) return cached.tokenizer
127
- let entry: ArtifactCacheEntry
128
- try {
129
- const tokenizer = createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin)
130
- entry = { tokenizer }
131
- } catch (error: unknown) {
132
- entry = { failure: error instanceof Error ? error.message : String(error) }
133
- }
134
- registryCache.set(artifact.origin, entry)
135
- return entry.tokenizer
136
- }
137
-
138
- /**
139
- * Read the cached initialization diagnostic for provider registration.
140
- * @param modelId - optional exact model id; defaults to the V4 Pro artifact.
141
- * @returns the first initialization failure for that artifact, or undefined.
142
- */
143
- export function deepSeekV4TokenizerFailureReason(modelId?: string): string | undefined {
144
- const artifact = modelId === undefined ? ARTIFACTS[0] : artifactForModel(modelId)
145
- if (artifact === undefined) return undefined
146
- return registryCache.get(artifact.origin)?.failure
147
- }
148
-
149
- /** Complete pinned artifact inventory, in stable registration order. */
150
- export function deepSeekTokenizerArtifacts(): readonly DeepSeekTokenizerArtifactOrigin[] {
151
- return ARTIFACTS.map(artifact => artifact.origin)
152
- }
153
-
154
- /**
155
- * Build a tokenizer from one local asset directory after byte/hash validation.
156
- * This provider-private seam exists so tests can prove every failure branch
157
- * without mutating the committed artifact.
158
- * @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
159
- * @param integrity - expected byte length and SHA-256 for both files.
160
- * @param origin - auditable identity recorded on every returned count.
161
- * @returns a synchronous exact text counter.
162
- * @internal
163
- */
164
- export function createDeepSeekV4TokenizerFromAssets(
165
- assetRoot: URL,
166
- integrity: DeepSeekV4TokenizerAssetIntegrity,
167
- origin: DeepSeekTokenizerArtifactOrigin = DEEPSEEK_V4_TOKENIZER_ARTIFACT,
168
- ): DeepSeekV4TextTokenizer {
169
- const tokenizerJson = readVerifiedJson(assetRoot, 'tokenizer.json', integrity.tokenizer)
170
- const tokenizerConfig = readVerifiedJson(assetRoot, 'tokenizer_config.json', integrity.config)
171
- const runtime = new Tokenizer(tokenizerJson, tokenizerConfig)
172
- return Object.freeze({
173
- countText(text: string): ExactTokenizerTokenCount {
174
- const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length
175
- return Object.freeze({
176
- kind: 'exact-tokenizer',
177
- tokens,
178
- tokenizerId: origin.repository,
179
- tokenizerRevision: origin.revision,
180
- })
181
- },
182
- })
183
- }
184
-
185
- function readVerifiedJson(
186
- assetRoot: URL,
187
- name: string,
188
- descriptor: DeepSeekV4TokenizerAssetDescriptor,
189
- ): Record<string, unknown> {
190
- const bytes = readFileSync(new URL(name, assetRoot))
191
- if (bytes.byteLength !== descriptor.bytes) {
192
- throw new Error(
193
- `DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`,
194
- )
195
- }
196
- const actualSha256 = createHash('sha256').update(bytes).digest('hex')
197
- if (actualSha256 !== descriptor.sha256) {
198
- throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`)
199
- }
200
- const parsed: unknown = JSON.parse(bytes.toString('utf8'))
201
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
202
- throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`)
203
- }
204
- return parsed as Record<string, unknown>
205
- }
1
+ /** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
2
+
3
+ import { createHash } from 'node:crypto'
4
+ import { readFileSync } from 'node:fs'
5
+ import { Tokenizer } from '@huggingface/tokenizers'
6
+ import type { ExactTokenizerTokenCount } from './runtime/token-count.ts'
7
+
8
+ const TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Pro'
9
+ const TOKENIZER_REVISION = '0e1a0e5e52aea73055f50fef6f2423db370265b6'
10
+ const TOKENIZER_SHA256 = '8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf'
11
+ const CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
12
+ const VISION_TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp'
13
+ const VISION_TOKENIZER_REVISION = '6821d6ad3681a4b137b066b76094fa82ebd0a380'
14
+ const VISION_TOKENIZER_SHA256 = 'c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b'
15
+ const VISION_CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
16
+
17
+ /** Auditable origin and compatibility mapping for one bundled tokenizer. */
18
+ export interface DeepSeekTokenizerArtifactOrigin {
19
+ /** Hugging Face repository the assets were pinned from. */
20
+ readonly repository: string
21
+ /** Immutable commit revision the assets were pinned from. */
22
+ readonly revision: string
23
+ /** Upstream license of the repository. */
24
+ readonly license: string
25
+ /** Exact API wire model ids served by this artifact. */
26
+ readonly modelIds: readonly string[]
27
+ readonly tokenizerSha256: string
28
+ readonly tokenizerConfigSha256: string
29
+ }
30
+
31
+ /** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
32
+ export const DEEPSEEK_V4_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
33
+ repository: TOKENIZER_ID,
34
+ revision: TOKENIZER_REVISION,
35
+ license: 'MIT',
36
+ tokenizerSha256: TOKENIZER_SHA256,
37
+ tokenizerConfigSha256: CONFIG_SHA256,
38
+ modelIds: Object.freeze(['deepseek-v4-flash', 'deepseek-v4-pro']),
39
+ })
40
+
41
+ /**
42
+ * Auditable origin and compatibility mapping for the bundled V4 Flash Vision
43
+ * tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
44
+ * the `<|deepseek_image|>` special token), so the vision model must never be
45
+ * mapped onto the V4 Pro tokenizer as an alias.
46
+ */
47
+ export const DEEPSEEK_VISION_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
48
+ repository: VISION_TOKENIZER_ID,
49
+ revision: VISION_TOKENIZER_REVISION,
50
+ license: 'MIT',
51
+ tokenizerSha256: VISION_TOKENIZER_SHA256,
52
+ tokenizerConfigSha256: VISION_CONFIG_SHA256,
53
+ modelIds: Object.freeze(['deepseek-v4-flash-vision-exp']),
54
+ })
55
+
56
+ /** Synchronous exact counter backed only by the verified local V4 artifacts. */
57
+ export interface DeepSeekV4TextTokenizer {
58
+ /** Count one fully determined text value with the official tokenizer. */
59
+ countText(text: string): ExactTokenizerTokenCount
60
+ }
61
+
62
+ /** Integrity tuple for one tokenizer JSON asset. @internal */
63
+ export interface DeepSeekV4TokenizerAssetDescriptor {
64
+ readonly bytes: number
65
+ readonly sha256: string
66
+ }
67
+
68
+ /** Injectable integrity manifest used by negative loader tests. @internal */
69
+ export interface DeepSeekV4TokenizerAssetIntegrity {
70
+ readonly tokenizer: DeepSeekV4TokenizerAssetDescriptor
71
+ readonly config: DeepSeekV4TokenizerAssetDescriptor
72
+ }
73
+
74
+ interface TokenizerArtifact {
75
+ readonly origin: DeepSeekTokenizerArtifactOrigin
76
+ readonly assetRoot: URL
77
+ readonly integrity: DeepSeekV4TokenizerAssetIntegrity
78
+ }
79
+
80
+ /**
81
+ * Every bundled artifact is registered with independent asset roots, integrity
82
+ * manifests, and cache entries: one corrupted artifact must never disable the
83
+ * tokenizer serving the other model family.
84
+ */
85
+ const ARTIFACTS: readonly TokenizerArtifact[] = Object.freeze([
86
+ Object.freeze({
87
+ origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
88
+ assetRoot: new URL('../assets/deepseek-v4/', import.meta.url),
89
+ integrity: Object.freeze({
90
+ tokenizer: Object.freeze({ bytes: 6_367_146, sha256: TOKENIZER_SHA256 }),
91
+ config: Object.freeze({ bytes: 801, sha256: CONFIG_SHA256 }),
92
+ }),
93
+ }),
94
+ Object.freeze({
95
+ origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
96
+ assetRoot: new URL('../assets/deepseek-v4-vision-exp/', import.meta.url),
97
+ integrity: Object.freeze({
98
+ tokenizer: Object.freeze({ bytes: 6_367_257, sha256: VISION_TOKENIZER_SHA256 }),
99
+ config: Object.freeze({ bytes: 801, sha256: VISION_CONFIG_SHA256 }),
100
+ }),
101
+ }),
102
+ ])
103
+
104
+ interface ArtifactCacheEntry {
105
+ readonly tokenizer?: DeepSeekV4TextTokenizer
106
+ readonly failure?: string
107
+ }
108
+
109
+ const registryCache = new Map<DeepSeekTokenizerArtifactOrigin, ArtifactCacheEntry>()
110
+
111
+ function artifactForModel(modelId: string): TokenizerArtifact | undefined {
112
+ return ARTIFACTS.find(artifact => (artifact.origin.modelIds).includes(modelId))
113
+ }
114
+
115
+ /**
116
+ * Resolve the shared offline tokenizer for one compatible API model.
117
+ * Unknown models and a cached asset/runtime failure return `undefined`; callers
118
+ * must report unavailable instead of manufacturing a character estimate.
119
+ * @param modelId - exact DeepSeek API wire model id.
120
+ * @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
121
+ */
122
+ export function deepSeekV4TokenizerForModel(modelId: string): DeepSeekV4TextTokenizer | undefined {
123
+ const artifact = artifactForModel(modelId)
124
+ if (artifact === undefined) return undefined
125
+ const cached = registryCache.get(artifact.origin)
126
+ if (cached !== undefined) return cached.tokenizer
127
+ let entry: ArtifactCacheEntry
128
+ try {
129
+ const tokenizer = createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin)
130
+ entry = { tokenizer }
131
+ } catch (error: unknown) {
132
+ entry = { failure: error instanceof Error ? error.message : String(error) }
133
+ }
134
+ registryCache.set(artifact.origin, entry)
135
+ return entry.tokenizer
136
+ }
137
+
138
+ /**
139
+ * Read the cached initialization diagnostic for provider registration.
140
+ * @param modelId - optional exact model id; defaults to the V4 Pro artifact.
141
+ * @returns the first initialization failure for that artifact, or undefined.
142
+ */
143
+ export function deepSeekV4TokenizerFailureReason(modelId?: string): string | undefined {
144
+ const artifact = modelId === undefined ? ARTIFACTS[0] : artifactForModel(modelId)
145
+ if (artifact === undefined) return undefined
146
+ return registryCache.get(artifact.origin)?.failure
147
+ }
148
+
149
+ /** Complete pinned artifact inventory, in stable registration order. */
150
+ export function deepSeekTokenizerArtifacts(): readonly DeepSeekTokenizerArtifactOrigin[] {
151
+ return ARTIFACTS.map(artifact => artifact.origin)
152
+ }
153
+
154
+ /**
155
+ * Build a tokenizer from one local asset directory after byte/hash validation.
156
+ * This provider-private seam exists so tests can prove every failure branch
157
+ * without mutating the committed artifact.
158
+ * @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
159
+ * @param integrity - expected byte length and SHA-256 for both files.
160
+ * @param origin - auditable identity recorded on every returned count.
161
+ * @returns a synchronous exact text counter.
162
+ * @internal
163
+ */
164
+ export function createDeepSeekV4TokenizerFromAssets(
165
+ assetRoot: URL,
166
+ integrity: DeepSeekV4TokenizerAssetIntegrity,
167
+ origin: DeepSeekTokenizerArtifactOrigin = DEEPSEEK_V4_TOKENIZER_ARTIFACT,
168
+ ): DeepSeekV4TextTokenizer {
169
+ const tokenizerJson = readVerifiedJson(assetRoot, 'tokenizer.json', integrity.tokenizer)
170
+ const tokenizerConfig = readVerifiedJson(assetRoot, 'tokenizer_config.json', integrity.config)
171
+ const runtime = new Tokenizer(tokenizerJson, tokenizerConfig)
172
+ return Object.freeze({
173
+ countText(text: string): ExactTokenizerTokenCount {
174
+ const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length
175
+ return Object.freeze({
176
+ kind: 'exact-tokenizer',
177
+ tokens,
178
+ tokenizerId: origin.repository,
179
+ tokenizerRevision: origin.revision,
180
+ })
181
+ },
182
+ })
183
+ }
184
+
185
+ function readVerifiedJson(
186
+ assetRoot: URL,
187
+ name: string,
188
+ descriptor: DeepSeekV4TokenizerAssetDescriptor,
189
+ ): Record<string, unknown> {
190
+ const bytes = readFileSync(new URL(name, assetRoot))
191
+ if (bytes.byteLength !== descriptor.bytes) {
192
+ throw new Error(
193
+ `DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`,
194
+ )
195
+ }
196
+ const actualSha256 = createHash('sha256').update(bytes).digest('hex')
197
+ if (actualSha256 !== descriptor.sha256) {
198
+ throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`)
199
+ }
200
+ const parsed: unknown = JSON.parse(bytes.toString('utf8'))
201
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
202
+ throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`)
203
+ }
204
+ return parsed as Record<string, unknown>
205
+ }
@@ -3,6 +3,14 @@
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
4
  import z from '@deepseek-ai/schemastery'
5
5
  import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
6
+ import { getSavingsLedger } from './runtime/savings.ts'
7
+ import {
8
+ applySessionOverride,
9
+ buildMonitorSnapshot,
10
+ estimateSavingsPricing,
11
+ isSessionOverrideAction,
12
+ type AgentDefaultModelLike,
13
+ } from './runtime/monitor.ts'
6
14
  import type { ContextCompressionSettings } from './profiles.ts'
7
15
  import {
8
16
  CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
@@ -38,6 +46,17 @@ const ADVISOR_REPORT_ROUTES = [
38
46
  '/api/dsh-context-compression-improved/advisor-report',
39
47
  ] as const
40
48
 
49
+ // Savings stats: one read-only snapshot route, dual prefixed like the others.
50
+ const SAVINGS_ROUTES = [
51
+ '/endpoint/dsh-context-compression-improved/savings',
52
+ '/api/dsh-context-compression-improved/savings',
53
+ ] as const
54
+
55
+ const MONITOR_ROUTES = [
56
+ '/endpoint/dsh-context-compression-improved/monitor',
57
+ '/api/dsh-context-compression-improved/monitor',
58
+ ] as const
59
+
41
60
  /** Minimal face of the agents service: session id → agent (carrying the session). */
42
61
  interface AgentsServiceLike {
43
62
  get?(id: unknown): { session?: unknown } | undefined
@@ -176,11 +195,6 @@ interface WebServerLike {
176
195
  }
177
196
 
178
197
  /** The estimator-side service the catalog handler enriches its response with. */
179
- interface AgentDefaultModelLike {
180
- /** Current host model-group selection, when the service exposes one. */
181
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
182
- }
183
-
184
198
  function asWebServer(value: unknown): WebServerLike | undefined {
185
199
  if (typeof value !== 'object' || value === null) return undefined
186
200
  const candidate = value as { register?: unknown }
@@ -292,6 +306,191 @@ function registerEstimatorCatalogRoute(ctx: Context): void {
292
306
  log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
293
307
  }
294
308
 
309
+ /**
310
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
311
+ * offsets (negative savings — compressed content later re-read in full), and net,
312
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
313
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
314
+ * channels for both service arrival orders, single guarded registration).
315
+ */
316
+ function registerSavingsRoute(ctx: Context): void {
317
+ const readService = (name: string): unknown => {
318
+ try {
319
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
320
+ } catch {
321
+ return undefined
322
+ }
323
+ }
324
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
325
+ console[level](message, ...args)
326
+ }
327
+
328
+ let registered = false
329
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
330
+ if (registered) return
331
+ const handler = (req: unknown, res: unknown): void => {
332
+ const resTyped = res as {
333
+ writeHead: (code: number, headers?: Record<string, string>) => void
334
+ end: (body?: string) => void
335
+ }
336
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
337
+ let sessionId: string | undefined
338
+ try {
339
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
340
+ const raw = url.searchParams.get('sessionId')
341
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
342
+ } catch {
343
+ /* 无法解析的查询串 = 全会话聚合 */
344
+ }
345
+ const snapshot = getSavingsLedger().snapshot(sessionId)
346
+ const pricing = estimateSavingsPricing(readService, snapshot)
347
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
348
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
349
+ }
350
+ try {
351
+ const disposers = SAVINGS_ROUTES
352
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
353
+ .filter((off): off is () => void => typeof off === 'function')
354
+ registered = true
355
+ ctx.effect(
356
+ () => () => { for (const off of disposers) off() },
357
+ 'contextCompressionSelector.savings route',
358
+ )
359
+ log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
360
+ } catch (error) {
361
+ log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
362
+ }
363
+ }
364
+
365
+ const active = asWebServer(readService('webServer'))
366
+ if (active !== undefined) {
367
+ register(active, 'direct')
368
+ if (registered) return
369
+ }
370
+
371
+ ctx.inject(['webServer'], (injected) => {
372
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
373
+ if (webServer === undefined) {
374
+ log('warn', 'context-compression webServer exposes no register() — savings route not registered')
375
+ return
376
+ }
377
+ register(webServer, 'inject')
378
+ })
379
+ }
380
+
381
+ /**
382
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
383
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
384
+ * pricing) — the payload shape the panel polls;
385
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
386
+ * driving the exact state machine `/ctx-summary` drives.
387
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
388
+ * single guarded registration); the handler branches on `req.method` because
389
+ * the registration surface is method-agnostic.
390
+ */
391
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
392
+ export function registerMonitorRoute(ctx: Context): void {
393
+ const readService = (name: string): unknown => {
394
+ try {
395
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
396
+ } catch {
397
+ return undefined
398
+ }
399
+ }
400
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
401
+ console[level](message, ...args)
402
+ }
403
+
404
+ let registered = false
405
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
406
+ if (registered) return
407
+ const handler = (req: unknown, res: unknown): void => {
408
+ const resTyped = res as {
409
+ writeHead: (code: number, headers?: Record<string, string>) => void
410
+ end: (body?: string) => void
411
+ }
412
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
413
+ let sessionId: string | undefined
414
+ try {
415
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
416
+ const raw = url.searchParams.get('sessionId')
417
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
418
+ } catch {
419
+ /* 无法解析的查询串 = 全会话聚合 */
420
+ }
421
+ const method = String((req as { method?: string })?.method ?? 'GET').toUpperCase()
422
+ if (method === 'POST') {
423
+ const chunks: Buffer[] = []
424
+ let size = 0
425
+ let done = false
426
+ const respond = (status: number, body: Record<string, unknown>): void => {
427
+ if (done) return
428
+ done = true
429
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
430
+ resTyped.end(JSON.stringify(body))
431
+ }
432
+ const reqTyped = req as { on?: (event: string, cb: (chunk?: Buffer) => void) => void }
433
+ if (typeof reqTyped?.on !== 'function') {
434
+ respond(400, { ok: false, error: 'unreadable request body' })
435
+ return
436
+ }
437
+ reqTyped.on('data', (chunk?: Buffer) => {
438
+ size += chunk?.length ?? 0
439
+ if (size <= 4096) chunks.push(Buffer.from(chunk ?? new Uint8Array()))
440
+ })
441
+ reqTyped.on('end', () => {
442
+ let action: unknown
443
+ try {
444
+ action = (JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') as { action?: unknown }).action
445
+ } catch {
446
+ respond(400, { ok: false, error: 'monitor override action must be JSON' })
447
+ return
448
+ }
449
+ if (!isSessionOverrideAction(action)) {
450
+ respond(400, { ok: false, error: 'monitor override action must be "on" | "off" | "clear"' })
451
+ return
452
+ }
453
+ const { override } = applySessionOverride(sessionId ?? '', action)
454
+ respond(200, { ok: true, override: override ?? null, sessionScope: sessionId ?? null })
455
+ })
456
+ return
457
+ }
458
+ const snapshot = buildMonitorSnapshot(sessionId)
459
+ const pricing = estimateSavingsPricing(readService, snapshot)
460
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
461
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
462
+ }
463
+ try {
464
+ const disposers = MONITOR_ROUTES
465
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
466
+ .filter((off): off is () => void => typeof off === 'function')
467
+ registered = true
468
+ ctx.effect(
469
+ () => () => { for (const off of disposers) off() },
470
+ 'contextCompressionSelector.monitor route',
471
+ )
472
+ log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
473
+ } catch (error) {
474
+ log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
475
+ }
476
+ }
477
+
478
+ const active = asWebServer(readService('webServer'))
479
+ if (active !== undefined) {
480
+ register(active, 'direct')
481
+ if (registered) return
482
+ }
483
+
484
+ ctx.inject(['webServer'], (injected) => {
485
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
486
+ if (webServer === undefined) {
487
+ log('warn', 'context-compression webServer exposes no register() — monitor route not registered')
488
+ return
489
+ }
490
+ register(webServer, 'inject')
491
+ })
492
+ }
493
+
295
494
  /**
296
495
  * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
297
496
  * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
@@ -364,6 +563,9 @@ export function apply(ctx: Context, config: Config = {}): void {
364
563
  // top-level plugin fiber, not inside the isolated `toolResultPruner`
365
564
  // service, because the route is host-wide rather than per-pruner-instance.
366
565
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
566
+ // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
567
+ registerSavingsRoute(ctx)
568
+ registerMonitorRoute(ctx)
367
569
 
368
570
  // Advisory advisor: read-only decay/score/advice report (opt-in).
369
571
  if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)