dsh-context-compression-improved 0.8.0-beta.4 → 0.8.0-beta.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 (36) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/package.json +1 -1
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +22 -0
  5. package/packages/selector/lib/client.js +528 -3
  6. package/packages/selector/lib/{intent-gate.js → config.js} +153 -136
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +215 -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 +1 -1
  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 +37 -0
  16. package/packages/selector/src/client/locales/de.ts +21 -0
  17. package/packages/selector/src/client/locales/es.ts +21 -0
  18. package/packages/selector/src/client/locales/fr.ts +21 -0
  19. package/packages/selector/src/client/locales/it.ts +21 -0
  20. package/packages/selector/src/client/locales/ja.ts +21 -0
  21. package/packages/selector/src/client/locales/ko.ts +21 -0
  22. package/packages/selector/src/client/locales/ru.ts +21 -0
  23. package/packages/selector/src/client/locales.ts +42 -0
  24. package/packages/selector/src/client/monitor-fab.ts +307 -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/runtime/config.ts +26 -1
  29. package/packages/selector/src/runtime/monitor.ts +149 -0
  30. package/packages/selector/src/runtime/types.ts +7 -0
  31. package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
  32. package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
  33. package/packages/selector/tests/runtime/monitor.spec.ts +236 -0
  34. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  35. package/scripts/packed-install-e2e.mjs +1 -1
  36. package/scripts/verify-release.mjs +1 -1
@@ -0,0 +1,307 @@
1
+ /**
2
+ * 压缩监控浮动球 + 面板(task: cci-monitor-fab;骨架整编自 pm 撤下的
3
+ * `longtask-fab.ts` — d29bcb1^, VANILLA DOM overlay 模式: FAB + 面板
4
+ * appendChild 到 document.body, position:fixed + JS 内联定位, Pointer Events
5
+ * 拖拽 + localStorage 持久化 + 视口夹紧)。
6
+ *
7
+ * cci 客户端纪律:
8
+ * - body 级直挂 = 幂等单例,应用生命周期存续,不做 dispose(页面刷新自然回收);
9
+ * - 回声环过滤:自有节点带 `dsh-cci-parasite` 类,不参与宿主面板探测;
10
+ * - 数据面: `/api/.../monitor` 忙 2s / 闲 5s 自调度轮询(savings 卡同口径),
11
+ * fetch 失败静默降级 + 陈旧标记——监控面板永不打扰主流程;
12
+ * - 动作面: 仅会话覆盖(POST,复用 /ctx-summary 状态机),不做压缩执行。
13
+ *
14
+ * 显隐: `enabledOf()`(设置文档 monitorPanel.enabled)为总闸;总闸开才显示球;
15
+ * 净节省为负时「点亮」呼吸态(负节省警示)。v1 监控全会话聚合(savings 卡同
16
+ * 口径),覆盖作用于默认会话;会话级绑定待 cci 有输入栏座位后另行接线。
17
+ */
18
+
19
+ const FAB_ID = 'dsh-cci-monitor-fab';
20
+ const PANEL_ID = 'dsh-cci-monitor-panel';
21
+ const STYLE_ID = 'dsh-cci-monitor-style';
22
+ const PARASITE = 'dsh-cci-parasite';
23
+ const POS_KEY = 'dsh.cci.monitor.pos';
24
+
25
+ /** `/monitor` 快照的消费侧窄化(服务端契约在路由 spec 钉住;此处自断言)。 */
26
+ export interface MonitorSnapshotPayload {
27
+ ok?: unknown
28
+ startedAt?: unknown
29
+ gross?: { exact?: unknown; estimated?: unknown }
30
+ offsets?: { exact?: unknown; estimated?: unknown }
31
+ net?: { exact?: unknown; estimated?: unknown }
32
+ usage?: { requests?: unknown; cacheHitRate?: unknown }
33
+ pricing?: { currency?: unknown; actualCost?: unknown; estimatedSavedCost?: unknown }
34
+ intent?: {
35
+ override?: 'on' | 'off' | undefined
36
+ observedEnabled?: boolean | undefined
37
+ gate?: { floorFraction?: unknown; growthTokens?: unknown }
38
+ lastFold?: { turn?: unknown; startSeq?: unknown; endSeq?: unknown } | undefined
39
+ }
40
+ recentOffsets?: Array<{ component?: unknown; tokens?: unknown }>
41
+ sessionScope?: string | null
42
+ }
43
+
44
+ export type MonitorAction = 'on' | 'off' | 'clear'
45
+
46
+ export interface MonitorFabDeps {
47
+ /** bind(NS) 的活性翻译器:漏译回退键名,跟随宿主语言切换。 */
48
+ t: (key: string) => string
49
+ fetchSnapshot: (sessionId: string | undefined) => Promise<MonitorSnapshotPayload>
50
+ applyOverride: (sessionId: string | undefined, action: MonitorAction) => Promise<void>
51
+ sessionIdOf: () => string | undefined
52
+ enabledOf: () => boolean
53
+ /** 首轮轮询延迟(ms);测试注入 1ms 走真实时钟。 */
54
+ initialDelayMs?: number
55
+ }
56
+
57
+ const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
58
+
59
+ export function initMonitorFab(deps: MonitorFabDeps): void {
60
+ if (document.getElementById(FAB_ID) !== null) return;
61
+ const { t } = deps;
62
+
63
+ const style = document.createElement('style');
64
+ style.id = STYLE_ID;
65
+ style.textContent = `
66
+ #${FAB_ID} { position: fixed; z-index: 9999; width: 42px; height: 42px; border-radius: 50%;
67
+ background: rgba(30,30,32,.72); backdrop-filter: blur(22px) saturate(180%);
68
+ border: 1px solid rgba(255,255,255,.14); box-shadow: 0 8px 24px rgba(0,0,0,.4);
69
+ color: #f5f5f7; font-size: 18px; line-height: 40px; text-align: center; cursor: grab;
70
+ touch-action: none; user-select: none; display: none; transition: transform .18s; }
71
+ #${FAB_ID}:hover { transform: scale(1.08); }
72
+ #${FAB_ID}.lit { display: block; box-shadow: 0 0 0 5px rgba(255,159,10,.28), 0 8px 24px rgba(0,0,0,.4);
73
+ animation: dsh-cci-mon-breathe 2.4s ease-in-out infinite; }
74
+ @keyframes dsh-cci-mon-breathe { 0%,100% { box-shadow: 0 0 0 4px rgba(255,159,10,.18), 0 8px 24px rgba(0,0,0,.4); }
75
+ 50% { box-shadow: 0 0 0 8px rgba(255,159,10,.32), 0 8px 24px rgba(0,0,0,.4); } }
76
+ #${PANEL_ID} { position: fixed; z-index: 9998; width: 336px; border-radius: 14px;
77
+ background: rgba(28,28,30,.78); backdrop-filter: blur(26px) saturate(180%);
78
+ border: 1px solid rgba(255,255,255,.12); box-shadow: 0 14px 44px rgba(0,0,0,.55);
79
+ color: #f5f5f7; font-size: 12.5px; opacity: 0; pointer-events: none;
80
+ transform: translateY(10px) scale(.92); transform-origin: 88% 100%;
81
+ transition: opacity .22s cubic-bezier(.16,.8,.3,1.05), transform .22s cubic-bezier(.16,.8,.3,1.1); }
82
+ #${PANEL_ID}.open { opacity: 1; pointer-events: auto; transform: none; }
83
+ #${PANEL_ID} h4 { margin: 0; padding: 10px 14px 8px; font-size: 13px; cursor: grab;
84
+ touch-action: none; user-select: none; border-bottom: 1px solid rgba(255,255,255,.09); }
85
+ #${PANEL_ID} .row { display: flex; align-items: center; gap: 8px; padding: 6px 14px; }
86
+ #${PANEL_ID} .row.label { width: 108px; flex: none; color: rgba(245,245,247,.55); }
87
+ #${PANEL_ID} .muted { color: rgba(245,245,247,.55); }
88
+ #${PANEL_ID} .neg { color: #ff9f0a; }
89
+ #${PANEL_ID} button { font: inherit; border-radius: 8px; border: 1px solid rgba(255,255,255,.18);
90
+ background: rgba(10,132,255,.85); color: #fff; padding: 4px 10px; cursor: pointer; }
91
+ #${PANEL_ID} button.ghost { background: transparent; }
92
+ #${PANEL_ID} button:disabled { opacity: .45; cursor: default; }
93
+ #${PANEL_ID} .stale { padding: 4px 14px 8px; color: #ffd60a; display: none; }
94
+ #${PANEL_ID} .stale.show { display: block; }
95
+ #${PANEL_ID} .recent { max-height: 132px; overflow: auto; padding: 2px 14px 8px;
96
+ color: rgba(245,245,247,.8); white-space: pre-wrap; }
97
+ `;
98
+ document.head.appendChild(style);
99
+
100
+ const fab = document.createElement('div');
101
+ fab.id = FAB_ID;
102
+ fab.className = PARASITE;
103
+ fab.textContent = '📉';
104
+ fab.title = t('monitor.fab.title');
105
+ const panel = document.createElement('div');
106
+ panel.id = PANEL_ID;
107
+ panel.className = PARASITE;
108
+ panel.hidden = true;
109
+ panel.innerHTML = `
110
+ <h4>${t('monitor.panel.title')}</h4>
111
+ <div class="row"><span class="label">${t('monitor.panel.net')}</span><span data-net>–</span></div>
112
+ <div class="row"><span class="label">${t('monitor.panel.gross')}</span><span data-gross class="muted">–</span></div>
113
+ <div class="row"><span class="label">${t('monitor.panel.offsets')}</span><span data-offsets class="muted">–</span></div>
114
+ <div class="row"><span class="label">${t('monitor.panel.cacheHit')}</span><span data-cache class="muted">–</span></div>
115
+ <div class="row"><span class="label">${t('monitor.panel.cost')}</span><span data-cost class="muted">–</span></div>
116
+ <div class="row"><span class="label">${t('monitor.panel.intent')}</span><span data-intent class="muted">–</span></div>
117
+ <div class="row"><span class="label">${t('monitor.panel.overrideHint')}</span>
118
+ <button data-overon>${t('monitor.panel.resume')}</button>
119
+ <button data-overoff class="ghost">${t('monitor.panel.disable')}</button></div>
120
+ <div class="row muted" data-fold style="display:none"></div>
121
+ <div class="stale" data-stale>${t('monitor.panel.stale')}</div>
122
+ <div class="recent" data-recent></div>
123
+ `;
124
+ document.body.append(fab, panel);
125
+
126
+ // 位置:localStorage 恢复 + 视口夹紧(pm 骨架原样)
127
+ let pos: { x: number; y: number };
128
+ try {
129
+ pos = JSON.parse(localStorage.getItem(POS_KEY) ?? 'null') ?? {
130
+ x: Math.max(8, window.innerWidth - 66),
131
+ y: Math.max(8, Math.round(window.innerHeight * 0.6)),
132
+ };
133
+ } catch {
134
+ pos = { x: Math.max(8, window.innerWidth - 66), y: Math.max(8, Math.round(window.innerHeight * 0.6)) };
135
+ }
136
+ const clamp = (p: { x: number; y: number }): { x: number; y: number } => ({
137
+ x: Math.max(8, Math.min(window.innerWidth - 50, p.x)),
138
+ y: Math.max(8, Math.min(window.innerHeight - 50, p.y)),
139
+ });
140
+ const place = (): void => {
141
+ pos = clamp(pos);
142
+ fab.style.left = `${pos.x}px`;
143
+ fab.style.top = `${pos.y}px`;
144
+ };
145
+ place();
146
+ window.addEventListener('resize', place);
147
+
148
+ const makeDrag = (el: HTMLElement, key: 'fab' | 'panel'): void => {
149
+ let active = false;
150
+ let moved = false;
151
+ let origin = { x: 0, y: 0 };
152
+ el.addEventListener('pointerdown', (e) => {
153
+ active = true;
154
+ moved = false;
155
+ origin = { x: e.clientX, y: e.clientY };
156
+ el.setPointerCapture(e.pointerId);
157
+ });
158
+ el.addEventListener('pointermove', (e) => {
159
+ if (!active) return;
160
+ const next = clamp({ x: pos.x + e.clientX - origin.x, y: pos.y + e.clientY - origin.y });
161
+ if (Math.abs(next.x - pos.x) > 2 || Math.abs(next.y - pos.y) > 2) moved = true;
162
+ pos = key === 'fab' ? next : pos;
163
+ if (key === 'fab') place();
164
+ });
165
+ el.addEventListener('pointerup', () => {
166
+ active = false;
167
+ if (moved && key === 'fab') {
168
+ try { localStorage.setItem(POS_KEY, JSON.stringify(pos)); } catch { /* 隐私模式:位置不持久化 */ }
169
+ }
170
+ });
171
+ el.addEventListener('pointercancel', () => {
172
+ active = false;
173
+ });
174
+ };
175
+ let suppressClick = false;
176
+ makeDrag(fab, 'fab');
177
+
178
+ let open = false;
179
+ fab.addEventListener('click', () => {
180
+ if (suppressClick) {
181
+ suppressClick = false;
182
+ return;
183
+ }
184
+ open = !open;
185
+ if (open) {
186
+ panel.hidden = false;
187
+ const px = Math.max(8, Math.min(window.innerWidth - 344, pos.x - 300));
188
+ const py = pos.y - 300 < 8 ? pos.y + 46 : Math.max(8, pos.y - 300);
189
+ panel.style.left = `${px}px`;
190
+ panel.style.top = `${py}px`;
191
+ void panel.offsetHeight;
192
+ panel.classList.add('open');
193
+ } else {
194
+ panel.classList.remove('open');
195
+ setTimeout(() => {
196
+ panel.hidden = true;
197
+ }, 240);
198
+ }
199
+ });
200
+ makeDrag(panel.querySelector('h4') as HTMLElement, 'panel');
201
+
202
+ // 状态与轮询
203
+ let last: MonitorSnapshotPayload | undefined;
204
+ let stale = false;
205
+ let busyAction = false;
206
+
207
+ const fmtTokens = (n: unknown): string => num(n).toLocaleString('en-US');
208
+
209
+ const render = (snap: MonitorSnapshotPayload): void => {
210
+ last = snap;
211
+ const net = num(snap.net?.exact) + num(snap.net?.estimated);
212
+ const netEl = panel.querySelector('[data-net]') as HTMLElement;
213
+ netEl.textContent = `${net >= 0 ? '' : ''}${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ''}`;
214
+ netEl.classList.toggle('neg', net < 0);
215
+ fab.classList.toggle('lit', net < 0);
216
+ (panel.querySelector('[data-gross]') as HTMLElement).textContent = fmtTokens(snap.gross?.exact);
217
+ (panel.querySelector('[data-offsets]') as HTMLElement).textContent = `-${fmtTokens(snap.offsets?.exact)}`;
218
+ const hit = snap.usage?.cacheHitRate;
219
+ (panel.querySelector('[data-cache]') as HTMLElement).textContent =
220
+ typeof hit === 'number' ? `${Math.round(hit * 100)}%` : '–';
221
+ const pricing = snap.pricing;
222
+ (panel.querySelector('[data-cost]') as HTMLElement).textContent =
223
+ pricing?.actualCost === undefined && pricing?.estimatedSavedCost === undefined
224
+ ? '–'
225
+ : `${pricing?.actualCost ?? '–'} / -${pricing?.estimatedSavedCost ?? '–'} ${String(pricing?.currency ?? '')}`.trim();
226
+ const intentEl = panel.querySelector('[data-intent]') as HTMLElement;
227
+ const override = snap.intent?.override;
228
+ const observed = snap.intent?.observedEnabled;
229
+ intentEl.textContent = override === 'on' || override === 'off'
230
+ ? `${t('monitor.panel.overridePrefix')} ${override === 'on' ? t('monitor.panel.stateOn') : t('monitor.panel.stateOff')}`
231
+ : observed === undefined
232
+ ? t('monitor.panel.gateUnknown')
233
+ : observed ? t('monitor.panel.stateOn') : t('monitor.panel.stateOff');
234
+ const fold = snap.intent?.lastFold;
235
+ const foldEl = panel.querySelector('[data-fold]') as HTMLElement;
236
+ if (fold !== undefined && fold !== null && typeof fold === 'object') {
237
+ foldEl.style.display = '';
238
+ foldEl.textContent = `${t('monitor.panel.lastFold')} turn ${String(fold.turn ?? '–')}, seq ${String(fold.startSeq ?? '–')}..${String(fold.endSeq ?? '–')}`;
239
+ } else {
240
+ foldEl.style.display = 'none';
241
+ }
242
+ const recent = Array.isArray(snap.recentOffsets) ? snap.recentOffsets.slice(0, 3) : [];
243
+ (panel.querySelector('[data-recent]') as HTMLElement).textContent = recent.length === 0
244
+ ? t('savings.empty')
245
+ : recent
246
+ .map((entry: { component?: unknown; tokens?: unknown }) => {
247
+ const e = entry as { component?: unknown; tokens?: unknown };
248
+ return `${String(e.component ?? '–')}: ${fmtTokens(e.tokens)}`;
249
+ })
250
+ .join('\n');
251
+ for (const [selector, action] of [
252
+ ['[data-overon]', 'on'],
253
+ ['[data-overoff]', 'off'],
254
+ ] as const) {
255
+ (panel.querySelector(selector) as HTMLButtonElement).disabled = busyAction || override === action;
256
+ }
257
+ };
258
+
259
+ const markStale = (isStale: boolean): void => {
260
+ stale = isStale;
261
+ (panel.querySelector('[data-stale]') as HTMLElement).classList.toggle('show', stale);
262
+ };
263
+
264
+ const tick = async (): Promise<void> => {
265
+ const enabled = deps.enabledOf();
266
+ fab.style.display = enabled ? 'block' : 'none';
267
+ if (!enabled) {
268
+ if (open) {
269
+ open = false;
270
+ panel.classList.remove('open');
271
+ panel.hidden = true;
272
+ }
273
+ setTimeout(tick, 5000);
274
+ return;
275
+ }
276
+ try {
277
+ const snap = await deps.fetchSnapshot(deps.sessionIdOf());
278
+ markStale(false);
279
+ render(snap);
280
+ } catch {
281
+ /* 快照不可达:静默 + 陈旧标记,不打扰主流程 */
282
+ markStale(true);
283
+ }
284
+ setTimeout(tick, open ? 2000 : 5000);
285
+ };
286
+ setTimeout(tick, deps.initialDelayMs ?? 1500);
287
+
288
+ const wireOverride = (selector: string, action: MonitorAction): void => {
289
+ panel.querySelector(selector)?.addEventListener('click', async () => {
290
+ if (busyAction) return;
291
+ busyAction = true;
292
+ try {
293
+ await deps.applyOverride(deps.sessionIdOf(), action);
294
+ const sid = deps.sessionIdOf();
295
+ const snap = await deps.fetchSnapshot(sid);
296
+ markStale(false);
297
+ render(snap);
298
+ } catch {
299
+ markStale(true);
300
+ } finally {
301
+ busyAction = false;
302
+ }
303
+ });
304
+ };
305
+ wireOverride('[data-overon]', 'on');
306
+ wireOverride('[data-overoff]', 'off');
307
+ }
@@ -15,7 +15,7 @@ import {
15
15
  type CustomCompressionPolicyV3,
16
16
  } from '../profiles.ts'
17
17
  import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
18
- import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls } from './CompressionProfileControls.tsx'
18
+ import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
19
19
  import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
20
20
  import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
21
21
  import { SavingsCard } from './savings-card'
@@ -26,7 +26,7 @@ export function ContextCompressionSettingsSection(props: CompressionProfileSelec
26
26
  }
27
27
 
28
28
  export function SettingsCompressionProfileControls({
29
- useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary,
29
+ useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
30
30
  savePresetOptions, t,
31
31
  }: CompressionProfileSelectorProps) {
32
32
  const state = useCompression(snapshot => snapshot)
@@ -110,6 +110,13 @@ export function SettingsCompressionProfileControls({
110
110
  settle={settle}
111
111
  t={t}
112
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
+ />
113
120
  {current !== 'tokenpilot-inspired' ? (
114
121
  <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
115
122
  ) : (
@@ -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
  }
@@ -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
  },