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,463 +1,673 @@
1
- /** Host owner of the context-compression preference consumed by the browser selector. */
2
-
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import z from '@deepseek-ai/schemastery'
5
- import {
6
- type SettingsScope,
7
- type default as SettingsService,
8
- } from '@deepseek-ai/dsh-settings'
9
- import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
10
- import {
11
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
12
- ContextCompressionSettingsSchema,
13
- } from './runtime/config.ts'
14
-
15
- import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
16
-
17
- // The settings namespace literal and the settings schema are owned by the
18
- // runtime config module. Both were once inlined/replaced here to dodge a
19
- // cross-package dependency (ab2175a: the namespace literal was duplicated and
20
- // the schema was downgraded to `z.any()`); the runtime is now part of this
21
- // package, so the real schema is back and the daily Custom defaults are
22
- // published again through settings.register(). The namespace value is
23
- // unchanged ('context-compression').
24
- const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never
25
- import {
26
- decorateAgentPresets,
27
- resolveCompressionModulePaths,
28
- } from './preset-overlay.ts'
29
-
30
- // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
31
- // absolute paths are registered (each is its own (kind, path) table entry) and
32
- // one handler serves both prefixes. The bundled client only probes /api.
33
- const ESTIMATOR_CATALOG_ROUTES = [
34
- '/endpoint/dsh-context-compression-improved/estimator-catalog',
35
- '/api/dsh-context-compression-improved/estimator-catalog',
36
- ] as const
37
-
38
- // Advisory advisor: one read-only report route, dual prefixed like the others.
39
- const ADVISOR_REPORT_ROUTES = [
40
- '/endpoint/dsh-context-compression-improved/advisor-report',
41
- '/api/dsh-context-compression-improved/advisor-report',
42
- ] as const
43
-
44
- /** Minimal face of the agents service: session id → agent (carrying the session). */
45
- interface AgentsServiceLike {
46
- get?(id: unknown): { session?: unknown } | undefined
47
- }
48
-
49
- function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
50
- const agents = readService('agents') as AgentsServiceLike | undefined
51
- return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
52
- }
53
-
54
- function jsonResponse(res: unknown, status: number, body: unknown): void {
55
- const resTyped = res as {
56
- writeHead: (code: number, headers?: Record<string, string>) => void
57
- end: (body?: string) => void
58
- }
59
- resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
60
- resTyped.end(JSON.stringify(body))
61
- }
62
-
63
- /**
64
- * Serve the advisory advisor's read-only report route (same registration
65
- * skeleton as the estimator-catalog route):
66
- *
67
- * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
68
- * the todolist-bound task summary, and the score distribution. Content-free
69
- * by construction: task semantics are LLM-derived summaries, never message
70
- * text, and no score reason or candidate preview is ever returned.
71
- * Unknown session → 404; no agents service → 503. A session whose advisor
72
- * never ran reports nulls and empty arrays, not an error.
73
- */
74
- function registerAdvisorReportRoute(ctx: Context): void {
75
- const readService = (name: string): unknown => {
76
- try {
77
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
78
- } catch {
79
- return undefined
80
- }
81
- }
82
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
83
- console[level](message, ...args)
84
- }
85
-
86
- const getHandler = (req: unknown, res: unknown): void => {
87
- const agents = readService('agents') as AgentsServiceLike | undefined
88
- if (typeof agents?.get !== 'function') {
89
- jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
90
- return
91
- }
92
- let sessionId = ''
93
- try {
94
- const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
95
- sessionId = url.searchParams.get('sessionId') ?? ''
96
- } catch {
97
- // Malformed URL: fall through with the empty sessionId already set.
98
- }
99
- if (sessionId === '') {
100
- jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
101
- return
102
- }
103
- const session = sessionFor(readService, sessionId)
104
- if (session === undefined) {
105
- jsonResponse(res, 404, { ok: false, error: 'unknown session' })
106
- return
107
- }
108
- const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
109
- jsonResponse(res, 200, {
110
- ok: true,
111
- sessionId,
112
- advisor: {
113
- summary: state.summary ?? null,
114
- decay: state.lastDecay?.decay ?? null,
115
- weightedChars: state.lastDecay?.weightedChars ?? null,
116
- decayTurn: state.lastDecay?.turn ?? null,
117
- scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
118
- lowRelevanceSeqs: [...state.recertified.keys()],
119
- // The benefit model's label of the last landed batch — advice, never a
120
- // gate: the batch it describes landed regardless of the band.
121
- lastAdvice: state.lastAdvice === undefined
122
- ? null
123
- : {
124
- band: state.lastAdvice.band,
125
- turn: state.lastAdvice.turn,
126
- itemSeqs: state.lastAdvice.itemSeqs,
127
- recoveredTokens: state.lastAdvice.recoveredTokens,
128
- penaltyTokens: state.lastAdvice.penaltyTokens,
129
- paybackTurns: state.lastAdvice.paybackTurns ?? null,
130
- },
131
- },
132
- })
133
- }
134
-
135
- const register = (webServer: WebServerLike): void => {
136
- const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
137
- const disposers = table
138
- .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
139
- .filter((off): off is () => void => typeof off === 'function')
140
- ctx.effect(
141
- () => () => { for (const off of disposers) off() },
142
- 'contextCompressionSelector.advisor report route',
143
- )
144
- log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
145
- }
146
-
147
- const active = asWebServer(readService('webServer'))
148
- if (active !== undefined) {
149
- register(active)
150
- return
151
- }
152
-
153
- ctx.inject(['webServer'], (injected) => {
154
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
155
- if (webServer === undefined) {
156
- log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
157
- return
158
- }
159
- register(webServer)
160
- })
161
-
162
- log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
163
- }
164
-
165
- /**
166
- * The one service the catalog route actually needs. `llm` and
167
- * `agentDefaultModel` are payload enrichment the handler resolves per request,
168
- * never reasons to withhold the route.
169
- */
170
- const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
171
-
172
- /** The minimal face of the DSH `webServer` service this plugin uses. */
173
- interface WebServerLike {
174
- register(route: {
175
- kind: 'exact'
176
- path: string
177
- handler: (req: unknown, res: unknown) => unknown
178
- }): () => void
179
- }
180
-
181
- /** The estimator-side service the catalog handler enriches its response with. */
182
- interface AgentDefaultModelLike {
183
- /** Current host model-group selection, when the service exposes one. */
184
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
185
- }
186
-
187
- function asWebServer(value: unknown): WebServerLike | undefined {
188
- if (typeof value !== 'object' || value === null) return undefined
189
- const candidate = value as { register?: unknown }
190
- // Hand back the service itself -- never a wrapper re-exporting `register`.
191
- // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
192
- // so a detached call makes `this` the wrapper and throws "Cannot read
193
- // properties of undefined (reading 'has')" inside the host, after which the
194
- // route is simply absent and the client sees a bare 404. The 0.1.5 branch
195
- // never had that defect; take this implementation, not the 0.1.2 history's.
196
- return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
197
- }
198
-
199
- /**
200
- * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
201
- * settings card's host-route dropdowns (live provider/model groups from the DSH
202
- * `llm` service plus the effective selection). Best effort: without the
203
- * `webServer` service the plugin keeps working, only the HTTP API is missing.
204
- *
205
- * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
206
- * enrich the response and are resolved per request, so listing them here would
207
- * let an estimator-side service the handler never needs keep the route
208
- * unregistered. That failure is silent by construction — an unsatisfied
209
- * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
210
- * every request falls through to the host 404.
211
- *
212
- * Two channels cover the two arrival orders: a direct lookup catches a
213
- * `webServer` that is already active when the plugin loads, and `ctx.inject`
214
- * catches one that activates later. Both funnel into a single guarded
215
- * registration, because a late-arriving service must not re-register a
216
- * `(kind, path)` the host treats as a composition-contract violation.
217
- */
218
- function registerEstimatorCatalogRoute(ctx: Context): void {
219
- const readService = (name: string): unknown => {
220
- try {
221
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
222
- } catch {
223
- return undefined
224
- }
225
- }
226
- // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
227
- // surfaces no plugin output in the `dsh web` terminal at all — a full boot
228
- // produced zero plugin log lines while the process itself stayed chatty — so
229
- // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
230
- // uses `console.warn` for the same message class on the same host.
231
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
232
- console[level](message, ...args)
233
- }
234
-
235
- let registered = false
236
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
237
- if (registered) return
238
- const handler = (_req: unknown, res: unknown): void => {
239
- const resTyped = res as {
240
- writeHead: (code: number, headers?: Record<string, string>) => void
241
- end: (body?: string) => void
242
- }
243
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
244
- const llm = readService('llm')
245
- const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
246
- const deps: EstimatorCatalogDeps = {
247
- ...(llm === undefined
248
- ? {}
249
- : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
250
- ...(typeof defaults?.currentSelection === 'function'
251
- ? { currentSelection: () => defaults.currentSelection?.() }
252
- : {}),
253
- }
254
- buildEstimatorCatalog(deps).then(
255
- catalog => {
256
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
257
- resTyped.end(JSON.stringify({ ok: true, ...catalog }))
258
- },
259
- (error: unknown) => {
260
- resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
261
- resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
262
- },
263
- )
264
- }
265
- try {
266
- const disposers = ESTIMATOR_CATALOG_ROUTES
267
- .map(path => webServer.register({ kind: 'exact', path, handler }))
268
- .filter((off): off is () => void => typeof off === 'function')
269
- registered = true
270
- ctx.effect(
271
- () => () => { for (const off of disposers) off() },
272
- 'contextCompressionSelector.estimator-catalog route',
273
- )
274
- log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
275
- } catch (error) {
276
- log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
277
- }
278
- }
279
-
280
- const active = asWebServer(readService('webServer'))
281
- if (active !== undefined) {
282
- register(active, 'direct')
283
- if (registered) return
284
- }
285
-
286
- ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
287
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
288
- if (webServer === undefined) {
289
- log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
290
- return
291
- }
292
- register(webServer, 'inject')
293
- })
294
-
295
- log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
296
- }
297
-
298
-
299
-
300
- /** Shared state forwarded through every Cordis proxy of one settings service. */
301
- interface SharedSettingsRegistration {
302
- /** Plugin fibers currently leasing the namespace. */
303
- readonly owners: Set<SettingsOwner>
304
- /** Owner whose fiber currently carries settings.register's native effect. */
305
- registrationOwner: SettingsOwner
306
- /** Current owner scope; replaced without changing the stored document. */
307
- scope: SettingsScope<unknown>
308
- }
309
-
310
- /** One selector Host row able to own the registration effect. */
311
- interface SettingsOwner {
312
- /** Traceable service proxy binding register() to this row's fiber. */
313
- readonly settings: SettingsService
314
- }
315
-
316
- /** Symbol properties reach the shared service target through Cordis proxies. */
317
- const SHARED_SETTINGS = Symbol.for(
318
- 'dsh-context-compression-improved/settings-registration',
319
- )
320
-
321
- type SettingsCarrier = SettingsService & {
322
- [SHARED_SETTINGS]?: SharedSettingsRegistration
323
- }
324
-
325
- /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
326
- export interface Config {
327
- /** Add the canonical compression stack to every non-Minimal preset. */
328
- presetOverlay?: boolean
329
- /**
330
- * Register the estimator-catalog HTTP route on this row.
331
- *
332
- * The standalone Bundle patch sets this on its own row (which declares
333
- * `inject: [webServer]`), so profiles without a host web server never mount a
334
- * row that could only announce a pending route. The row-level `inject` is
335
- * belt-and-braces: `dsh-host-webserver.register` performs no authorization
336
- * check and `ctx.get(name)` only asks whether the providing fiber is active,
337
- * so the two-channel registration inside this function is what actually
338
- * covers both arrival orders.
339
- */
340
- estimatorCatalogRoute?: boolean
341
- /**
342
- * Register the advisory advisor's read-only HTTP report route (decay
343
- * figure, task summary, score distribution, last benefit-model advice).
344
- * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
345
- * itself stays off until the user turns it on through the
346
- * `presetOptions.advisor*` settings keys.
347
- */
348
- advisorReportRoute?: boolean
349
- }
350
-
351
- /** Loader validation for the standalone Bundle opt-in. */
352
- export const Config: z<Config> = z.object({
353
- presetOverlay: z.boolean().default(false),
354
- estimatorCatalogRoute: z.boolean().default(false),
355
- advisorReportRoute: z.boolean().default(false),
356
- })
357
-
358
- /** Register the persisted default read by the currently mounted root pruner. */
359
- export function apply(ctx: Context, config: Config = {}): void {
360
- // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
361
- // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
362
- // here is completely invisible and looks exactly like a plugin that loaded
363
- // and quietly did nothing. Report it to a sink the host shows, then re-throw
364
- // unchanged: behaviour is untouched, only observability is restored.
365
- try {
366
- ctx.inject(['settings'], (settingsCtx) => {
367
- acquireSettingsRegistration(settingsCtx)
368
- })
369
-
370
- // The settings card's host-route dropdowns read this route; it lives on the
371
- // top-level plugin fiber, not inside the isolated `toolResultPruner`
372
- // service, because the route is host-wide rather than per-pruner-instance.
373
- if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
374
-
375
- // Advisory advisor: read-only decay/score/advice report (opt-in).
376
- if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
377
-
378
- if (config.presetOverlay !== true) return
379
-
380
- ctx.inject(['agentPresets'], (presetsCtx) => {
381
- const installation = decorateAgentPresets(
382
- presetsCtx.agentPresets,
383
- {
384
- modules: resolveCompressionModulePaths(),
385
- excludedPresetIds: ['minimal'],
386
- autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(presetsCtx),
387
- },
388
- )
389
- presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
390
- })
391
- } catch (error) {
392
- console.error('context-compression selector apply failed: %o', error)
393
- throw error
394
- }
395
- }
396
-
397
- /**
398
- * Read the current Auto Compact threshold ratio at composition time. Settings
399
- * values are revalidated here, and any unreadable value falls back to the 80%
400
- * default rather than blocking preset composition.
401
- */
402
- function resolveAutoCompactThresholdPercent(presetsCtx: Context): number {
403
- const raw = presetsCtx.get('settings')?.get(CONTEXT_COMPRESSION_NAMESPACE)
404
- try {
405
- const record = structuredClone(raw) as Record<string, unknown> | undefined
406
- const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
407
- const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
408
- return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
409
- } catch {
410
- return 80
411
- }
412
- }
413
-
414
- /**
415
- * Lease one native settings registration across duplicate Host rows.
416
- *
417
- * The lease effect is intentionally registered before settings.register().
418
- * Cordis disposes effects in reverse order, so the native registration first
419
- * releases the namespace; this disposer can then transfer it to another live
420
- * owner without a duplicate-registration window.
421
- */
422
- function acquireSettingsRegistration(ctx: Context): void {
423
- const settings = ctx.settings as SettingsCarrier
424
- const owner: SettingsOwner = { settings }
425
- let shared = settings[SHARED_SETTINGS]
426
- if (shared === undefined) {
427
- shared = {
428
- owners: new Set(),
429
- registrationOwner: owner,
430
- scope: undefined as unknown as SettingsScope<unknown>,
431
- }
432
- Object.defineProperty(settings, SHARED_SETTINGS, {
433
- configurable: true,
434
- enumerable: false,
435
- writable: false,
436
- value: shared,
437
- })
438
- }
439
- shared.owners.add(owner)
440
- const state = shared
441
-
442
- ctx.effect(() => () => {
443
- state.owners.delete(owner)
444
- if (state.registrationOwner === owner && state.owners.size > 0) {
445
- const next = state.owners.values().next().value as SettingsOwner
446
- state.registrationOwner = next
447
- state.scope = next.settings.register(
448
- CONTEXT_COMPRESSION_NAMESPACE,
449
- ContextCompressionSettingsSchema,
450
- )
451
- }
452
- if (state.owners.size === 0 && settings[SHARED_SETTINGS] === state) {
453
- Reflect.deleteProperty(settings, SHARED_SETTINGS)
454
- }
455
- }, 'contextCompressionSelector.settingsLease()')
456
-
457
- if (state.owners.size === 1) {
458
- state.scope = settings.register(
459
- CONTEXT_COMPRESSION_NAMESPACE,
460
- ContextCompressionSettingsSchema,
461
- )
462
- }
463
- }
1
+ /** Host owner of the context-compression preference consumed by the browser selector. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import {
6
+ type SettingsScope,
7
+ type default as SettingsService,
8
+ } from '@deepseek-ai/dsh-settings'
9
+ import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
10
+ import { getSavingsLedger } from './runtime/savings.ts'
11
+ import { priceOfficialDeepSeekUsage } from './runtime/deepseek-official-pricing.ts'
12
+ import {
13
+ applySessionOverride,
14
+ buildMonitorSnapshot,
15
+ estimateSavingsPricing,
16
+ isSessionOverrideAction,
17
+ type AgentDefaultModelLike,
18
+ } from './runtime/monitor.ts'
19
+ import {
20
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
21
+ ContextCompressionSettingsSchema,
22
+ } from './runtime/config.ts'
23
+
24
+ import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
25
+ import { registerSummaryCommand } from './runtime/summary-command.ts'
26
+
27
+ // The settings namespace literal and the settings schema are owned by the
28
+ // runtime config module. Both were once inlined/replaced here to dodge a
29
+ // cross-package dependency (ab2175a: the namespace literal was duplicated and
30
+ // the schema was downgraded to `z.any()`); the runtime is now part of this
31
+ // package, so the real schema is back and the daily Custom defaults are
32
+ // published again through settings.register(). The namespace value is
33
+ // unchanged ('context-compression').
34
+ const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never
35
+ import {
36
+ decorateAgentPresets,
37
+ resolveCompressionModulePaths,
38
+ } from './preset-overlay.ts'
39
+
40
+ // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
41
+ // absolute paths are registered (each is its own (kind, path) table entry) and
42
+ // one handler serves both prefixes. The bundled client only probes /api.
43
+ const ESTIMATOR_CATALOG_ROUTES = [
44
+ '/endpoint/dsh-context-compression-improved/estimator-catalog',
45
+ '/api/dsh-context-compression-improved/estimator-catalog',
46
+ ] as const
47
+
48
+ // Advisory advisor: one read-only report route, dual prefixed like the others.
49
+ const ADVISOR_REPORT_ROUTES = [
50
+ '/endpoint/dsh-context-compression-improved/advisor-report',
51
+ '/api/dsh-context-compression-improved/advisor-report',
52
+ ] as const
53
+
54
+ // Savings stats: one read-only snapshot route, dual prefixed like the others.
55
+ const SAVINGS_ROUTES = [
56
+ '/endpoint/dsh-context-compression-improved/savings',
57
+ '/api/dsh-context-compression-improved/savings',
58
+ ] as const
59
+
60
+ const MONITOR_ROUTES = [
61
+ '/endpoint/dsh-context-compression-improved/monitor',
62
+ '/api/dsh-context-compression-improved/monitor',
63
+ ] as const
64
+
65
+ /** Minimal face of the agents service: session id → agent (carrying the session). */
66
+ interface AgentsServiceLike {
67
+ get?(id: unknown): { session?: unknown } | undefined
68
+ }
69
+
70
+ function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
71
+ const agents = readService('agents') as AgentsServiceLike | undefined
72
+ return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
73
+ }
74
+
75
+ function jsonResponse(res: unknown, status: number, body: unknown): void {
76
+ const resTyped = res as {
77
+ writeHead: (code: number, headers?: Record<string, string>) => void
78
+ end: (body?: string) => void
79
+ }
80
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
81
+ resTyped.end(JSON.stringify(body))
82
+ }
83
+
84
+ /**
85
+ * Serve the advisory advisor's read-only report route (same registration
86
+ * skeleton as the estimator-catalog route):
87
+ *
88
+ * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
89
+ * the todolist-bound task summary, and the score distribution. Content-free
90
+ * by construction: task semantics are LLM-derived summaries, never message
91
+ * text, and no score reason or candidate preview is ever returned.
92
+ * Unknown session → 404; no agents service → 503. A session whose advisor
93
+ * never ran reports nulls and empty arrays, not an error.
94
+ */
95
+ function registerAdvisorReportRoute(ctx: Context): void {
96
+ const readService = (name: string): unknown => {
97
+ try {
98
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
99
+ } catch {
100
+ return undefined
101
+ }
102
+ }
103
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
104
+ console[level](message, ...args)
105
+ }
106
+
107
+ const getHandler = (req: unknown, res: unknown): void => {
108
+ const agents = readService('agents') as AgentsServiceLike | undefined
109
+ if (typeof agents?.get !== 'function') {
110
+ jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
111
+ return
112
+ }
113
+ let sessionId = ''
114
+ try {
115
+ const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
116
+ sessionId = url.searchParams.get('sessionId') ?? ''
117
+ } catch {
118
+ // Malformed URL: fall through with the empty sessionId already set.
119
+ }
120
+ if (sessionId === '') {
121
+ jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
122
+ return
123
+ }
124
+ const session = sessionFor(readService, sessionId)
125
+ if (session === undefined) {
126
+ jsonResponse(res, 404, { ok: false, error: 'unknown session' })
127
+ return
128
+ }
129
+ const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
130
+ jsonResponse(res, 200, {
131
+ ok: true,
132
+ sessionId,
133
+ advisor: {
134
+ summary: state.summary ?? null,
135
+ decay: state.lastDecay?.decay ?? null,
136
+ weightedChars: state.lastDecay?.weightedChars ?? null,
137
+ decayTurn: state.lastDecay?.turn ?? null,
138
+ scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
139
+ lowRelevanceSeqs: [...state.recertified.keys()],
140
+ // The benefit model's label of the last landed batch — advice, never a
141
+ // gate: the batch it describes landed regardless of the band.
142
+ lastAdvice: state.lastAdvice === undefined
143
+ ? null
144
+ : {
145
+ band: state.lastAdvice.band,
146
+ turn: state.lastAdvice.turn,
147
+ itemSeqs: state.lastAdvice.itemSeqs,
148
+ recoveredTokens: state.lastAdvice.recoveredTokens,
149
+ penaltyTokens: state.lastAdvice.penaltyTokens,
150
+ paybackTurns: state.lastAdvice.paybackTurns ?? null,
151
+ },
152
+ },
153
+ })
154
+ }
155
+
156
+ const register = (webServer: WebServerLike): void => {
157
+ const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
158
+ const disposers = table
159
+ .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
160
+ .filter((off): off is () => void => typeof off === 'function')
161
+ ctx.effect(
162
+ () => () => { for (const off of disposers) off() },
163
+ 'contextCompressionSelector.advisor report route',
164
+ )
165
+ log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
166
+ }
167
+
168
+ const active = asWebServer(readService('webServer'))
169
+ if (active !== undefined) {
170
+ register(active)
171
+ return
172
+ }
173
+
174
+ ctx.inject(['webServer'], (injected) => {
175
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
176
+ if (webServer === undefined) {
177
+ log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
178
+ return
179
+ }
180
+ register(webServer)
181
+ })
182
+
183
+ log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
184
+ }
185
+
186
+ /**
187
+ * The one service the catalog route actually needs. `llm` and
188
+ * `agentDefaultModel` are payload enrichment the handler resolves per request,
189
+ * never reasons to withhold the route.
190
+ */
191
+ const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
192
+
193
+ /** The minimal face of the DSH `webServer` service this plugin uses. */
194
+ interface WebServerLike {
195
+ register(route: {
196
+ kind: 'exact'
197
+ path: string
198
+ handler: (req: unknown, res: unknown) => unknown
199
+ }): () => void
200
+ }
201
+
202
+ /** The estimator-side service the catalog handler enriches its response with. */
203
+ function asWebServer(value: unknown): WebServerLike | undefined {
204
+ if (typeof value !== 'object' || value === null) return undefined
205
+ const candidate = value as { register?: unknown }
206
+ // Hand back the service itself -- never a wrapper re-exporting `register`.
207
+ // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
208
+ // so a detached call makes `this` the wrapper and throws "Cannot read
209
+ // properties of undefined (reading 'has')" inside the host, after which the
210
+ // route is simply absent and the client sees a bare 404. The 0.1.5 branch
211
+ // never had that defect; take this implementation, not the 0.1.2 history's.
212
+ return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
213
+ }
214
+
215
+ /**
216
+ * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
217
+ * settings card's host-route dropdowns (live provider/model groups from the DSH
218
+ * `llm` service plus the effective selection). Best effort: without the
219
+ * `webServer` service the plugin keeps working, only the HTTP API is missing.
220
+ *
221
+ * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
222
+ * enrich the response and are resolved per request, so listing them here would
223
+ * let an estimator-side service the handler never needs keep the route
224
+ * unregistered. That failure is silent by construction — an unsatisfied
225
+ * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
226
+ * every request falls through to the host 404.
227
+ *
228
+ * Two channels cover the two arrival orders: a direct lookup catches a
229
+ * `webServer` that is already active when the plugin loads, and `ctx.inject`
230
+ * catches one that activates later. Both funnel into a single guarded
231
+ * registration, because a late-arriving service must not re-register a
232
+ * `(kind, path)` the host treats as a composition-contract violation.
233
+ */
234
+ function registerEstimatorCatalogRoute(ctx: Context): void {
235
+ const readService = (name: string): unknown => {
236
+ try {
237
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
238
+ } catch {
239
+ return undefined
240
+ }
241
+ }
242
+ // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
243
+ // surfaces no plugin output in the `dsh web` terminal at all — a full boot
244
+ // produced zero plugin log lines while the process itself stayed chatty — so
245
+ // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
246
+ // uses `console.warn` for the same message class on the same host.
247
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
248
+ console[level](message, ...args)
249
+ }
250
+
251
+ let registered = false
252
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
253
+ if (registered) return
254
+ const handler = (_req: unknown, res: unknown): void => {
255
+ const resTyped = res as {
256
+ writeHead: (code: number, headers?: Record<string, string>) => void
257
+ end: (body?: string) => void
258
+ }
259
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
260
+ const llm = readService('llm')
261
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
262
+ const deps: EstimatorCatalogDeps = {
263
+ ...(llm === undefined
264
+ ? {}
265
+ : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
266
+ ...(typeof defaults?.currentSelection === 'function'
267
+ ? { currentSelection: () => defaults.currentSelection?.() }
268
+ : {}),
269
+ }
270
+ buildEstimatorCatalog(deps).then(
271
+ catalog => {
272
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
273
+ resTyped.end(JSON.stringify({ ok: true, ...catalog }))
274
+ },
275
+ (error: unknown) => {
276
+ resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
277
+ resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
278
+ },
279
+ )
280
+ }
281
+ try {
282
+ const disposers = ESTIMATOR_CATALOG_ROUTES
283
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
284
+ .filter((off): off is () => void => typeof off === 'function')
285
+ registered = true
286
+ ctx.effect(
287
+ () => () => { for (const off of disposers) off() },
288
+ 'contextCompressionSelector.estimator-catalog route',
289
+ )
290
+ log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
291
+ } catch (error) {
292
+ log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
293
+ }
294
+ }
295
+
296
+ const active = asWebServer(readService('webServer'))
297
+ if (active !== undefined) {
298
+ register(active, 'direct')
299
+ if (registered) return
300
+ }
301
+
302
+ ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
303
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
304
+ if (webServer === undefined) {
305
+ log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
306
+ return
307
+ }
308
+ register(webServer, 'inject')
309
+ })
310
+
311
+ log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
312
+ }
313
+
314
+
315
+
316
+ /** Shared state forwarded through every Cordis proxy of one settings service. */
317
+ interface SharedSettingsRegistration {
318
+ /** Plugin fibers currently leasing the namespace. */
319
+ readonly owners: Set<SettingsOwner>
320
+ /** Owner whose fiber currently carries settings.register's native effect. */
321
+ registrationOwner: SettingsOwner
322
+ /** Current owner scope; replaced without changing the stored document. */
323
+ scope: SettingsScope<unknown>
324
+ }
325
+
326
+ /**
327
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
328
+ * offsets (negative savings — compressed content later re-read in full), and net,
329
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
330
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
331
+ * channels for both service arrival orders, single guarded registration).
332
+ */
333
+ function registerSavingsRoute(ctx: Context): void {
334
+ const readService = (name: string): unknown => {
335
+ try {
336
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
337
+ } catch {
338
+ return undefined
339
+ }
340
+ }
341
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
342
+ console[level](message, ...args)
343
+ }
344
+
345
+ let registered = false
346
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
347
+ if (registered) return
348
+ const handler = (req: unknown, res: unknown): void => {
349
+ const resTyped = res as {
350
+ writeHead: (code: number, headers?: Record<string, string>) => void
351
+ end: (body?: string) => void
352
+ }
353
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
354
+ let sessionId: string | undefined
355
+ try {
356
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
357
+ const raw = url.searchParams.get('sessionId')
358
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
359
+ } catch {
360
+ /* 无法解析的查询串 = 全会话聚合 */
361
+ }
362
+ const snapshot = getSavingsLedger().snapshot(sessionId)
363
+ const pricing = estimateSavingsPricing(readService, snapshot)
364
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
365
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
366
+ }
367
+ try {
368
+ const disposers = SAVINGS_ROUTES
369
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
370
+ .filter((off): off is () => void => typeof off === 'function')
371
+ registered = true
372
+ ctx.effect(
373
+ () => () => { for (const off of disposers) off() },
374
+ 'contextCompressionSelector.savings route',
375
+ )
376
+ log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
377
+ } catch (error) {
378
+ log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
379
+ }
380
+ }
381
+
382
+ const active = asWebServer(readService('webServer'))
383
+ if (active !== undefined) {
384
+ register(active, 'direct')
385
+ if (registered) return
386
+ }
387
+
388
+ ctx.inject(['webServer'], (injected) => {
389
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
390
+ if (webServer === undefined) {
391
+ log('warn', 'context-compression webServer exposes no register() — savings route not registered')
392
+ return
393
+ }
394
+ register(webServer, 'inject')
395
+ })
396
+ }
397
+
398
+ /**
399
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
400
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
401
+ * pricing) — the payload shape the panel polls;
402
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
403
+ * driving the exact state machine `/ctx-summary` drives.
404
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
405
+ * single guarded registration); the handler branches on `req.method` because
406
+ * the registration surface is method-agnostic.
407
+ */
408
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
409
+ export function registerMonitorRoute(ctx: Context): void {
410
+ const readService = (name: string): unknown => {
411
+ try {
412
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
413
+ } catch {
414
+ return undefined
415
+ }
416
+ }
417
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
418
+ console[level](message, ...args)
419
+ }
420
+
421
+ let registered = false
422
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
423
+ if (registered) return
424
+ const handler = (req: unknown, res: unknown): void => {
425
+ const resTyped = res as {
426
+ writeHead: (code: number, headers?: Record<string, string>) => void
427
+ end: (body?: string) => void
428
+ }
429
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
430
+ let sessionId: string | undefined
431
+ try {
432
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
433
+ const raw = url.searchParams.get('sessionId')
434
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
435
+ } catch {
436
+ /* 无法解析的查询串 = 全会话聚合 */
437
+ }
438
+ const method = String((req as { method?: string })?.method ?? 'GET').toUpperCase()
439
+ if (method === 'POST') {
440
+ const chunks: Buffer[] = []
441
+ let size = 0
442
+ let done = false
443
+ const respond = (status: number, body: Record<string, unknown>): void => {
444
+ if (done) return
445
+ done = true
446
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
447
+ resTyped.end(JSON.stringify(body))
448
+ }
449
+ const reqTyped = req as { on?: (event: string, cb: (chunk?: Buffer) => void) => void }
450
+ if (typeof reqTyped?.on !== 'function') {
451
+ respond(400, { ok: false, error: 'unreadable request body' })
452
+ return
453
+ }
454
+ reqTyped.on('data', (chunk?: Buffer) => {
455
+ size += chunk?.length ?? 0
456
+ if (size <= 4096) chunks.push(Buffer.from(chunk ?? new Uint8Array()))
457
+ })
458
+ reqTyped.on('end', () => {
459
+ let action: unknown
460
+ try {
461
+ action = (JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') as { action?: unknown }).action
462
+ } catch {
463
+ respond(400, { ok: false, error: 'monitor override action must be JSON' })
464
+ return
465
+ }
466
+ if (!isSessionOverrideAction(action)) {
467
+ respond(400, { ok: false, error: 'monitor override action must be "on" | "off" | "clear"' })
468
+ return
469
+ }
470
+ const { override } = applySessionOverride(sessionId ?? '', action)
471
+ respond(200, { ok: true, override: override ?? null, sessionScope: sessionId ?? null })
472
+ })
473
+ return
474
+ }
475
+ const snapshot = buildMonitorSnapshot(sessionId)
476
+ const pricing = estimateSavingsPricing(readService, snapshot)
477
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
478
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
479
+ }
480
+ try {
481
+ const disposers = MONITOR_ROUTES
482
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
483
+ .filter((off): off is () => void => typeof off === 'function')
484
+ registered = true
485
+ ctx.effect(
486
+ () => () => { for (const off of disposers) off() },
487
+ 'contextCompressionSelector.monitor route',
488
+ )
489
+ log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
490
+ } catch (error) {
491
+ log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
492
+ }
493
+ }
494
+
495
+ const active = asWebServer(readService('webServer'))
496
+ if (active !== undefined) {
497
+ register(active, 'direct')
498
+ if (registered) return
499
+ }
500
+
501
+ ctx.inject(['webServer'], (injected) => {
502
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
503
+ if (webServer === undefined) {
504
+ log('warn', 'context-compression webServer exposes no register() — monitor route not registered')
505
+ return
506
+ }
507
+ register(webServer, 'inject')
508
+ })
509
+ }
510
+
511
+ /** One selector Host row able to own the registration effect. */
512
+ interface SettingsOwner {
513
+ /** Traceable service proxy binding register() to this row's fiber. */
514
+ readonly settings: SettingsService
515
+ }
516
+
517
+ /** Symbol properties reach the shared service target through Cordis proxies. */
518
+ const SHARED_SETTINGS = Symbol.for(
519
+ 'dsh-context-compression-improved/settings-registration',
520
+ )
521
+
522
+ type SettingsCarrier = SettingsService & {
523
+ [SHARED_SETTINGS]?: SharedSettingsRegistration
524
+ }
525
+
526
+ /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
527
+ export interface Config {
528
+ /** Add the canonical compression stack to every non-Minimal preset. */
529
+ presetOverlay?: boolean
530
+ /**
531
+ * Register the estimator-catalog HTTP route on this row.
532
+ *
533
+ * The standalone Bundle patch sets this on its own row (which declares
534
+ * `inject: [webServer]`), so profiles without a host web server never mount a
535
+ * row that could only announce a pending route. The row-level `inject` is
536
+ * belt-and-braces: `dsh-host-webserver.register` performs no authorization
537
+ * check and `ctx.get(name)` only asks whether the providing fiber is active,
538
+ * so the two-channel registration inside this function is what actually
539
+ * covers both arrival orders.
540
+ */
541
+ estimatorCatalogRoute?: boolean
542
+ /**
543
+ * Register the advisory advisor's read-only HTTP report route (decay
544
+ * figure, task summary, score distribution, last benefit-model advice).
545
+ * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
546
+ * itself stays off until the user turns it on through the
547
+ * `presetOptions.advisor*` settings keys.
548
+ */
549
+ advisorReportRoute?: boolean
550
+ }
551
+
552
+ /** Loader validation for the standalone Bundle opt-in. */
553
+ export const Config: z<Config> = z.object({
554
+ presetOverlay: z.boolean().default(false),
555
+ estimatorCatalogRoute: z.boolean().default(false),
556
+ advisorReportRoute: z.boolean().default(false),
557
+ })
558
+
559
+ /** Register the persisted default read by the currently mounted root pruner. */
560
+ export function apply(ctx: Context, config: Config = {}): void {
561
+ // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
562
+ // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
563
+ // here is completely invisible and looks exactly like a plugin that loaded
564
+ // and quietly did nothing. Report it to a sink the host shows, then re-throw
565
+ // unchanged: behaviour is untouched, only observability is restored.
566
+ try {
567
+ ctx.inject(['settings'], (settingsCtx) => {
568
+ acquireSettingsRegistration(settingsCtx)
569
+ })
570
+
571
+ // The settings card's host-route dropdowns read this route; it lives on the
572
+ // top-level plugin fiber, not inside the isolated `toolResultPruner`
573
+ // service, because the route is host-wide rather than per-pruner-instance.
574
+ if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
575
+ // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
576
+ registerSavingsRoute(ctx)
577
+ registerMonitorRoute(ctx)
578
+
579
+ // Advisory advisor: read-only decay/score/advice report (opt-in).
580
+ if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
581
+
582
+ // Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
583
+ // free to register and stays quiet on hosts without the commands
584
+ // registry; the capability itself is gated by the frozen `intentSummary`
585
+ // setting plus the session-scoped override this command controls.
586
+ registerSummaryCommand(ctx)
587
+
588
+ if (config.presetOverlay !== true) return
589
+
590
+ ctx.inject(['agentPresets'], (presetsCtx) => {
591
+ const installation = decorateAgentPresets(
592
+ presetsCtx.agentPresets,
593
+ {
594
+ modules: resolveCompressionModulePaths(),
595
+ excludedPresetIds: ['minimal'],
596
+ autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(presetsCtx),
597
+ },
598
+ )
599
+ presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
600
+ })
601
+ } catch (error) {
602
+ console.error('context-compression selector apply failed: %o', error)
603
+ throw error
604
+ }
605
+ }
606
+
607
+ /**
608
+ * Read the current Auto Compact threshold ratio at composition time. Settings
609
+ * values are revalidated here, and any unreadable value falls back to the 80%
610
+ * default rather than blocking preset composition.
611
+ */
612
+ function resolveAutoCompactThresholdPercent(presetsCtx: Context): number {
613
+ const raw = presetsCtx.get('settings')?.get(CONTEXT_COMPRESSION_NAMESPACE)
614
+ try {
615
+ const record = structuredClone(raw) as Record<string, unknown> | undefined
616
+ const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
617
+ const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
618
+ return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
619
+ } catch {
620
+ return 80
621
+ }
622
+ }
623
+
624
+ /**
625
+ * Lease one native settings registration across duplicate Host rows.
626
+ *
627
+ * The lease effect is intentionally registered before settings.register().
628
+ * Cordis disposes effects in reverse order, so the native registration first
629
+ * releases the namespace; this disposer can then transfer it to another live
630
+ * owner without a duplicate-registration window.
631
+ */
632
+ function acquireSettingsRegistration(ctx: Context): void {
633
+ const settings = ctx.settings as SettingsCarrier
634
+ const owner: SettingsOwner = { settings }
635
+ let shared = settings[SHARED_SETTINGS]
636
+ if (shared === undefined) {
637
+ shared = {
638
+ owners: new Set(),
639
+ registrationOwner: owner,
640
+ scope: undefined as unknown as SettingsScope<unknown>,
641
+ }
642
+ Object.defineProperty(settings, SHARED_SETTINGS, {
643
+ configurable: true,
644
+ enumerable: false,
645
+ writable: false,
646
+ value: shared,
647
+ })
648
+ }
649
+ shared.owners.add(owner)
650
+ const state = shared
651
+
652
+ ctx.effect(() => () => {
653
+ state.owners.delete(owner)
654
+ if (state.registrationOwner === owner && state.owners.size > 0) {
655
+ const next = state.owners.values().next().value as SettingsOwner
656
+ state.registrationOwner = next
657
+ state.scope = next.settings.register(
658
+ CONTEXT_COMPRESSION_NAMESPACE,
659
+ ContextCompressionSettingsSchema,
660
+ )
661
+ }
662
+ if (state.owners.size === 0 && settings[SHARED_SETTINGS] === state) {
663
+ Reflect.deleteProperty(settings, SHARED_SETTINGS)
664
+ }
665
+ }, 'contextCompressionSelector.settingsLease()')
666
+
667
+ if (state.owners.size === 1) {
668
+ state.scope = settings.register(
669
+ CONTEXT_COMPRESSION_NAMESPACE,
670
+ ContextCompressionSettingsSchema,
671
+ )
672
+ }
673
+ }