dsh-context-compression-improved 0.8.0-beta.5 → 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.
- package/CHANGELOG.md +16 -0
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +58 -19
- package/packages/selector/lib/config.js +133 -1
- package/packages/selector/lib/index.js +1 -85
- package/packages/selector/lib/pruner.js +5 -3
- package/packages/selector/src/client/index.ts +26 -3
- package/packages/selector/src/client/locales/de.ts +1 -0
- package/packages/selector/src/client/locales/es.ts +1 -0
- package/packages/selector/src/client/locales/fr.ts +1 -0
- package/packages/selector/src/client/locales/it.ts +1 -0
- package/packages/selector/src/client/locales/ja.ts +1 -0
- package/packages/selector/src/client/locales/ko.ts +1 -0
- package/packages/selector/src/client/locales/ru.ts +1 -0
- package/packages/selector/src/client/locales.ts +2 -0
- package/packages/selector/src/client/monitor-fab.ts +13 -0
- package/packages/selector/src/pruner.ts +2 -0
- package/packages/selector/src/runtime/monitor.ts +65 -3
- package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
- package/packages/selector/tests/runtime/monitor.spec.ts +38 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +18 -6
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes use this file. The project follows semantic versioning after `0.1.0`.
|
|
4
4
|
|
|
5
|
+
## 0.8.0-beta.6 - 2026-10-02
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Session binding for the floating monitor**: a deliberately invisible `conversation.input.left`
|
|
10
|
+
seat captures the active session id (pm longtask precedent) — the panel now shows the bound
|
|
11
|
+
session's data and its override buttons act on that session instead of the default one.
|
|
12
|
+
- **Context occupancy bar** in the panel: the turn-tail postflight observes live tokens vs the
|
|
13
|
+
auto-compact-derived window per session; the panel renders the occupancy percentage
|
|
14
|
+
(hot tint past 70%).
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Client specs that captured the settings face by `inject` presence now key off the
|
|
19
|
+
`settings.section` seat explicitly (the input-bar binder's `inject` is a session callback).
|
|
20
|
+
|
|
5
21
|
## 0.8.0-beta.5 - 2026-10-02
|
|
6
22
|
|
|
7
23
|
### Added
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "dsh-external/dsh-context-compression-improved",
|
|
3
|
-
"version": "0.8.0-beta.
|
|
3
|
+
"version": "0.8.0-beta.6",
|
|
4
4
|
"main": "./lib/index.js",
|
|
5
5
|
"description": "Auditable tool-result context-compression selector with code-skeleton gate for DeepSeek Harness",
|
|
6
6
|
"engines": {
|
|
@@ -81,6 +81,7 @@ declare const zh: {
|
|
|
81
81
|
'monitor.panel.net': string;
|
|
82
82
|
'monitor.panel.gross': string;
|
|
83
83
|
'monitor.panel.offsets': string;
|
|
84
|
+
'monitor.panel.context': string;
|
|
84
85
|
'monitor.panel.cacheHit': string;
|
|
85
86
|
'monitor.panel.cost': string;
|
|
86
87
|
'monitor.panel.intent': string;
|
|
@@ -1562,6 +1562,7 @@ window.__ModuleLoader__.load({
|
|
|
1562
1562
|
<div class="row"><span class="label">${t("monitor.panel.net")}</span><span data-net>–</span></div>
|
|
1563
1563
|
<div class="row"><span class="label">${t("monitor.panel.gross")}</span><span data-gross class="muted">–</span></div>
|
|
1564
1564
|
<div class="row"><span class="label">${t("monitor.panel.offsets")}</span><span data-offsets class="muted">–</span></div>
|
|
1565
|
+
<div class="row"><span class="label">${t("monitor.panel.context")}</span><div class="bar"><i data-ctxbar></i></div><span data-ctxpct class="muted">–</span></div>
|
|
1565
1566
|
<div class="row"><span class="label">${t("monitor.panel.cacheHit")}</span><span data-cache class="muted">–</span></div>
|
|
1566
1567
|
<div class="row"><span class="label">${t("monitor.panel.cost")}</span><span data-cost class="muted">–</span></div>
|
|
1567
1568
|
<div class="row"><span class="label">${t("monitor.panel.intent")}</span><span data-intent class="muted">–</span></div>
|
|
@@ -1668,6 +1669,17 @@ window.__ModuleLoader__.load({
|
|
|
1668
1669
|
fab.classList.toggle("lit", net < 0);
|
|
1669
1670
|
panel.querySelector("[data-gross]").textContent = fmtTokens(snap.gross?.exact);
|
|
1670
1671
|
panel.querySelector("[data-offsets]").textContent = `-${fmtTokens(snap.offsets?.exact)}`;
|
|
1672
|
+
const ctxBar = panel.querySelector("[data-ctxbar]");
|
|
1673
|
+
const ctxPct = panel.querySelector("[data-ctxpct]");
|
|
1674
|
+
const ctxPctNum = typeof snap.context?.pct === "number" ? snap.context.pct : null;
|
|
1675
|
+
if (ctxPctNum === null) {
|
|
1676
|
+
ctxBar.style.width = "0%";
|
|
1677
|
+
ctxPct.textContent = "–";
|
|
1678
|
+
} else {
|
|
1679
|
+
ctxBar.style.width = `${Math.min(100, Math.round(ctxPctNum * 100))}%`;
|
|
1680
|
+
ctxBar.parentElement?.classList.toggle("hot", ctxPctNum >= .7);
|
|
1681
|
+
ctxPct.textContent = `${Math.round(ctxPctNum * 100)}%`;
|
|
1682
|
+
}
|
|
1671
1683
|
const hit = snap.usage?.cacheHitRate;
|
|
1672
1684
|
panel.querySelector("[data-cache]").textContent = typeof hit === "number" ? `${Math.round(hit * 100)}%` : "–";
|
|
1673
1685
|
const pricing = snap.pricing;
|
|
@@ -1811,6 +1823,7 @@ window.__ModuleLoader__.load({
|
|
|
1811
1823
|
"monitor.panel.net": "净节省",
|
|
1812
1824
|
"monitor.panel.gross": "毛节省",
|
|
1813
1825
|
"monitor.panel.offsets": "抵消",
|
|
1826
|
+
"monitor.panel.context": "上下文占用",
|
|
1814
1827
|
"monitor.panel.cacheHit": "缓存命中率",
|
|
1815
1828
|
"monitor.panel.cost": "成本(实际 / 省估)",
|
|
1816
1829
|
"monitor.panel.intent": "意图摘要",
|
|
@@ -1947,6 +1960,7 @@ window.__ModuleLoader__.load({
|
|
|
1947
1960
|
"monitor.panel.net": "Net savings",
|
|
1948
1961
|
"monitor.panel.gross": "Gross savings",
|
|
1949
1962
|
"monitor.panel.offsets": "Offsets",
|
|
1963
|
+
"monitor.panel.context": "Context occupancy",
|
|
1950
1964
|
"monitor.panel.cacheHit": "Cache hit rate",
|
|
1951
1965
|
"monitor.panel.cost": "Cost (actual / saved est.)",
|
|
1952
1966
|
"monitor.panel.intent": "Intent summary",
|
|
@@ -2085,6 +2099,7 @@ window.__ModuleLoader__.load({
|
|
|
2085
2099
|
"monitor.panel.net": "Nettoeinsparung",
|
|
2086
2100
|
"monitor.panel.gross": "Bruttoeinsparung",
|
|
2087
2101
|
"monitor.panel.offsets": "Ausgleiche",
|
|
2102
|
+
"monitor.panel.context": "Kontextbelegung",
|
|
2088
2103
|
"monitor.panel.cacheHit": "Cache-Trefferquote",
|
|
2089
2104
|
"monitor.panel.cost": "Kosten (ist / gespart gesch.)",
|
|
2090
2105
|
"monitor.panel.intent": "Intent-Zusammenfassung",
|
|
@@ -2223,6 +2238,7 @@ window.__ModuleLoader__.load({
|
|
|
2223
2238
|
"monitor.panel.net": "Ahorro neto",
|
|
2224
2239
|
"monitor.panel.gross": "Ahorro bruto",
|
|
2225
2240
|
"monitor.panel.offsets": "Compensaciones",
|
|
2241
|
+
"monitor.panel.context": "Ocupación del contexto",
|
|
2226
2242
|
"monitor.panel.cacheHit": "Tasa de acierto de caché",
|
|
2227
2243
|
"monitor.panel.cost": "Coste (real / ahorro est.)",
|
|
2228
2244
|
"monitor.panel.intent": "Resumen de intención",
|
|
@@ -2361,6 +2377,7 @@ window.__ModuleLoader__.load({
|
|
|
2361
2377
|
"monitor.panel.net": "Économie nette",
|
|
2362
2378
|
"monitor.panel.gross": "Économie brute",
|
|
2363
2379
|
"monitor.panel.offsets": "Compensations",
|
|
2380
|
+
"monitor.panel.context": "Occupation du contexte",
|
|
2364
2381
|
"monitor.panel.cacheHit": "Taux de réussite du cache",
|
|
2365
2382
|
"monitor.panel.cost": "Coût (réel / écon. est.)",
|
|
2366
2383
|
"monitor.panel.intent": "Résumé d'intention",
|
|
@@ -2499,6 +2516,7 @@ window.__ModuleLoader__.load({
|
|
|
2499
2516
|
"monitor.panel.net": "Risparmio netto",
|
|
2500
2517
|
"monitor.panel.gross": "Risparmio lordo",
|
|
2501
2518
|
"monitor.panel.offsets": "Compensazioni",
|
|
2519
|
+
"monitor.panel.context": "Occupazione del contesto",
|
|
2502
2520
|
"monitor.panel.cacheHit": "Tasso di hit della cache",
|
|
2503
2521
|
"monitor.panel.cost": "Costo (effettivo / stimo)",
|
|
2504
2522
|
"monitor.panel.intent": "Riepilogo di intento",
|
|
@@ -2637,6 +2655,7 @@ window.__ModuleLoader__.load({
|
|
|
2637
2655
|
"monitor.panel.net": "正味節約",
|
|
2638
2656
|
"monitor.panel.gross": "総節約",
|
|
2639
2657
|
"monitor.panel.offsets": "相殺",
|
|
2658
|
+
"monitor.panel.context": "コンテキスト占有",
|
|
2640
2659
|
"monitor.panel.cacheHit": "キャッシュ ヒット率",
|
|
2641
2660
|
"monitor.panel.cost": "コスト(実績 / 節約概算)",
|
|
2642
2661
|
"monitor.panel.intent": "インテント要約",
|
|
@@ -2775,6 +2794,7 @@ window.__ModuleLoader__.load({
|
|
|
2775
2794
|
"monitor.panel.net": "순 절감",
|
|
2776
2795
|
"monitor.panel.gross": "총 절감",
|
|
2777
2796
|
"monitor.panel.offsets": "상쇄",
|
|
2797
|
+
"monitor.panel.context": "컨텍스트 점유",
|
|
2778
2798
|
"monitor.panel.cacheHit": "캐시 적중률",
|
|
2779
2799
|
"monitor.panel.cost": "비용 (실제 / 절감 추정)",
|
|
2780
2800
|
"monitor.panel.intent": "인텐트 요약",
|
|
@@ -2913,6 +2933,7 @@ window.__ModuleLoader__.load({
|
|
|
2913
2933
|
"monitor.panel.net": "Чистая экономия",
|
|
2914
2934
|
"monitor.panel.gross": "Валовая экономия",
|
|
2915
2935
|
"monitor.panel.offsets": "Компенсации",
|
|
2936
|
+
"monitor.panel.context": "Заполнение контекста",
|
|
2916
2937
|
"monitor.panel.cacheHit": "Процент попаданий кэша",
|
|
2917
2938
|
"monitor.panel.cost": "Стоимость (факт / эконом. оценка)",
|
|
2918
2939
|
"monitor.panel.intent": "Итог намерения",
|
|
@@ -3125,25 +3146,30 @@ window.__ModuleLoader__.load({
|
|
|
3125
3146
|
return false;
|
|
3126
3147
|
}
|
|
3127
3148
|
};
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3149
|
+
let latestSessionId;
|
|
3150
|
+
try {
|
|
3151
|
+
initMonitorFab({
|
|
3152
|
+
t: tNav,
|
|
3153
|
+
sessionIdOf: () => latestSessionId,
|
|
3154
|
+
enabledOf: () => readMonitorPanelEnabled(),
|
|
3155
|
+
fetchSnapshot: async (sessionId) => {
|
|
3156
|
+
const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
|
|
3157
|
+
const response = await fetch(`/api/dsh-context-compression-improved/monitor${query}`, { headers: { "cache-control": "no-cache" } });
|
|
3158
|
+
if (!response.ok) throw new Error(`monitor snapshot ${response.status}`);
|
|
3159
|
+
return await response.json();
|
|
3160
|
+
},
|
|
3161
|
+
applyOverride: async (sessionId, action) => {
|
|
3162
|
+
const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
|
|
3163
|
+
await fetch(`/api/dsh-context-compression-improved/monitor${query}`, {
|
|
3164
|
+
method: "POST",
|
|
3165
|
+
headers: { "content-type": "application/json" },
|
|
3166
|
+
body: JSON.stringify({ action })
|
|
3167
|
+
});
|
|
3168
|
+
}
|
|
3169
|
+
});
|
|
3170
|
+
} catch (error) {
|
|
3171
|
+
console.warn("[dsh-context-compression-improved] 监控浮动球挂载失败(不影响设置分节):", error);
|
|
3172
|
+
}
|
|
3147
3173
|
const injected = () => {
|
|
3148
3174
|
const form = ctx.configForms.get(ENTRY_ID);
|
|
3149
3175
|
const readDoc = () => decodeSettings(form.getSnapshot().value?.settings);
|
|
@@ -3233,6 +3259,19 @@ window.__ModuleLoader__.load({
|
|
|
3233
3259
|
} catch (error) {
|
|
3234
3260
|
console.warn("[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):", error);
|
|
3235
3261
|
}
|
|
3262
|
+
try {
|
|
3263
|
+
ctx.slots.inject("conversation.input.left", () => ctx.slots.register({
|
|
3264
|
+
name: "conversation.input.left",
|
|
3265
|
+
id: "context-compression-session-bind",
|
|
3266
|
+
order: 170,
|
|
3267
|
+
inject: (sessionId) => {
|
|
3268
|
+
latestSessionId = sessionId;
|
|
3269
|
+
return {};
|
|
3270
|
+
}
|
|
3271
|
+
}, () => null));
|
|
3272
|
+
} catch (error) {
|
|
3273
|
+
console.warn("[dsh-context-compression-improved] conversation.input.left 注册失败(旧宿主无该槽,浮动面板保持聚合口径):", error);
|
|
3274
|
+
}
|
|
3236
3275
|
}
|
|
3237
3276
|
//#endregion
|
|
3238
3277
|
exports.apply = apply;
|
|
@@ -634,6 +634,138 @@ function evaluateIntentGate(input) {
|
|
|
634
634
|
return snapshot(true, "passed");
|
|
635
635
|
}
|
|
636
636
|
//#endregion
|
|
637
|
+
//#region src/runtime/monitor.ts
|
|
638
|
+
/**
|
|
639
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
640
|
+
* injectable so tests seed a private instance instead of the process
|
|
641
|
+
* singleton.
|
|
642
|
+
*/
|
|
643
|
+
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
644
|
+
const scopeKey = sessionId ?? "";
|
|
645
|
+
const override = getSummaryOverride(scopeKey);
|
|
646
|
+
const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
|
|
647
|
+
const contextBlock = observedContext === void 0 ? void 0 : {
|
|
648
|
+
liveTokens: observedContext.liveTokens,
|
|
649
|
+
contextWindow: observedContext.contextWindow,
|
|
650
|
+
pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
|
|
651
|
+
sessionId: observedContext.sessionId
|
|
652
|
+
};
|
|
653
|
+
return {
|
|
654
|
+
...ledger.snapshot(sessionId),
|
|
655
|
+
...contextBlock === void 0 ? {} : { context: contextBlock },
|
|
656
|
+
intent: {
|
|
657
|
+
override,
|
|
658
|
+
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
659
|
+
gate: {
|
|
660
|
+
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
661
|
+
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
662
|
+
},
|
|
663
|
+
lastFold: getLastIntentFold(scopeKey)
|
|
664
|
+
},
|
|
665
|
+
sessionScope: sessionId ?? null
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
/** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
|
|
669
|
+
const contextUsageBySession = /* @__PURE__ */ new Map();
|
|
670
|
+
const CONTEXT_USAGE_CAP = 64;
|
|
671
|
+
/**
|
|
672
|
+
* 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
|
|
673
|
+
* contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
|
|
674
|
+
*/
|
|
675
|
+
function observeContextUsage(sessionId, liveTokens, contextWindow) {
|
|
676
|
+
if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
|
|
677
|
+
if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
|
|
678
|
+
const oldest = contextUsageBySession.keys().next().value;
|
|
679
|
+
if (oldest !== void 0) contextUsageBySession.delete(oldest);
|
|
680
|
+
}
|
|
681
|
+
contextUsageBySession.set(sessionId, {
|
|
682
|
+
liveTokens,
|
|
683
|
+
contextWindow,
|
|
684
|
+
at: Date.now(),
|
|
685
|
+
seq: ++observeSeq
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
function getContextUsage(sessionId) {
|
|
689
|
+
const entry = contextUsageBySession.get(sessionId);
|
|
690
|
+
return entry === void 0 ? void 0 : {
|
|
691
|
+
liveTokens: entry.liveTokens,
|
|
692
|
+
contextWindow: entry.contextWindow,
|
|
693
|
+
sessionId
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
let observeSeq = 0;
|
|
697
|
+
function latestObservedContextUsage() {
|
|
698
|
+
let latest;
|
|
699
|
+
for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
|
|
700
|
+
sessionId,
|
|
701
|
+
liveTokens: entry.liveTokens,
|
|
702
|
+
contextWindow: entry.contextWindow,
|
|
703
|
+
seq: entry.seq
|
|
704
|
+
};
|
|
705
|
+
return latest;
|
|
706
|
+
}
|
|
707
|
+
function isSessionOverrideAction(value) {
|
|
708
|
+
return value === "on" || value === "off" || value === "clear";
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
712
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
713
|
+
* handed back so the route can echo the post-action truth.
|
|
714
|
+
*/
|
|
715
|
+
function applySessionOverride(sessionId, action) {
|
|
716
|
+
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
717
|
+
return { override: getSummaryOverride(sessionId) };
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
721
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
722
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
723
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
724
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
725
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
726
|
+
*/
|
|
727
|
+
function estimateSavingsPricing(readService, snapshot) {
|
|
728
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
729
|
+
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
730
|
+
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
731
|
+
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
732
|
+
if (provider !== "deepseek-official") return void 0;
|
|
733
|
+
const now = /* @__PURE__ */ new Date();
|
|
734
|
+
const startedAt = new Date(snapshot.startedAt);
|
|
735
|
+
const base = {
|
|
736
|
+
provider,
|
|
737
|
+
baseUrlClass: "official-public",
|
|
738
|
+
apiRoute: "chat-completions",
|
|
739
|
+
modelId,
|
|
740
|
+
currency: "USD",
|
|
741
|
+
startedAt,
|
|
742
|
+
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
743
|
+
};
|
|
744
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
745
|
+
...base,
|
|
746
|
+
usage: {
|
|
747
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
748
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
749
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
753
|
+
...base,
|
|
754
|
+
usage: {
|
|
755
|
+
cacheReadTokens: 0,
|
|
756
|
+
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
757
|
+
outputTokens: 0
|
|
758
|
+
}
|
|
759
|
+
}) : void 0;
|
|
760
|
+
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
761
|
+
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
762
|
+
return {
|
|
763
|
+
currency: "USD",
|
|
764
|
+
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
765
|
+
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
//#endregion
|
|
637
769
|
//#region src/runtime/types.ts
|
|
638
770
|
/** User-facing mixed strategy profile. */
|
|
639
771
|
const COMPRESSION_PROFILES = [
|
|
@@ -1566,4 +1698,4 @@ function assertNonNegativeInteger(name, value) {
|
|
|
1566
1698
|
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
|
|
1567
1699
|
}
|
|
1568
1700
|
//#endregion
|
|
1569
|
-
export {
|
|
1701
|
+
export { getLastIntentFold as A, decimalRateNanoUnits as B, estimateSavingsPricing as C, INTENT_GATE_GROWTH_TOKENS as D, INTENT_GATE_FLOOR_FRACTION as E, recordIntentFold as F, resolveOfficialDeepSeekPrice as H, recordRecertified as I, recordScore as L, getSummaryOverride as M, invalidateOnTaskChange as N, evaluateIntentGate as O, observeIntentEnabled as P, setSummaryOverride as R, buildMonitorSnapshot as S, observeContextUsage as T, getSavingsLedger as U, priceOfficialDeepSeekUsage as V, resolveCustomPolicy as _, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as a, COMPRESSION_PROFILES as b, charsToTokens as c, isValidAutoCompactThresholdPercent as d, parseContextCompressionSettings as f, DEFAULT_CUSTOM_COMPRESSION_POLICY as g, CustomCompressionPolicySchema as h, DEFAULTS as i, getObservedIntentEnabled as j, getAdvisorState as k, codePointLength as l, resolvePolicy as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, PRUNE_MARKER as o, resolveConfig as p, ContextCompressionSettingsSchema as r, charsForTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isCompressionProfile as u, assertNever as v, isSessionOverrideAction as w, applySessionOverride as x, deepFreeze as y, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as getLastIntentFold, C as estimateSavingsPricing, D as INTENT_GATE_GROWTH_TOKENS, E as INTENT_GATE_FLOOR_FRACTION, M as getSummaryOverride, R as setSummaryOverride, S as buildMonitorSnapshot, U as getSavingsLedger, a as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, j as getObservedIntentEnabled, k as getAdvisorState, w as isSessionOverrideAction, x as applySessionOverride } from "./config.js";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -75,90 +75,6 @@ async function buildEstimatorCatalog(deps) {
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
//#endregion
|
|
78
|
-
//#region src/runtime/monitor.ts
|
|
79
|
-
/**
|
|
80
|
-
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
81
|
-
* injectable so tests seed a private instance instead of the process
|
|
82
|
-
* singleton.
|
|
83
|
-
*/
|
|
84
|
-
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
85
|
-
const override = getSummaryOverride(sessionId ?? "");
|
|
86
|
-
return {
|
|
87
|
-
...ledger.snapshot(sessionId),
|
|
88
|
-
intent: {
|
|
89
|
-
override,
|
|
90
|
-
observedEnabled: getObservedIntentEnabled(sessionId ?? ""),
|
|
91
|
-
gate: {
|
|
92
|
-
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
93
|
-
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
94
|
-
},
|
|
95
|
-
lastFold: getLastIntentFold(sessionId ?? "")
|
|
96
|
-
},
|
|
97
|
-
sessionScope: sessionId ?? null
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
function isSessionOverrideAction(value) {
|
|
101
|
-
return value === "on" || value === "off" || value === "clear";
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
105
|
-
* session, `clear` returns it to settings-driven. The resulting override is
|
|
106
|
-
* handed back so the route can echo the post-action truth.
|
|
107
|
-
*/
|
|
108
|
-
function applySessionOverride(sessionId, action) {
|
|
109
|
-
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
110
|
-
return { override: getSummaryOverride(sessionId) };
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
114
|
-
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
115
|
-
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
116
|
-
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
117
|
-
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
118
|
-
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
119
|
-
*/
|
|
120
|
-
function estimateSavingsPricing(readService, snapshot) {
|
|
121
|
-
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
122
|
-
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
123
|
-
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
124
|
-
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
125
|
-
if (provider !== "deepseek-official") return void 0;
|
|
126
|
-
const now = /* @__PURE__ */ new Date();
|
|
127
|
-
const startedAt = new Date(snapshot.startedAt);
|
|
128
|
-
const base = {
|
|
129
|
-
provider,
|
|
130
|
-
baseUrlClass: "official-public",
|
|
131
|
-
apiRoute: "chat-completions",
|
|
132
|
-
modelId,
|
|
133
|
-
currency: "USD",
|
|
134
|
-
startedAt,
|
|
135
|
-
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
136
|
-
};
|
|
137
|
-
const actual = priceOfficialDeepSeekUsage({
|
|
138
|
-
...base,
|
|
139
|
-
usage: {
|
|
140
|
-
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
141
|
-
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
142
|
-
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
146
|
-
...base,
|
|
147
|
-
usage: {
|
|
148
|
-
cacheReadTokens: 0,
|
|
149
|
-
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
150
|
-
outputTokens: 0
|
|
151
|
-
}
|
|
152
|
-
}) : void 0;
|
|
153
|
-
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
154
|
-
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
155
|
-
return {
|
|
156
|
-
currency: "USD",
|
|
157
|
-
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
158
|
-
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
//#endregion
|
|
162
78
|
//#region src/runtime/summary-command.ts
|
|
163
79
|
const SUMMARY_COMMAND_NAME = "ctx-summary";
|
|
164
80
|
const USAGE = "Usage: /ctx-summary off|on|status";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as decimalRateNanoUnits, F as recordIntentFold, H as resolveOfficialDeepSeekPrice, I as recordRecertified, L as recordScore, M as getSummaryOverride, N as invalidateOnTaskChange, O as evaluateIntentGate, P as observeIntentEnabled, T as observeContextUsage, U as getSavingsLedger, V as priceOfficialDeepSeekUsage, _ as resolveCustomPolicy, b as COMPRESSION_PROFILES, c as charsToTokens, d as isValidAutoCompactThresholdPercent, f as parseContextCompressionSettings, g as DEFAULT_CUSTOM_COMPRESSION_POLICY, h as CustomCompressionPolicySchema, i as DEFAULTS, k as getAdvisorState, l as codePointLength, m as resolvePolicy, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as PRUNE_MARKER, p as resolveConfig, r as ContextCompressionSettingsSchema, s as charsForTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isCompressionProfile, v as assertNever, y as deepFreeze, z as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION } from "./config.js";
|
|
2
2
|
import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as eventBySeq, r as tailTrimRef, s as sessionEvents, t as parseTailTrimRef } from "./tail-trim.js";
|
|
3
3
|
import z from "@deepseek-ai/schemastery";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -4421,13 +4421,15 @@ var ToolResultPruner = class extends Service {
|
|
|
4421
4421
|
const view = measureForCompaction(this.ctx, session);
|
|
4422
4422
|
const thresholdPercent = settings.autoCompact.thresholdPercent;
|
|
4423
4423
|
const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
|
|
4424
|
-
|
|
4424
|
+
const gate = evaluateIntentGate({
|
|
4425
4425
|
enabled: intentEnabled,
|
|
4426
4426
|
override,
|
|
4427
4427
|
liveTokens: view.totalTokens,
|
|
4428
4428
|
contextWindow,
|
|
4429
4429
|
baselineTokens: this.state.intentBaselines.get(session) ?? 0
|
|
4430
|
-
})
|
|
4430
|
+
});
|
|
4431
|
+
observeContextUsage(sessionId, view.totalTokens, contextWindow);
|
|
4432
|
+
if (!gate.decision) return;
|
|
4431
4433
|
const settingsPreset = settings.presetOptions;
|
|
4432
4434
|
if (settingsPreset === void 0) return;
|
|
4433
4435
|
if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
|
|
@@ -119,9 +119,12 @@ export function apply(ctx: ClientContext): void {
|
|
|
119
119
|
return false
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
|
-
|
|
122
|
+
// 浮动面板会话绑定:跟随输入栏座位的 inject 回调(裸 sessionId,pm longtask 同款)。
|
|
123
|
+
let latestSessionId: string | undefined
|
|
124
|
+
try {
|
|
125
|
+
initMonitorFab({
|
|
123
126
|
t: tNav,
|
|
124
|
-
sessionIdOf: () =>
|
|
127
|
+
sessionIdOf: () => latestSessionId,
|
|
125
128
|
enabledOf: () => readMonitorPanelEnabled(),
|
|
126
129
|
fetchSnapshot: async (sessionId) => {
|
|
127
130
|
const query = sessionId === undefined ? '' : `?sessionId=${encodeURIComponent(sessionId)}`
|
|
@@ -137,7 +140,10 @@ export function apply(ctx: ClientContext): void {
|
|
|
137
140
|
body: JSON.stringify({ action }),
|
|
138
141
|
})
|
|
139
142
|
},
|
|
140
|
-
|
|
143
|
+
})
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.warn('[dsh-context-compression-improved] 监控浮动球挂载失败(不影响设置分节):', error)
|
|
146
|
+
}
|
|
141
147
|
const injected = (): CompressionSelectorInjected => {
|
|
142
148
|
// 0.1.7: the compression document rides the selector row's entry config as
|
|
143
149
|
// the volatile `settings` field. The form handle is fetched per factory
|
|
@@ -277,6 +283,23 @@ export function apply(ctx: ClientContext): void {
|
|
|
277
283
|
} catch (error) {
|
|
278
284
|
console.warn('[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):', error)
|
|
279
285
|
}
|
|
286
|
+
|
|
287
|
+
// 输入栏左座(0.1.5+ 宿主):组件刻意空渲染——注册此座位只为接收宿主的
|
|
288
|
+
// sessionId 注入回调,供浮动监控面板绑定会话(pm longtask 同款)。旧宿主
|
|
289
|
+
// 未声明该槽时激活期会抛错,try/catch 守卫(同上双槽冗余先例)。
|
|
290
|
+
try {
|
|
291
|
+
ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
|
|
292
|
+
name: 'conversation.input.left',
|
|
293
|
+
id: 'context-compression-session-bind',
|
|
294
|
+
order: 170,
|
|
295
|
+
inject: (sessionId: string) => {
|
|
296
|
+
latestSessionId = sessionId
|
|
297
|
+
return {}
|
|
298
|
+
},
|
|
299
|
+
}, () => null))
|
|
300
|
+
} catch (error) {
|
|
301
|
+
console.warn('[dsh-context-compression-improved] conversation.input.left 注册失败(旧宿主无该槽,浮动面板保持聚合口径):', error)
|
|
302
|
+
}
|
|
280
303
|
}
|
|
281
304
|
|
|
282
305
|
export type {
|
|
@@ -74,6 +74,7 @@ export const de = {
|
|
|
74
74
|
'monitor.panel.net': 'Nettoeinsparung',
|
|
75
75
|
'monitor.panel.gross': 'Bruttoeinsparung',
|
|
76
76
|
'monitor.panel.offsets': 'Ausgleiche',
|
|
77
|
+
'monitor.panel.context': 'Kontextbelegung',
|
|
77
78
|
'monitor.panel.cacheHit': 'Cache-Trefferquote',
|
|
78
79
|
'monitor.panel.cost': 'Kosten (ist / gespart gesch.)',
|
|
79
80
|
'monitor.panel.intent': 'Intent-Zusammenfassung',
|
|
@@ -74,6 +74,7 @@ export const es = {
|
|
|
74
74
|
'monitor.panel.net': 'Ahorro neto',
|
|
75
75
|
'monitor.panel.gross': 'Ahorro bruto',
|
|
76
76
|
'monitor.panel.offsets': 'Compensaciones',
|
|
77
|
+
'monitor.panel.context': 'Ocupación del contexto',
|
|
77
78
|
'monitor.panel.cacheHit': 'Tasa de acierto de caché',
|
|
78
79
|
'monitor.panel.cost': 'Coste (real / ahorro est.)',
|
|
79
80
|
'monitor.panel.intent': 'Resumen de intención',
|
|
@@ -74,6 +74,7 @@ export const fr = {
|
|
|
74
74
|
'monitor.panel.net': 'Économie nette',
|
|
75
75
|
'monitor.panel.gross': 'Économie brute',
|
|
76
76
|
'monitor.panel.offsets': 'Compensations',
|
|
77
|
+
'monitor.panel.context': 'Occupation du contexte',
|
|
77
78
|
'monitor.panel.cacheHit': 'Taux de réussite du cache',
|
|
78
79
|
'monitor.panel.cost': 'Coût (réel / écon. est.)',
|
|
79
80
|
'monitor.panel.intent': 'Résumé d\'intention',
|
|
@@ -74,6 +74,7 @@ export const it = {
|
|
|
74
74
|
'monitor.panel.net': 'Risparmio netto',
|
|
75
75
|
'monitor.panel.gross': 'Risparmio lordo',
|
|
76
76
|
'monitor.panel.offsets': 'Compensazioni',
|
|
77
|
+
'monitor.panel.context': 'Occupazione del contesto',
|
|
77
78
|
'monitor.panel.cacheHit': 'Tasso di hit della cache',
|
|
78
79
|
'monitor.panel.cost': 'Costo (effettivo / stimo)',
|
|
79
80
|
'monitor.panel.intent': 'Riepilogo di intento',
|
|
@@ -74,6 +74,7 @@ export const ja = {
|
|
|
74
74
|
'monitor.panel.net': '正味節約',
|
|
75
75
|
'monitor.panel.gross': '総節約',
|
|
76
76
|
'monitor.panel.offsets': '相殺',
|
|
77
|
+
'monitor.panel.context': 'コンテキスト占有',
|
|
77
78
|
'monitor.panel.cacheHit': 'キャッシュ ヒット率',
|
|
78
79
|
'monitor.panel.cost': 'コスト(実績 / 節約概算)',
|
|
79
80
|
'monitor.panel.intent': 'インテント要約',
|
|
@@ -74,6 +74,7 @@ export const ko = {
|
|
|
74
74
|
'monitor.panel.net': '순 절감',
|
|
75
75
|
'monitor.panel.gross': '총 절감',
|
|
76
76
|
'monitor.panel.offsets': '상쇄',
|
|
77
|
+
'monitor.panel.context': '컨텍스트 점유',
|
|
77
78
|
'monitor.panel.cacheHit': '캐시 적중률',
|
|
78
79
|
'monitor.panel.cost': '비용 (실제 / 절감 추정)',
|
|
79
80
|
'monitor.panel.intent': '인텐트 요약',
|
|
@@ -74,6 +74,7 @@ export const ru = {
|
|
|
74
74
|
'monitor.panel.net': 'Чистая экономия',
|
|
75
75
|
'monitor.panel.gross': 'Валовая экономия',
|
|
76
76
|
'monitor.panel.offsets': 'Компенсации',
|
|
77
|
+
'monitor.panel.context': 'Заполнение контекста',
|
|
77
78
|
'monitor.panel.cacheHit': 'Процент попаданий кэша',
|
|
78
79
|
'monitor.panel.cost': 'Стоимость (факт / эконом. оценка)',
|
|
79
80
|
'monitor.panel.intent': 'Итог намерения',
|
|
@@ -72,6 +72,7 @@ export const zh = {
|
|
|
72
72
|
'monitor.panel.net': '净节省',
|
|
73
73
|
'monitor.panel.gross': '毛节省',
|
|
74
74
|
'monitor.panel.offsets': '抵消',
|
|
75
|
+
'monitor.panel.context': '上下文占用',
|
|
75
76
|
'monitor.panel.cacheHit': '缓存命中率',
|
|
76
77
|
'monitor.panel.cost': '成本(实际 / 省估)',
|
|
77
78
|
'monitor.panel.intent': '意图摘要',
|
|
@@ -214,6 +215,7 @@ export const en = {
|
|
|
214
215
|
'monitor.panel.net': 'Net savings',
|
|
215
216
|
'monitor.panel.gross': 'Gross savings',
|
|
216
217
|
'monitor.panel.offsets': 'Offsets',
|
|
218
|
+
'monitor.panel.context': 'Context occupancy',
|
|
217
219
|
'monitor.panel.cacheHit': 'Cache hit rate',
|
|
218
220
|
'monitor.panel.cost': 'Cost (actual / saved est.)',
|
|
219
221
|
'monitor.panel.intent': 'Intent summary',
|
|
@@ -37,6 +37,7 @@ export interface MonitorSnapshotPayload {
|
|
|
37
37
|
gate?: { floorFraction?: unknown; growthTokens?: unknown }
|
|
38
38
|
lastFold?: { turn?: unknown; startSeq?: unknown; endSeq?: unknown } | undefined
|
|
39
39
|
}
|
|
40
|
+
context?: { liveTokens?: unknown; contextWindow?: unknown; pct?: unknown }
|
|
40
41
|
recentOffsets?: Array<{ component?: unknown; tokens?: unknown }>
|
|
41
42
|
sessionScope?: string | null
|
|
42
43
|
}
|
|
@@ -111,6 +112,7 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
|
|
|
111
112
|
<div class="row"><span class="label">${t('monitor.panel.net')}</span><span data-net>–</span></div>
|
|
112
113
|
<div class="row"><span class="label">${t('monitor.panel.gross')}</span><span data-gross class="muted">–</span></div>
|
|
113
114
|
<div class="row"><span class="label">${t('monitor.panel.offsets')}</span><span data-offsets class="muted">–</span></div>
|
|
115
|
+
<div class="row"><span class="label">${t('monitor.panel.context')}</span><div class="bar"><i data-ctxbar></i></div><span data-ctxpct class="muted">–</span></div>
|
|
114
116
|
<div class="row"><span class="label">${t('monitor.panel.cacheHit')}</span><span data-cache class="muted">–</span></div>
|
|
115
117
|
<div class="row"><span class="label">${t('monitor.panel.cost')}</span><span data-cost class="muted">–</span></div>
|
|
116
118
|
<div class="row"><span class="label">${t('monitor.panel.intent')}</span><span data-intent class="muted">–</span></div>
|
|
@@ -215,6 +217,17 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
|
|
|
215
217
|
fab.classList.toggle('lit', net < 0);
|
|
216
218
|
(panel.querySelector('[data-gross]') as HTMLElement).textContent = fmtTokens(snap.gross?.exact);
|
|
217
219
|
(panel.querySelector('[data-offsets]') as HTMLElement).textContent = `-${fmtTokens(snap.offsets?.exact)}`;
|
|
220
|
+
const ctxBar = panel.querySelector('[data-ctxbar]') as HTMLElement;
|
|
221
|
+
const ctxPct = panel.querySelector('[data-ctxpct]') as HTMLElement;
|
|
222
|
+
const ctxPctNum = typeof snap.context?.pct === 'number' ? snap.context.pct : null;
|
|
223
|
+
if (ctxPctNum === null) {
|
|
224
|
+
ctxBar.style.width = '0%';
|
|
225
|
+
ctxPct.textContent = '–';
|
|
226
|
+
} else {
|
|
227
|
+
ctxBar.style.width = `${Math.min(100, Math.round(ctxPctNum * 100))}%`;
|
|
228
|
+
ctxBar.parentElement?.classList.toggle('hot', ctxPctNum >= 0.7);
|
|
229
|
+
ctxPct.textContent = `${Math.round(ctxPctNum * 100)}%`;
|
|
230
|
+
}
|
|
218
231
|
const hit = snap.usage?.cacheHitRate;
|
|
219
232
|
(panel.querySelector('[data-cache]') as HTMLElement).textContent =
|
|
220
233
|
typeof hit === 'number' ? `${Math.round(hit * 100)}%` : '–';
|
|
@@ -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
|
|
@@ -46,8 +46,18 @@ export interface MonitorIntentBlock {
|
|
|
46
46
|
lastFold: IntentFoldRecord | undefined
|
|
47
47
|
}
|
|
48
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
|
+
|
|
49
57
|
export type MonitorSnapshot = SavingsSnapshot & {
|
|
50
58
|
intent: MonitorIntentBlock
|
|
59
|
+
/** Latest observed context occupancy; undefined until the pruner observes a turn. */
|
|
60
|
+
context?: MonitorContextBlock
|
|
51
61
|
/** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
|
|
52
62
|
sessionScope: string | null
|
|
53
63
|
}
|
|
@@ -61,19 +71,71 @@ export function buildMonitorSnapshot(
|
|
|
61
71
|
sessionId?: string,
|
|
62
72
|
ledger: SavingsLedger = getSavingsLedger(),
|
|
63
73
|
): MonitorSnapshot {
|
|
64
|
-
const
|
|
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
|
+
}
|
|
65
89
|
return {
|
|
66
90
|
...ledger.snapshot(sessionId),
|
|
91
|
+
...(contextBlock === undefined ? {} : { context: contextBlock }),
|
|
67
92
|
intent: {
|
|
68
93
|
override,
|
|
69
|
-
observedEnabled: getObservedIntentEnabled(
|
|
94
|
+
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
70
95
|
gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
|
|
71
|
-
lastFold: getLastIntentFold(
|
|
96
|
+
lastFold: getLastIntentFold(scopeKey),
|
|
72
97
|
},
|
|
73
98
|
sessionScope: sessionId ?? null,
|
|
74
99
|
}
|
|
75
100
|
}
|
|
76
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
|
+
|
|
77
139
|
export type SessionOverrideAction = 'on' | 'off' | 'clear'
|
|
78
140
|
|
|
79
141
|
export function isSessionOverrideAction(value: unknown): value is SessionOverrideAction {
|
|
@@ -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
|
},
|
|
@@ -3,6 +3,7 @@ import { parseContextCompressionSettings, DEFAULT_CONTEXT_COMPRESSION_SETTINGS }
|
|
|
3
3
|
import { SavingsLedger } from '../../src/runtime/savings.ts'
|
|
4
4
|
import {
|
|
5
5
|
applySessionOverride,
|
|
6
|
+
observeContextUsage,
|
|
6
7
|
buildMonitorSnapshot,
|
|
7
8
|
estimateSavingsPricing,
|
|
8
9
|
isSessionOverrideAction,
|
|
@@ -234,3 +235,40 @@ describe('monitorPanel settings parsing (schema surface, mirrors intentSummary c
|
|
|
234
235
|
.toThrow(/monitorPanel must be a plain object/)
|
|
235
236
|
})
|
|
236
237
|
})
|
|
238
|
+
|
|
239
|
+
describe('context occupancy observation (task_6.2)', () => {
|
|
240
|
+
it('scoped snapshot carries the observed occupancy block', () => {
|
|
241
|
+
const sessionId = uniqueSession()
|
|
242
|
+
observeContextUsage(sessionId, 60_000, 128_000)
|
|
243
|
+
const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
|
|
244
|
+
expect(snap.context).toEqual({ liveTokens: 60_000, contextWindow: 128_000, pct: 0.469, sessionId })
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
it('aggregate snapshot carries the most recently observed session', () => {
|
|
248
|
+
const a = uniqueSession()
|
|
249
|
+
const b = uniqueSession()
|
|
250
|
+
observeContextUsage(a, 10_000, 100_000)
|
|
251
|
+
observeContextUsage(b, 90_000, 100_000)
|
|
252
|
+
const snap = buildMonitorSnapshot(undefined, new SavingsLedger())
|
|
253
|
+
expect(snap.context?.sessionId).toBe(b)
|
|
254
|
+
expect(snap.context?.pct).toBe(0.9)
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
it('no observation yet — context block absent', () => {
|
|
258
|
+
const snap = buildMonitorSnapshot(uniqueSession(), new SavingsLedger())
|
|
259
|
+
expect(snap.context).toBeUndefined()
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
it('observation cap keeps the newest 64 sessions', () => {
|
|
263
|
+
for (let i = 0; i < 70; i++) observeContextUsage(`cap-${i}`, i, 1000)
|
|
264
|
+
const snap = buildMonitorSnapshot('cap-69', new SavingsLedger())
|
|
265
|
+
expect(snap.context?.sessionId).toBe('cap-69')
|
|
266
|
+
})
|
|
267
|
+
|
|
268
|
+
it('empty session id and non-finite tokens are ignored', () => {
|
|
269
|
+
observeContextUsage('', 5, 100)
|
|
270
|
+
observeContextUsage('fin-check', Number.NaN, 100)
|
|
271
|
+
expect(buildMonitorSnapshot('fin-check', new SavingsLedger()).context).toBeUndefined()
|
|
272
|
+
})
|
|
273
|
+
})
|
|
274
|
+
|
|
@@ -64,16 +64,17 @@ function collectRegistrations(
|
|
|
64
64
|
return { declared, registrations }
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
describe('settings-seat contract (standalone settings.section
|
|
67
|
+
describe('settings-seat contract (standalone settings.section + input-bar session binder)', () => {
|
|
68
68
|
it('declares the services apply consumes (cordis waits; no lazy-get race)', () => {
|
|
69
69
|
expect(inject).toEqual(['slots', 'locale', 'configForms'])
|
|
70
70
|
})
|
|
71
71
|
|
|
72
|
-
it('injects exactly the settings.section
|
|
72
|
+
it('injects exactly two seats: the settings.section panel + the input-bar session binder', () => {
|
|
73
73
|
const { declared, registrations } = collectRegistrations()
|
|
74
|
-
expect(declared).toEqual(['settings.section'])
|
|
75
|
-
expect(registrations).toHaveLength(
|
|
74
|
+
expect(declared).toEqual(['settings.section', 'conversation.input.left'])
|
|
75
|
+
expect(registrations).toHaveLength(2)
|
|
76
76
|
expect(registrations[0]!.slot).toBe('settings.section')
|
|
77
|
+
expect(registrations[1]!.slot).toBe('conversation.input.left')
|
|
77
78
|
})
|
|
78
79
|
|
|
79
80
|
it('no longer claims a shell.overlay float (the review panel it served is gone)', () => {
|
|
@@ -94,6 +95,17 @@ describe('settings-seat contract (standalone settings.section only)', () => {
|
|
|
94
95
|
expect(component).toBe(ContextCompressionSettingsSection)
|
|
95
96
|
})
|
|
96
97
|
|
|
98
|
+
it('pins the input-bar binder: invisible component, inject captures the bare sessionId', () => {
|
|
99
|
+
const { registrations } = collectRegistrations()
|
|
100
|
+
const inputSeat = registrations[1]!
|
|
101
|
+
expect(inputSeat.options['id']).toBe('context-compression-session-bind')
|
|
102
|
+
expect(inputSeat.options['order']).toBe(170)
|
|
103
|
+
expect(typeof inputSeat.options['inject']).toBe('function')
|
|
104
|
+
const face = (inputSeat.options['inject'] as (sessionId: string) => Record<string, unknown>)('sess-42')
|
|
105
|
+
expect(face).toEqual({})
|
|
106
|
+
expect(inputSeat.component).toBeTypeOf('function')
|
|
107
|
+
})
|
|
108
|
+
|
|
97
109
|
it('never adds a Plugins-section card or tab alongside the standalone section', () => {
|
|
98
110
|
const { declared } = collectRegistrations()
|
|
99
111
|
expect(declared).not.toContain('settings.plugins.tab')
|
|
@@ -154,8 +166,8 @@ describe('settings-seat contract (standalone settings.section only)', () => {
|
|
|
154
166
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
155
167
|
try {
|
|
156
168
|
const { declared } = collectRegistrations({ registerThrows: true })
|
|
157
|
-
// It tried
|
|
158
|
-
expect(declared).toEqual(['settings.section'])
|
|
169
|
+
// It tried both seats (so the degradation is "loud", not a silent no-op)…
|
|
170
|
+
expect(declared).toEqual(['settings.section', 'conversation.input.left'])
|
|
159
171
|
// …and the rejection never escaped apply().
|
|
160
172
|
expect(warn).toHaveBeenCalled()
|
|
161
173
|
} finally {
|