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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +17 -18
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +44 -0
  5. package/packages/selector/lib/client.js +1007 -13
  6. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +204 -3
  9. package/packages/selector/lib/profiles.d.ts +6 -0
  10. package/packages/selector/lib/pruner.d.ts +6 -0
  11. package/packages/selector/lib/pruner.js +90 -258
  12. package/packages/selector/lib/style.css +42 -0
  13. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  14. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  15. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  16. package/packages/selector/src/client/decode.ts +5 -1
  17. package/packages/selector/src/client/index.ts +307 -243
  18. package/packages/selector/src/client/locales/de.ts +43 -0
  19. package/packages/selector/src/client/locales/es.ts +43 -0
  20. package/packages/selector/src/client/locales/fr.ts +43 -0
  21. package/packages/selector/src/client/locales/it.ts +43 -0
  22. package/packages/selector/src/client/locales/ja.ts +43 -0
  23. package/packages/selector/src/client/locales/ko.ts +43 -0
  24. package/packages/selector/src/client/locales/ru.ts +43 -0
  25. package/packages/selector/src/client/locales.ts +282 -196
  26. package/packages/selector/src/client/monitor-fab.ts +336 -0
  27. package/packages/selector/src/client/savings-card.tsx +150 -0
  28. package/packages/selector/src/client/settings-section.tsx +140 -124
  29. package/packages/selector/src/index.ts +207 -5
  30. package/packages/selector/src/profiles.ts +17 -0
  31. package/packages/selector/src/pruner.ts +96 -2
  32. package/packages/selector/src/runtime/config.ts +26 -1
  33. package/packages/selector/src/runtime/monitor.ts +235 -0
  34. package/packages/selector/src/runtime/retrieve.ts +479 -457
  35. package/packages/selector/src/runtime/savings.ts +337 -0
  36. package/packages/selector/src/runtime/types.ts +7 -0
  37. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  38. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  39. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  40. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  41. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  42. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  43. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  44. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  45. package/scripts/packed-install-e2e.mjs +1 -1
  46. package/scripts/verify-release.mjs +1 -1
@@ -1,124 +1,140 @@
1
- /**
2
- * Full-page Settings surface backed by the same durable selector state.
3
- *
4
- * Extracted from CompressionProfileSelector.tsx to reduce god-module size.
5
- *
6
- * @module dsh-context-compression-improved/client/settings-section
7
- */
8
-
9
- import { useEffect, useState } from 'react'
10
- import css from './CompressionProfileSelector.module.css'
11
- import {
12
- AUTO_COMPACT_THRESHOLD_LIMITS,
13
- COMPRESSION_PROFILES,
14
- type CompressionProfile,
15
- type CustomCompressionPolicyV3,
16
- } from '../profiles.ts'
17
- import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
18
- import { AutoCompactThresholdControls, CodeSkeletonControls } from './CompressionProfileControls.tsx'
19
- import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
20
- import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
21
-
22
- /** Full-page Settings surface backed by the same durable selector state. */
23
- export function ContextCompressionSettingsSection(props: CompressionProfileSelectorProps) {
24
- return <SettingsCompressionProfileControls {...props} />
25
- }
26
-
27
- export function SettingsCompressionProfileControls({
28
- useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton,
29
- savePresetOptions, t,
30
- }: CompressionProfileSelectorProps) {
31
- const state = useCompression(snapshot => snapshot)
32
- // Harness 0.1.5 dropped browser-side agentPreset from session summaries, so
33
- // the old Minimal-preset gate has no data source; the selector stays enabled.
34
- const selectorAvailable = true
35
- const [saving, setSaving] = useState(false)
36
- const [saveError, setSaveError] = useState<string | null>(null)
37
- const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
38
- const current = state.value?.profile ?? 'balanced'
39
- useEffect(() => {
40
- const custom = state.value?.custom
41
- setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
42
- }, [current, state.value?.custom])
43
- if (state.status === 'unavailable') return null
44
-
45
- const busy = state.status === 'loading' || saving
46
- const selectProfile = (profile: CompressionProfile): void => {
47
- if (!selectorAvailable || !state.writable || profile === current) return
48
- setSaveError(null)
49
- setSaving(true)
50
- void select(profile).then(
51
- () => { setSaving(false) },
52
- (error: unknown) => {
53
- setSaving(false)
54
- setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
55
- },
56
- )
57
- }
58
- const settle = (operation: () => Promise<void>): void => {
59
- setSaveError(null)
60
- setSaving(true)
61
- void operation().then(
62
- () => { setSaving(false) },
63
- (error: unknown) => {
64
- setSaving(false)
65
- setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
66
- },
67
- )
68
- }
69
-
70
- return (
71
- <section className={css.settingsSection}>
72
- <h2 className={css.settingsTitle}>{t('settings.title')}</h2>
73
- <p className={css.settingsDescription}>{t('settings.description')}</p>
74
- {selectorAvailable ? (
75
- <div className={css.profileGrid} aria-label={t('label')}>
76
- {COMPRESSION_PROFILES.map((profile) => {
77
- const selected = profile === current
78
- return (
79
- <button key={profile} type="button" className={css.profileCard} aria-pressed={selected}
80
- disabled={busy || !state.writable} onClick={() => { selectProfile(profile) }}>
81
- <span className={css.profileCardTop}>
82
- <span className={css.profileCardTitle}>{t(`profile.${profile}`)}</span>
83
- {selected ? <span className={css.profileCurrent}>{t('profile.current')}</span> : null}
84
- </span>
85
- <span className={css.profileCardDetail}>{t(`detail.${profile}`)}</span>
86
- </button>
87
- )
88
- })}
89
- </div>
90
- ) : <div className={css.unavailable} role="status">{t('status.minimalUnavailable')}</div>}
91
- <AutoCompactThresholdControls
92
- value={state.value?.autoCompact?.thresholdPercent ?? AUTO_COMPACT_THRESHOLD_LIMITS.default}
93
- disabled={busy || !state.writable || !selectorAvailable}
94
- save={saveAutoCompact}
95
- settle={settle}
96
- t={t}
97
- />
98
- <CodeSkeletonControls
99
- value={state.value?.codeSkeleton?.enabled ?? false}
100
- disabled={busy || !state.writable || !selectorAvailable}
101
- save={saveCodeSkeleton}
102
- settle={settle}
103
- t={t}
104
- />
105
- {current !== 'tokenpilot-inspired' ? (
106
- <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
107
- ) : (
108
- <EstimatorControls
109
- options={state.value?.presetOptions ?? {}}
110
- disabled={busy || !state.writable || !selectorAvailable}
111
- save={savePresetOptions}
112
- settle={settle}
113
- t={t}
114
- />
115
- )}
116
- <div className={css.pricing}>{t('pricing.disclosure')}</div>
117
- {current !== 'custom' || draft === null || !selectorAvailable ? null : (
118
- <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
119
- save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
120
- )}
121
- {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
122
- </section>
123
- )
124
- }
1
+ /**
2
+ * Full-page Settings surface backed by the same durable selector state.
3
+ *
4
+ * Extracted from CompressionProfileSelector.tsx to reduce god-module size.
5
+ *
6
+ * @module dsh-context-compression-improved/client/settings-section
7
+ */
8
+
9
+ import { useEffect, useState } from 'react'
10
+ import css from './CompressionProfileSelector.module.css'
11
+ import {
12
+ AUTO_COMPACT_THRESHOLD_LIMITS,
13
+ COMPRESSION_PROFILES,
14
+ type CompressionProfile,
15
+ type CustomCompressionPolicyV3,
16
+ } from '../profiles.ts'
17
+ import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
18
+ import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
19
+ import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
20
+ import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
21
+ import { SavingsCard } from './savings-card'
22
+
23
+ /** Full-page Settings surface backed by the same durable selector state. */
24
+ export function ContextCompressionSettingsSection(props: CompressionProfileSelectorProps) {
25
+ return <SettingsCompressionProfileControls {...props} />
26
+ }
27
+
28
+ export function SettingsCompressionProfileControls({
29
+ useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
30
+ savePresetOptions, t,
31
+ }: CompressionProfileSelectorProps) {
32
+ const state = useCompression(snapshot => snapshot)
33
+ // Harness 0.1.5 dropped browser-side agentPreset from session summaries, so
34
+ // the old Minimal-preset gate has no data source; the selector stays enabled.
35
+ const selectorAvailable = true
36
+ const [saving, setSaving] = useState(false)
37
+ const [saveError, setSaveError] = useState<string | null>(null)
38
+ const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
39
+ const current = state.value?.profile ?? 'balanced'
40
+ useEffect(() => {
41
+ const custom = state.value?.custom
42
+ setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
43
+ }, [current, state.value?.custom])
44
+ if (state.status === 'unavailable') return null
45
+
46
+ const busy = state.status === 'loading' || saving
47
+ const selectProfile = (profile: CompressionProfile): void => {
48
+ if (!selectorAvailable || !state.writable || profile === current) return
49
+ setSaveError(null)
50
+ setSaving(true)
51
+ void select(profile).then(
52
+ () => { setSaving(false) },
53
+ (error: unknown) => {
54
+ setSaving(false)
55
+ setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
56
+ },
57
+ )
58
+ }
59
+ const settle = (operation: () => Promise<void>): void => {
60
+ setSaveError(null)
61
+ setSaving(true)
62
+ void operation().then(
63
+ () => { setSaving(false) },
64
+ (error: unknown) => {
65
+ setSaving(false)
66
+ setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
67
+ },
68
+ )
69
+ }
70
+
71
+ return (
72
+ <section className={css.settingsSection}>
73
+ <h2 className={css.settingsTitle}>{t('settings.title')}</h2>
74
+ <p className={css.settingsDescription}>{t('settings.description')}</p>
75
+ {selectorAvailable ? (
76
+ <div className={css.profileGrid} aria-label={t('label')}>
77
+ {COMPRESSION_PROFILES.map((profile) => {
78
+ const selected = profile === current
79
+ return (
80
+ <button key={profile} type="button" className={css.profileCard} aria-pressed={selected}
81
+ disabled={busy || !state.writable} onClick={() => { selectProfile(profile) }}>
82
+ <span className={css.profileCardTop}>
83
+ <span className={css.profileCardTitle}>{t(`profile.${profile}`)}</span>
84
+ {selected ? <span className={css.profileCurrent}>{t('profile.current')}</span> : null}
85
+ </span>
86
+ <span className={css.profileCardDetail}>{t(`detail.${profile}`)}</span>
87
+ </button>
88
+ )
89
+ })}
90
+ </div>
91
+ ) : <div className={css.unavailable} role="status">{t('status.minimalUnavailable')}</div>}
92
+ <AutoCompactThresholdControls
93
+ value={state.value?.autoCompact?.thresholdPercent ?? AUTO_COMPACT_THRESHOLD_LIMITS.default}
94
+ disabled={busy || !state.writable || !selectorAvailable}
95
+ save={saveAutoCompact}
96
+ settle={settle}
97
+ t={t}
98
+ />
99
+ <CodeSkeletonControls
100
+ value={state.value?.codeSkeleton?.enabled ?? false}
101
+ disabled={busy || !state.writable || !selectorAvailable}
102
+ save={saveCodeSkeleton}
103
+ settle={settle}
104
+ t={t}
105
+ />
106
+ <IntentSummaryControls
107
+ value={state.value?.intentSummary?.enabled ?? false}
108
+ disabled={busy || !state.writable || !selectorAvailable}
109
+ save={saveIntentSummary}
110
+ settle={settle}
111
+ t={t}
112
+ />
113
+ <MonitorPanelControls
114
+ value={state.value?.monitorPanel?.enabled ?? false}
115
+ disabled={busy || !state.writable || !selectorAvailable}
116
+ save={saveMonitorPanel}
117
+ settle={settle}
118
+ t={t}
119
+ />
120
+ {current !== 'tokenpilot-inspired' ? (
121
+ <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
122
+ ) : (
123
+ <EstimatorControls
124
+ options={state.value?.presetOptions ?? {}}
125
+ disabled={busy || !state.writable || !selectorAvailable}
126
+ save={savePresetOptions}
127
+ settle={settle}
128
+ t={t}
129
+ />
130
+ )}
131
+ <SavingsCard t={t} />
132
+ <div className={css.pricing}>{t('pricing.disclosure')}</div>
133
+ {current !== 'custom' || draft === null || !selectorAvailable ? null : (
134
+ <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
135
+ save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
136
+ )}
137
+ {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
138
+ </section>
139
+ )
140
+ }
@@ -3,6 +3,14 @@
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
4
  import z from '@deepseek-ai/schemastery'
5
5
  import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
6
+ import { getSavingsLedger } from './runtime/savings.ts'
7
+ import {
8
+ applySessionOverride,
9
+ buildMonitorSnapshot,
10
+ estimateSavingsPricing,
11
+ isSessionOverrideAction,
12
+ type AgentDefaultModelLike,
13
+ } from './runtime/monitor.ts'
6
14
  import type { ContextCompressionSettings } from './profiles.ts'
7
15
  import {
8
16
  CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
@@ -38,6 +46,17 @@ const ADVISOR_REPORT_ROUTES = [
38
46
  '/api/dsh-context-compression-improved/advisor-report',
39
47
  ] as const
40
48
 
49
+ // Savings stats: one read-only snapshot route, dual prefixed like the others.
50
+ const SAVINGS_ROUTES = [
51
+ '/endpoint/dsh-context-compression-improved/savings',
52
+ '/api/dsh-context-compression-improved/savings',
53
+ ] as const
54
+
55
+ const MONITOR_ROUTES = [
56
+ '/endpoint/dsh-context-compression-improved/monitor',
57
+ '/api/dsh-context-compression-improved/monitor',
58
+ ] as const
59
+
41
60
  /** Minimal face of the agents service: session id → agent (carrying the session). */
42
61
  interface AgentsServiceLike {
43
62
  get?(id: unknown): { session?: unknown } | undefined
@@ -176,11 +195,6 @@ interface WebServerLike {
176
195
  }
177
196
 
178
197
  /** The estimator-side service the catalog handler enriches its response with. */
179
- interface AgentDefaultModelLike {
180
- /** Current host model-group selection, when the service exposes one. */
181
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
182
- }
183
-
184
198
  function asWebServer(value: unknown): WebServerLike | undefined {
185
199
  if (typeof value !== 'object' || value === null) return undefined
186
200
  const candidate = value as { register?: unknown }
@@ -292,6 +306,191 @@ function registerEstimatorCatalogRoute(ctx: Context): void {
292
306
  log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
293
307
  }
294
308
 
309
+ /**
310
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
311
+ * offsets (negative savings — compressed content later re-read in full), and net,
312
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
313
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
314
+ * channels for both service arrival orders, single guarded registration).
315
+ */
316
+ function registerSavingsRoute(ctx: Context): void {
317
+ const readService = (name: string): unknown => {
318
+ try {
319
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
320
+ } catch {
321
+ return undefined
322
+ }
323
+ }
324
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
325
+ console[level](message, ...args)
326
+ }
327
+
328
+ let registered = false
329
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
330
+ if (registered) return
331
+ const handler = (req: unknown, res: unknown): void => {
332
+ const resTyped = res as {
333
+ writeHead: (code: number, headers?: Record<string, string>) => void
334
+ end: (body?: string) => void
335
+ }
336
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
337
+ let sessionId: string | undefined
338
+ try {
339
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
340
+ const raw = url.searchParams.get('sessionId')
341
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
342
+ } catch {
343
+ /* 无法解析的查询串 = 全会话聚合 */
344
+ }
345
+ const snapshot = getSavingsLedger().snapshot(sessionId)
346
+ const pricing = estimateSavingsPricing(readService, snapshot)
347
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
348
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
349
+ }
350
+ try {
351
+ const disposers = SAVINGS_ROUTES
352
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
353
+ .filter((off): off is () => void => typeof off === 'function')
354
+ registered = true
355
+ ctx.effect(
356
+ () => () => { for (const off of disposers) off() },
357
+ 'contextCompressionSelector.savings route',
358
+ )
359
+ log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
360
+ } catch (error) {
361
+ log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
362
+ }
363
+ }
364
+
365
+ const active = asWebServer(readService('webServer'))
366
+ if (active !== undefined) {
367
+ register(active, 'direct')
368
+ if (registered) return
369
+ }
370
+
371
+ ctx.inject(['webServer'], (injected) => {
372
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
373
+ if (webServer === undefined) {
374
+ log('warn', 'context-compression webServer exposes no register() — savings route not registered')
375
+ return
376
+ }
377
+ register(webServer, 'inject')
378
+ })
379
+ }
380
+
381
+ /**
382
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
383
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
384
+ * pricing) — the payload shape the panel polls;
385
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
386
+ * driving the exact state machine `/ctx-summary` drives.
387
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
388
+ * single guarded registration); the handler branches on `req.method` because
389
+ * the registration surface is method-agnostic.
390
+ */
391
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
392
+ export function registerMonitorRoute(ctx: Context): void {
393
+ const readService = (name: string): unknown => {
394
+ try {
395
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
396
+ } catch {
397
+ return undefined
398
+ }
399
+ }
400
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
401
+ console[level](message, ...args)
402
+ }
403
+
404
+ let registered = false
405
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
406
+ if (registered) return
407
+ const handler = (req: unknown, res: unknown): void => {
408
+ const resTyped = res as {
409
+ writeHead: (code: number, headers?: Record<string, string>) => void
410
+ end: (body?: string) => void
411
+ }
412
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
413
+ let sessionId: string | undefined
414
+ try {
415
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
416
+ const raw = url.searchParams.get('sessionId')
417
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
418
+ } catch {
419
+ /* 无法解析的查询串 = 全会话聚合 */
420
+ }
421
+ const method = String((req as { method?: string })?.method ?? 'GET').toUpperCase()
422
+ if (method === 'POST') {
423
+ const chunks: Buffer[] = []
424
+ let size = 0
425
+ let done = false
426
+ const respond = (status: number, body: Record<string, unknown>): void => {
427
+ if (done) return
428
+ done = true
429
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
430
+ resTyped.end(JSON.stringify(body))
431
+ }
432
+ const reqTyped = req as { on?: (event: string, cb: (chunk?: Buffer) => void) => void }
433
+ if (typeof reqTyped?.on !== 'function') {
434
+ respond(400, { ok: false, error: 'unreadable request body' })
435
+ return
436
+ }
437
+ reqTyped.on('data', (chunk?: Buffer) => {
438
+ size += chunk?.length ?? 0
439
+ if (size <= 4096) chunks.push(Buffer.from(chunk ?? new Uint8Array()))
440
+ })
441
+ reqTyped.on('end', () => {
442
+ let action: unknown
443
+ try {
444
+ action = (JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') as { action?: unknown }).action
445
+ } catch {
446
+ respond(400, { ok: false, error: 'monitor override action must be JSON' })
447
+ return
448
+ }
449
+ if (!isSessionOverrideAction(action)) {
450
+ respond(400, { ok: false, error: 'monitor override action must be "on" | "off" | "clear"' })
451
+ return
452
+ }
453
+ const { override } = applySessionOverride(sessionId ?? '', action)
454
+ respond(200, { ok: true, override: override ?? null, sessionScope: sessionId ?? null })
455
+ })
456
+ return
457
+ }
458
+ const snapshot = buildMonitorSnapshot(sessionId)
459
+ const pricing = estimateSavingsPricing(readService, snapshot)
460
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
461
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
462
+ }
463
+ try {
464
+ const disposers = MONITOR_ROUTES
465
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
466
+ .filter((off): off is () => void => typeof off === 'function')
467
+ registered = true
468
+ ctx.effect(
469
+ () => () => { for (const off of disposers) off() },
470
+ 'contextCompressionSelector.monitor route',
471
+ )
472
+ log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
473
+ } catch (error) {
474
+ log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
475
+ }
476
+ }
477
+
478
+ const active = asWebServer(readService('webServer'))
479
+ if (active !== undefined) {
480
+ register(active, 'direct')
481
+ if (registered) return
482
+ }
483
+
484
+ ctx.inject(['webServer'], (injected) => {
485
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
486
+ if (webServer === undefined) {
487
+ log('warn', 'context-compression webServer exposes no register() — monitor route not registered')
488
+ return
489
+ }
490
+ register(webServer, 'inject')
491
+ })
492
+ }
493
+
295
494
  /**
296
495
  * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
297
496
  * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
@@ -364,6 +563,9 @@ export function apply(ctx: Context, config: Config = {}): void {
364
563
  // top-level plugin fiber, not inside the isolated `toolResultPruner`
365
564
  // service, because the route is host-wide rather than per-pruner-instance.
366
565
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
566
+ // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
567
+ registerSavingsRoute(ctx)
568
+ registerMonitorRoute(ctx)
367
569
 
368
570
  // Advisory advisor: read-only decay/score/advice report (opt-in).
369
571
  if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
@@ -116,6 +116,11 @@ export interface IntentSummarySettings {
116
116
  enabled: boolean
117
117
  }
118
118
 
119
+ /** Floating compression-monitor panel (FAB); visibility switch. */
120
+ export interface MonitorPanelSettings {
121
+ enabled: boolean
122
+ }
123
+
119
124
  /**
120
125
  * Decode the persisted codeSkeleton section with exactly the runtime schema's
121
126
  * strictness: absent means the lossless off default; present values must be a
@@ -141,6 +146,16 @@ export function decodeIntentSummarySettings(value: unknown): IntentSummarySettin
141
146
  return typeof enabled === 'boolean' ? { enabled } : undefined
142
147
  }
143
148
 
149
+ /** Browser-safe mirror of the runtime monitorPanel section (absent inherits hidden). */
150
+ export function decodeMonitorPanelSettings(value: unknown): MonitorPanelSettings | undefined {
151
+ if (value === undefined) return { enabled: false }
152
+ if (!isPlainRecord(value)) return undefined
153
+ const keys = Object.keys(value)
154
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
155
+ const enabled = (value as Record<string, unknown>).enabled
156
+ return typeof enabled === 'boolean' ? { enabled } : undefined
157
+ }
158
+
144
159
  /** Browser-safe mirror of the runtime presetOptions section. */
145
160
  export interface PresetOptionsSettings {
146
161
  readonly dedupeToolResults?: boolean
@@ -309,6 +324,8 @@ export interface ContextCompressionSettings {
309
324
  codeSkeleton: CodeSkeletonSettings
310
325
  /** Turn-tail intent-summary gate captured independently of `profile`. */
311
326
  intentSummary: IntentSummarySettings
327
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
328
+ monitorPanel?: MonitorPanelSettings
312
329
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
313
330
  presetOptions?: PresetOptionsSettings
314
331
  }