dsh-context-compression-improved 0.8.0-beta.4 → 0.8.0-beta.6

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 (39) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/package.json +1 -1
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +23 -0
  5. package/packages/selector/lib/client.js +567 -3
  6. package/packages/selector/lib/{intent-gate.js → config.js} +285 -136
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +131 -50
  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 +5 -3
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
  14. package/packages/selector/src/client/decode.ts +5 -1
  15. package/packages/selector/src/client/index.ts +60 -0
  16. package/packages/selector/src/client/locales/de.ts +22 -0
  17. package/packages/selector/src/client/locales/es.ts +22 -0
  18. package/packages/selector/src/client/locales/fr.ts +22 -0
  19. package/packages/selector/src/client/locales/it.ts +22 -0
  20. package/packages/selector/src/client/locales/ja.ts +22 -0
  21. package/packages/selector/src/client/locales/ko.ts +22 -0
  22. package/packages/selector/src/client/locales/ru.ts +22 -0
  23. package/packages/selector/src/client/locales.ts +44 -0
  24. package/packages/selector/src/client/monitor-fab.ts +320 -0
  25. package/packages/selector/src/client/settings-section.tsx +9 -2
  26. package/packages/selector/src/index.ts +126 -60
  27. package/packages/selector/src/profiles.ts +17 -0
  28. package/packages/selector/src/pruner.ts +2 -0
  29. package/packages/selector/src/runtime/config.ts +26 -1
  30. package/packages/selector/src/runtime/monitor.ts +211 -0
  31. package/packages/selector/src/runtime/types.ts +7 -0
  32. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  33. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  34. package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
  35. package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
  36. package/packages/selector/tests/runtime/monitor.spec.ts +274 -0
  37. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  38. package/scripts/packed-install-e2e.mjs +1 -1
  39. package/scripts/verify-release.mjs +1 -1
@@ -4,7 +4,13 @@ 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
6
  import { getSavingsLedger } from './runtime/savings.ts'
7
- import { priceOfficialDeepSeekUsage } from './runtime/deepseek-official-pricing.ts'
7
+ import {
8
+ applySessionOverride,
9
+ buildMonitorSnapshot,
10
+ estimateSavingsPricing,
11
+ isSessionOverrideAction,
12
+ type AgentDefaultModelLike,
13
+ } from './runtime/monitor.ts'
8
14
  import type { ContextCompressionSettings } from './profiles.ts'
9
15
  import {
10
16
  CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
@@ -46,6 +52,11 @@ const SAVINGS_ROUTES = [
46
52
  '/api/dsh-context-compression-improved/savings',
47
53
  ] as const
48
54
 
55
+ const MONITOR_ROUTES = [
56
+ '/endpoint/dsh-context-compression-improved/monitor',
57
+ '/api/dsh-context-compression-improved/monitor',
58
+ ] as const
59
+
49
60
  /** Minimal face of the agents service: session id → agent (carrying the session). */
50
61
  interface AgentsServiceLike {
51
62
  get?(id: unknown): { session?: unknown } | undefined
@@ -184,11 +195,6 @@ interface WebServerLike {
184
195
  }
185
196
 
186
197
  /** The estimator-side service the catalog handler enriches its response with. */
187
- interface AgentDefaultModelLike {
188
- /** Current host model-group selection, when the service exposes one. */
189
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
190
- }
191
-
192
198
  function asWebServer(value: unknown): WebServerLike | undefined {
193
199
  if (typeof value !== 'object' || value === null) return undefined
194
200
  const candidate = value as { register?: unknown }
@@ -300,60 +306,6 @@ function registerEstimatorCatalogRoute(ctx: Context): void {
300
306
  log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
301
307
  }
302
308
 
303
- /**
304
- * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
305
- * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
306
- * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
307
- * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
308
- * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
309
- */
310
- function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
311
- startedAt: string
312
- net: { exact: number; estimated: number }
313
- usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
314
- }): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
315
- if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
316
- const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
317
- const selection = defaults?.currentSelection?.()
318
- const provider = typeof selection?.provider === 'string' ? selection.provider : ''
319
- const modelId = typeof selection?.model === 'string' ? selection.model : ''
320
- if (provider !== 'deepseek-official') return undefined
321
- const now = new Date()
322
- const startedAt = new Date(snapshot.startedAt)
323
- const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
324
- const base = {
325
- provider,
326
- baseUrlClass: 'official-public',
327
- apiRoute: 'chat-completions',
328
- modelId,
329
- currency: 'USD',
330
- startedAt,
331
- completedAt,
332
- } as const
333
- const actual = priceOfficialDeepSeekUsage({
334
- ...base,
335
- usage: {
336
- cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
337
- cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
338
- outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
339
- },
340
- })
341
- const saved = snapshot.net.exact > 0
342
- ? priceOfficialDeepSeekUsage({
343
- ...base,
344
- usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
345
- })
346
- : undefined
347
- const decimalOf = (cost: typeof actual): string | undefined =>
348
- cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
349
- if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
350
- return {
351
- currency: 'USD',
352
- ...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
353
- ...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
354
- }
355
- }
356
-
357
309
  /**
358
310
  * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
359
311
  * offsets (negative savings — compressed content later re-read in full), and net,
@@ -426,6 +378,119 @@ function registerSavingsRoute(ctx: Context): void {
426
378
  })
427
379
  }
428
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
+
429
494
  /**
430
495
  * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
431
496
  * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
@@ -500,6 +565,7 @@ export function apply(ctx: Context, config: Config = {}): void {
500
565
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
501
566
  // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
502
567
  registerSavingsRoute(ctx)
568
+ registerMonitorRoute(ctx)
503
569
 
504
570
  // Advisory advisor: read-only decay/score/advice report (opt-in).
505
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
  }
@@ -97,6 +97,7 @@ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/token
97
97
  import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
98
98
  import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
99
99
  import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
100
+ import { observeContextUsage } from './runtime/monitor.ts'
100
101
 
101
102
  import {
102
103
  DedupeTable,
@@ -821,6 +822,7 @@ export class ToolResultPruner extends Service {
821
822
  contextWindow,
822
823
  baselineTokens: this.state.intentBaselines.get(session) ?? 0,
823
824
  })
825
+ observeContextUsage(sessionId, view.totalTokens, contextWindow)
824
826
  if (!gate.decision) return
825
827
 
826
828
  const settingsPreset = settings.presetOptions
@@ -6,6 +6,7 @@ import type {
6
6
  CodeSkeletonSettings,
7
7
  CompressionPolicy,
8
8
  IntentSummarySettings,
9
+ MonitorPanelSettings,
9
10
  CompressionProfile,
10
11
  CustomCompressionPolicy,
11
12
  PresetOptions,
@@ -136,6 +137,27 @@ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
136
137
  return { enabled }
137
138
  }
138
139
 
140
+ /**
141
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
142
+ * section semantics: absent inherits the hidden default, while a
143
+ * present-but-invalid section is an explicitly invalid document.
144
+ */
145
+ function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
146
+ if (value === undefined) return { enabled: false }
147
+ if (!isPlainRecord(value)) {
148
+ throw new TypeError('Context-compression monitorPanel must be a plain object')
149
+ }
150
+ const keys = Object.keys(value)
151
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
152
+ throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
153
+ }
154
+ const enabled = (value as Record<string, unknown>).enabled
155
+ if (typeof enabled !== 'boolean') {
156
+ throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
157
+ }
158
+ return { enabled }
159
+ }
160
+
139
161
  /**
140
162
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
141
163
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
@@ -276,6 +298,7 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
276
298
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
277
299
  codeSkeleton: { enabled: false },
278
300
  intentSummary: { enabled: false },
301
+ monitorPanel: { enabled: false },
279
302
  }
280
303
 
281
304
  /**
@@ -313,7 +336,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
313
336
  // remain valid and inherit their defaults; the sections themselves stay
314
337
  // strictly shaped.
315
338
  const unknown = Object.keys(candidate).find(key =>
316
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')
339
+ key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
317
340
  if (unknown !== undefined) {
318
341
  throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
319
342
  }
@@ -326,12 +349,14 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
326
349
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
327
350
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
328
351
  const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
352
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
329
353
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
330
354
  return {
331
355
  ...contextCompressionSettingsInputSchema(candidate),
332
356
  autoCompact,
333
357
  codeSkeleton,
334
358
  intentSummary,
359
+ monitorPanel,
335
360
  ...presetOptions === undefined ? {} : { presetOptions },
336
361
  }
337
362
  },
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Compression monitor surface for the floating panel (FAB, task: cci-monitor-fab).
3
+ *
4
+ * Three pieces, one module:
5
+ * - `buildMonitorSnapshot`: the savings snapshot (reused verbatim from the
6
+ * ledger — no second accounting) plus the turn-tail intent-summary block
7
+ * (override / observed flag / gate constants / last fold);
8
+ * - `applySessionOverride`: the `/ctx-summary` override state machine,
9
+ * addressed by session id — the panel buttons drive the same state the
10
+ * command drives, never a second one;
11
+ * - `estimateSavingsPricing`: moved here from the entry (the savings route
12
+ * and the monitor route share it; keeping it next to the monitor payload
13
+ * avoids a runtime → entry import cycle).
14
+ *
15
+ * The monitor route itself stays in the entry (`registerMonitorRoute`),
16
+ * mirroring the savings/estimator registrars: all webServer wiring lives in
17
+ * one place, the data plane lives here.
18
+ *
19
+ * Contract discipline: the published `/savings` route contract is frozen
20
+ * (estimator-route spec encodes it) — the monitor aggregates but never
21
+ * reshapes it; new fields attach under `intent` / `sessionScope`.
22
+ */
23
+
24
+ /** Current host model-group selection, when the service exposes one. */
25
+ export interface AgentDefaultModelLike {
26
+ currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
27
+ }
28
+
29
+ import { priceOfficialDeepSeekUsage } from './deepseek-official-pricing.ts'
30
+ import { getSavingsLedger, type SavingsLedger, type SavingsSnapshot } from './savings.ts'
31
+ import {
32
+ getLastIntentFold,
33
+ getObservedIntentEnabled,
34
+ getSummaryOverride,
35
+ setSummaryOverride,
36
+ type IntentFoldRecord,
37
+ } from './tokenpilot/advisor-state.ts'
38
+ import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
39
+
40
+ export interface MonitorIntentBlock {
41
+ /** Session-scoped override; absent = settings-driven. */
42
+ override: 'on' | 'off' | undefined
43
+ /** Settings flag as last observed by the gate; absent = gate not evaluated yet. */
44
+ observedEnabled: boolean | undefined
45
+ gate: { floorFraction: number, growthTokens: number }
46
+ lastFold: IntentFoldRecord | undefined
47
+ }
48
+
49
+ export interface MonitorContextBlock {
50
+ liveTokens: number
51
+ contextWindow: number | undefined
52
+ /** liveTokens / contextWindow, rounded to 3 decimals; null when the window is unknown. */
53
+ pct: number | null
54
+ sessionId: string
55
+ }
56
+
57
+ export type MonitorSnapshot = SavingsSnapshot & {
58
+ intent: MonitorIntentBlock
59
+ /** Latest observed context occupancy; undefined until the pruner observes a turn. */
60
+ context?: MonitorContextBlock
61
+ /** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
62
+ sessionScope: string | null
63
+ }
64
+
65
+ /**
66
+ * Savings snapshot plus the intent-summary control block. Ledger is
67
+ * injectable so tests seed a private instance instead of the process
68
+ * singleton.
69
+ */
70
+ export function buildMonitorSnapshot(
71
+ sessionId?: string,
72
+ ledger: SavingsLedger = getSavingsLedger(),
73
+ ): MonitorSnapshot {
74
+ const scopeKey = sessionId ?? ''
75
+ const override = getSummaryOverride(scopeKey)
76
+ const observedContext = scopeKey.length > 0
77
+ ? getContextUsage(scopeKey)
78
+ : latestObservedContextUsage()
79
+ const contextBlock = observedContext === undefined
80
+ ? undefined
81
+ : {
82
+ liveTokens: observedContext.liveTokens,
83
+ contextWindow: observedContext.contextWindow,
84
+ pct: observedContext.contextWindow !== undefined && observedContext.contextWindow > 0
85
+ ? Math.round((observedContext.liveTokens / observedContext.contextWindow) * 1000) / 1000
86
+ : null,
87
+ sessionId: observedContext.sessionId,
88
+ }
89
+ return {
90
+ ...ledger.snapshot(sessionId),
91
+ ...(contextBlock === undefined ? {} : { context: contextBlock }),
92
+ intent: {
93
+ override,
94
+ observedEnabled: getObservedIntentEnabled(scopeKey),
95
+ gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
96
+ lastFold: getLastIntentFold(scopeKey),
97
+ },
98
+ sessionScope: sessionId ?? null,
99
+ }
100
+ }
101
+
102
+ export interface ContextUsageObservation {
103
+ liveTokens: number
104
+ contextWindow: number | undefined
105
+ }
106
+
107
+ /** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
108
+ const contextUsageBySession = new Map<string, ContextUsageObservation & { at: number; seq: number }>()
109
+ const CONTEXT_USAGE_CAP = 64
110
+
111
+ /**
112
+ * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
113
+ * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
114
+ */
115
+ export function observeContextUsage(sessionId: string, liveTokens: number, contextWindow: number | undefined): void {
116
+ if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return
117
+ if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
118
+ const oldest = contextUsageBySession.keys().next().value
119
+ if (oldest !== undefined) contextUsageBySession.delete(oldest)
120
+ }
121
+ contextUsageBySession.set(sessionId, { liveTokens, contextWindow, at: Date.now(), seq: ++observeSeq })
122
+ }
123
+
124
+ export function getContextUsage(sessionId: string): (ContextUsageObservation & { sessionId: string }) | undefined {
125
+ const entry = contextUsageBySession.get(sessionId)
126
+ return entry === undefined ? undefined : { liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, sessionId }
127
+ }
128
+
129
+ let observeSeq = 0
130
+
131
+ function latestObservedContextUsage(): (ContextUsageObservation & { sessionId: string }) | undefined {
132
+ let latest: (ContextUsageObservation & { sessionId: string; seq: number }) | undefined
133
+ for (const [sessionId, entry] of contextUsageBySession) {
134
+ if (latest === undefined || entry.seq > latest.seq) latest = { sessionId, liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, seq: entry.seq }
135
+ }
136
+ return latest
137
+ }
138
+
139
+ export type SessionOverrideAction = 'on' | 'off' | 'clear'
140
+
141
+ export function isSessionOverrideAction(value: unknown): value is SessionOverrideAction {
142
+ return value === 'on' || value === 'off' || value === 'clear'
143
+ }
144
+
145
+ /**
146
+ * Drive the `/ctx-summary` override state machine: `on`/`off` pin the
147
+ * session, `clear` returns it to settings-driven. The resulting override is
148
+ * handed back so the route can echo the post-action truth.
149
+ */
150
+ export function applySessionOverride(
151
+ sessionId: string,
152
+ action: SessionOverrideAction,
153
+ ): { override: 'on' | 'off' | undefined } {
154
+ setSummaryOverride(sessionId, action === 'clear' ? undefined : action)
155
+ return { override: getSummaryOverride(sessionId) }
156
+ }
157
+
158
+ /**
159
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
160
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
161
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
162
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
163
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
164
+ * (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
165
+ */
166
+ export function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
167
+ startedAt: string
168
+ net: { exact: number; estimated: number }
169
+ usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
170
+ }): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
171
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
172
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
173
+ const selection = defaults?.currentSelection?.()
174
+ const provider = typeof selection?.provider === 'string' ? selection.provider : ''
175
+ const modelId = typeof selection?.model === 'string' ? selection.model : ''
176
+ if (provider !== 'deepseek-official') return undefined
177
+ const now = new Date()
178
+ const startedAt = new Date(snapshot.startedAt)
179
+ const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
180
+ const base = {
181
+ provider,
182
+ baseUrlClass: 'official-public',
183
+ apiRoute: 'chat-completions',
184
+ modelId,
185
+ currency: 'USD',
186
+ startedAt,
187
+ completedAt,
188
+ } as const
189
+ const actual = priceOfficialDeepSeekUsage({
190
+ ...base,
191
+ usage: {
192
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
193
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
194
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
195
+ },
196
+ })
197
+ const saved = snapshot.net.exact > 0
198
+ ? priceOfficialDeepSeekUsage({
199
+ ...base,
200
+ usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
201
+ })
202
+ : undefined
203
+ const decimalOf = (cost: typeof actual): string | undefined =>
204
+ cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
205
+ if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
206
+ return {
207
+ currency: 'USD',
208
+ ...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
209
+ ...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
210
+ }
211
+ }
@@ -141,6 +141,11 @@ export interface IntentSummarySettings {
141
141
  enabled: boolean
142
142
  }
143
143
 
144
+ /** Floating compression-monitor panel (FAB); visibility switch. */
145
+ export interface MonitorPanelSettings {
146
+ enabled: boolean
147
+ }
148
+
144
149
  /**
145
150
  * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
146
151
  * Absent fields inherit the preset defaults; the section is only meaningful
@@ -183,6 +188,8 @@ export interface ContextCompressionSettings {
183
188
  codeSkeleton: CodeSkeletonSettings
184
189
  /** Turn-tail intent-summary gate snapped independently of `profile`. */
185
190
  intentSummary: IntentSummarySettings
191
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
192
+ monitorPanel?: MonitorPanelSettings
186
193
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
187
194
  presetOptions?: PresetOptionsSettings
188
195
  }
@@ -59,9 +59,9 @@ describe('codeSkeleton confirm-on-write client contract', () => {
59
59
  configForms: { get: vi.fn(() => form) },
60
60
  slots: {
61
61
  inject: (_slot: string, install: () => unknown) => { install() },
62
- register: (registration: { inject?: () => CompressionSelectorInjected }) => {
62
+ register: (registration: { name?: string, inject?: () => CompressionSelectorInjected }) => {
63
63
  // The R4 overlay registration carries no inject face; keep the card's.
64
- if (typeof registration.inject === 'function') injected = registration.inject
64
+ if (registration.name === 'settings.section' && typeof registration.inject === 'function') injected = registration.inject
65
65
  return () => {}
66
66
  },
67
67
  },
@@ -167,9 +167,9 @@ describe('context compression browser contract', () => {
167
167
  },
168
168
  slots: {
169
169
  inject: (_slot: string, install: () => unknown) => { install() },
170
- register: (registration: { inject?: () => CompressionSelectorInjected }) => {
170
+ register: (registration: { name?: string, inject?: () => CompressionSelectorInjected }) => {
171
171
  // The R4 overlay registration carries no inject face; keep the card's.
172
- if (typeof registration.inject === 'function') injected = registration.inject
172
+ if (registration.name === 'settings.section' && typeof registration.inject === 'function') injected = registration.inject
173
173
  return () => {}
174
174
  },
175
175
  },
@@ -17,6 +17,8 @@ const CATALOG_ROUTE = '/api/dsh-context-compression-improved/estimator-catalog'
17
17
  const LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/estimator-catalog'
18
18
  const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
19
19
  const SAVINGS_LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/savings'
20
+ const MONITOR_ROUTE = '/api/dsh-context-compression-improved/monitor'
21
+ const MONITOR_LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/monitor'
20
22
 
21
23
  interface RegisteredRoute {
22
24
  kind: string
@@ -106,7 +108,7 @@ describe('estimator catalog route registration', () => {
106
108
  apply(runtime, { estimatorCatalogRoute: true })
107
109
  await settle()
108
110
 
109
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
111
+ expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
110
112
  expect(routes.every(route => route.kind === 'exact')).toBe(true)
111
113
  })
112
114
 
@@ -122,7 +124,7 @@ describe('estimator catalog route registration', () => {
122
124
  await mountWebServer(runtime, routes)
123
125
  await settle()
124
126
 
125
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
127
+ expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
126
128
  })
127
129
 
128
130
  it('registers nothing twice when the estimator services arrive later', async () => {
@@ -176,9 +178,9 @@ describe('estimator catalog route registration', () => {
176
178
  expect(JSON.parse(String(response.body))).toMatchObject({ ok: true, providers: [] })
177
179
  })
178
180
 
179
- it('without the estimator opt-in only the always-on savings snapshot route registers', async () => {
180
- // savings 路由是有意常开的只读面(纯 token 聚合,无会话内容);estimator
181
- // catalog 才是 opt-in 行。默认面 = 恰好两条 savings 前缀。
181
+ it('without the estimator opt-in only the always-on read routes register (savings + monitor)', async () => {
182
+ // savings 与 monitor 路由是有意常开的只读面(纯 token 聚合与折叠状态,无会话内容);estimator
183
+ // catalog 才是 opt-in 行。默认面 = 恰好两条 savings 前缀 + 两条 monitor 前缀。
182
184
  const routes: RegisteredRoute[] = []
183
185
  const runtime = new Context()
184
186
  ctx = runtime
@@ -187,6 +189,6 @@ describe('estimator catalog route registration', () => {
187
189
  apply(runtime, { presetOverlay: false })
188
190
  await settle()
189
191
 
190
- expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
192
+ expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
191
193
  })
192
194
  })