dsh-context-compression-improved 0.2.4 → 0.2.5

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