dsh-context-compression-improved 0.8.0-beta.3 → 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.
- package/CHANGELOG.md +20 -0
- package/eslint.config.js +30 -30
- package/package.json +163 -163
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +28 -0
- package/packages/selector/lib/client.js +631 -7
- package/packages/selector/lib/{advisor-state.js → config.js} +170 -65
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +306 -50
- package/packages/selector/lib/profiles.d.ts +15 -0
- package/packages/selector/lib/pruner.d.ts +65 -0
- package/packages/selector/lib/pruner.js +408 -5
- package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +41 -0
- package/packages/selector/src/client/locales/de.ts +26 -0
- package/packages/selector/src/client/locales/es.ts +26 -0
- package/packages/selector/src/client/locales/fr.ts +26 -0
- package/packages/selector/src/client/locales/it.ts +26 -0
- package/packages/selector/src/client/locales/ja.ts +26 -0
- package/packages/selector/src/client/locales/ko.ts +26 -0
- package/packages/selector/src/client/locales/ru.ts +26 -0
- package/packages/selector/src/client/locales.ts +52 -0
- package/packages/selector/src/client/monitor-fab.ts +307 -0
- package/packages/selector/src/client/settings-section.tsx +16 -2
- package/packages/selector/src/index.ts +133 -60
- package/packages/selector/src/profiles.ts +431 -394
- package/packages/selector/src/pruner/state.ts +57 -50
- package/packages/selector/src/pruner.ts +241 -1
- package/packages/selector/src/runtime/audit.ts +303 -286
- package/packages/selector/src/runtime/config.ts +756 -706
- package/packages/selector/src/runtime/monitor.ts +149 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/types.ts +365 -346
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
- package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
- package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/runtime/audit.spec.ts +275 -274
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +236 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -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 } 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,
|
|
29
|
+
useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
|
|
30
30
|
savePresetOptions, t,
|
|
31
31
|
}: CompressionProfileSelectorProps) {
|
|
32
32
|
const state = useCompression(snapshot => snapshot)
|
|
@@ -103,6 +103,20 @@ export function SettingsCompressionProfileControls({
|
|
|
103
103
|
settle={settle}
|
|
104
104
|
t={t}
|
|
105
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
|
+
/>
|
|
106
120
|
{current !== 'tokenpilot-inspired' ? (
|
|
107
121
|
<EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
|
|
108
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 {
|
|
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,
|
|
@@ -12,6 +18,7 @@ import {
|
|
|
12
18
|
} from './runtime/config.ts'
|
|
13
19
|
|
|
14
20
|
import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
|
|
21
|
+
import { registerSummaryCommand } from './runtime/summary-command.ts'
|
|
15
22
|
|
|
16
23
|
// The settings namespace literal and the settings schema are owned by the
|
|
17
24
|
// runtime config module. Both were once inlined/replaced here to dodge a
|
|
@@ -45,6 +52,11 @@ const SAVINGS_ROUTES = [
|
|
|
45
52
|
'/api/dsh-context-compression-improved/savings',
|
|
46
53
|
] as const
|
|
47
54
|
|
|
55
|
+
const MONITOR_ROUTES = [
|
|
56
|
+
'/endpoint/dsh-context-compression-improved/monitor',
|
|
57
|
+
'/api/dsh-context-compression-improved/monitor',
|
|
58
|
+
] as const
|
|
59
|
+
|
|
48
60
|
/** Minimal face of the agents service: session id → agent (carrying the session). */
|
|
49
61
|
interface AgentsServiceLike {
|
|
50
62
|
get?(id: unknown): { session?: unknown } | undefined
|
|
@@ -183,11 +195,6 @@ interface WebServerLike {
|
|
|
183
195
|
}
|
|
184
196
|
|
|
185
197
|
/** The estimator-side service the catalog handler enriches its response with. */
|
|
186
|
-
interface AgentDefaultModelLike {
|
|
187
|
-
/** Current host model-group selection, when the service exposes one. */
|
|
188
|
-
currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
|
|
189
|
-
}
|
|
190
|
-
|
|
191
198
|
function asWebServer(value: unknown): WebServerLike | undefined {
|
|
192
199
|
if (typeof value !== 'object' || value === null) return undefined
|
|
193
200
|
const candidate = value as { register?: unknown }
|
|
@@ -299,60 +306,6 @@ function registerEstimatorCatalogRoute(ctx: Context): void {
|
|
|
299
306
|
log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
|
|
300
307
|
}
|
|
301
308
|
|
|
302
|
-
/**
|
|
303
|
-
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
304
|
-
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
305
|
-
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
306
|
-
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
307
|
-
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
308
|
-
*/
|
|
309
|
-
function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
|
|
310
|
-
startedAt: string
|
|
311
|
-
net: { exact: number; estimated: number }
|
|
312
|
-
usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
|
|
313
|
-
}): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
|
|
314
|
-
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
|
|
315
|
-
const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
|
|
316
|
-
const selection = defaults?.currentSelection?.()
|
|
317
|
-
const provider = typeof selection?.provider === 'string' ? selection.provider : ''
|
|
318
|
-
const modelId = typeof selection?.model === 'string' ? selection.model : ''
|
|
319
|
-
if (provider !== 'deepseek-official') return undefined
|
|
320
|
-
const now = new Date()
|
|
321
|
-
const startedAt = new Date(snapshot.startedAt)
|
|
322
|
-
const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
323
|
-
const base = {
|
|
324
|
-
provider,
|
|
325
|
-
baseUrlClass: 'official-public',
|
|
326
|
-
apiRoute: 'chat-completions',
|
|
327
|
-
modelId,
|
|
328
|
-
currency: 'USD',
|
|
329
|
-
startedAt,
|
|
330
|
-
completedAt,
|
|
331
|
-
} as const
|
|
332
|
-
const actual = priceOfficialDeepSeekUsage({
|
|
333
|
-
...base,
|
|
334
|
-
usage: {
|
|
335
|
-
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
336
|
-
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
337
|
-
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
|
|
338
|
-
},
|
|
339
|
-
})
|
|
340
|
-
const saved = snapshot.net.exact > 0
|
|
341
|
-
? priceOfficialDeepSeekUsage({
|
|
342
|
-
...base,
|
|
343
|
-
usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
|
|
344
|
-
})
|
|
345
|
-
: undefined
|
|
346
|
-
const decimalOf = (cost: typeof actual): string | undefined =>
|
|
347
|
-
cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
|
|
348
|
-
if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
|
|
349
|
-
return {
|
|
350
|
-
currency: 'USD',
|
|
351
|
-
...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
|
|
352
|
-
...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
309
|
/**
|
|
357
310
|
* Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
|
|
358
311
|
* offsets (negative savings — compressed content later re-read in full), and net,
|
|
@@ -425,6 +378,119 @@ function registerSavingsRoute(ctx: Context): void {
|
|
|
425
378
|
})
|
|
426
379
|
}
|
|
427
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
|
+
|
|
428
494
|
/**
|
|
429
495
|
* Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
|
|
430
496
|
* otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
|
|
@@ -499,10 +565,17 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
499
565
|
if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
|
|
500
566
|
// 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
|
|
501
567
|
registerSavingsRoute(ctx)
|
|
568
|
+
registerMonitorRoute(ctx)
|
|
502
569
|
|
|
503
570
|
// Advisory advisor: read-only decay/score/advice report (opt-in).
|
|
504
571
|
if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
|
|
505
572
|
|
|
573
|
+
// Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
|
|
574
|
+
// free to register and stays quiet on hosts without the commands
|
|
575
|
+
// registry; the capability itself is gated by the frozen `intentSummary`
|
|
576
|
+
// setting plus the session-scoped override this command controls.
|
|
577
|
+
registerSummaryCommand(ctx)
|
|
578
|
+
|
|
506
579
|
if (config.presetOverlay !== true) return
|
|
507
580
|
|
|
508
581
|
ctx.inject(['agentPresets'], (presetsCtx) => {
|