dsh-context-compression-improved 0.8.0-beta.5 → 0.8.0-beta.7

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 CHANGED
@@ -2,6 +2,34 @@
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.7 - 2026-10-02
6
+
7
+ ### Added
8
+
9
+ - **灾难性遗忘区建议压缩**: the monitor snapshot carries a `suggestion` block — when
10
+ observed context occupancy reaches `MONITOR_SUGGEST_PCT` (0.7, deliberately one notch
11
+ below the host Auto Compact default of 80%) the floating bubble lights up (breathing
12
+ tint) and the panel shows a localized hint recommending compression or history trimming.
13
+ - Context occupancy observation is decoupled from the intent-summary gate: every turn
14
+ records live tokens vs the auto-compact-derived window, so the occupancy bar and the
15
+ suggestion work even with intent summaries off (previously the bar stayed empty).
16
+
17
+ ## 0.8.0-beta.6 - 2026-10-02
18
+
19
+ ### Added
20
+
21
+ - **Session binding for the floating monitor**: a deliberately invisible `conversation.input.left`
22
+ seat captures the active session id (pm longtask precedent) — the panel now shows the bound
23
+ session's data and its override buttons act on that session instead of the default one.
24
+ - **Context occupancy bar** in the panel: the turn-tail postflight observes live tokens vs the
25
+ auto-compact-derived window per session; the panel renders the occupancy percentage
26
+ (hot tint past 70%).
27
+
28
+ ### Fixed
29
+
30
+ - Client specs that captured the settings face by `inject` presence now key off the
31
+ `settings.section` seat explicitly (the input-bar binder's `inject` is a session callback).
32
+
5
33
  ## 0.8.0-beta.5 - 2026-10-02
6
34
 
7
35
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.8.0-beta.5",
3
+ "version": "0.8.0-beta.7",
4
4
  "publishConfig": {
5
5
  "tag": "dsh-0.2.0"
6
6
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-context-compression-improved",
3
- "version": "0.8.0-beta.5",
3
+ "version": "0.8.0-beta.7",
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,8 @@ 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;
85
+ 'monitor.panel.suggest': string;
84
86
  'monitor.panel.cacheHit': string;
85
87
  'monitor.panel.cost': string;
86
88
  'monitor.panel.intent': string;
@@ -1543,6 +1543,9 @@ window.__ModuleLoader__.load({
1543
1543
  #${PANEL_ID} button.ghost { background: transparent; }
1544
1544
  #${PANEL_ID} button:disabled { opacity: .45; cursor: default; }
1545
1545
  #${PANEL_ID} .stale { padding: 4px 14px 8px; color: #ffd60a; display: none; }
1546
+ #${PANEL_ID} .hint { margin: 0; padding: 8px 14px; color: #ffd60a; display: none;
1547
+ border-bottom: 1px solid rgba(255,255,255,.09); }
1548
+ #${PANEL_ID} .hint.show { display: block; }
1546
1549
  #${PANEL_ID} .stale.show { display: block; }
1547
1550
  #${PANEL_ID} .recent { max-height: 132px; overflow: auto; padding: 2px 14px 8px;
1548
1551
  color: rgba(245,245,247,.8); white-space: pre-wrap; }
@@ -1559,9 +1562,11 @@ window.__ModuleLoader__.load({
1559
1562
  panel.hidden = true;
1560
1563
  panel.innerHTML = `
1561
1564
  <h4>${t("monitor.panel.title")}</h4>
1565
+ <div class="hint" data-hint></div>
1562
1566
  <div class="row"><span class="label">${t("monitor.panel.net")}</span><span data-net>–</span></div>
1563
1567
  <div class="row"><span class="label">${t("monitor.panel.gross")}</span><span data-gross class="muted">–</span></div>
1564
1568
  <div class="row"><span class="label">${t("monitor.panel.offsets")}</span><span data-offsets class="muted">–</span></div>
1569
+ <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
1570
  <div class="row"><span class="label">${t("monitor.panel.cacheHit")}</span><span data-cache class="muted">–</span></div>
1566
1571
  <div class="row"><span class="label">${t("monitor.panel.cost")}</span><span data-cost class="muted">–</span></div>
1567
1572
  <div class="row"><span class="label">${t("monitor.panel.intent")}</span><span data-intent class="muted">–</span></div>
@@ -1663,11 +1668,29 @@ window.__ModuleLoader__.load({
1663
1668
  const render = (snap) => {
1664
1669
  const net = num(snap.net?.exact) + num(snap.net?.estimated);
1665
1670
  const netEl = panel.querySelector("[data-net]");
1666
- netEl.textContent = `${net >= 0 ? "" : ""}${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ""}`;
1671
+ netEl.textContent = `${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ""}`;
1667
1672
  netEl.classList.toggle("neg", net < 0);
1668
- fab.classList.toggle("lit", net < 0);
1673
+ const suggest = snap.suggestion?.suggest === true;
1674
+ fab.classList.toggle("lit", suggest || net < 0);
1675
+ const hint = panel.querySelector("[data-hint]");
1676
+ if (suggest) {
1677
+ const pct = typeof snap.suggestion?.occupancyPct === "number" ? Math.round(snap.suggestion.occupancyPct * 100) : null;
1678
+ hint.textContent = t("monitor.panel.suggest").replace("{pct}", String(pct ?? "–"));
1679
+ hint.classList.add("show");
1680
+ } else hint.classList.remove("show");
1669
1681
  panel.querySelector("[data-gross]").textContent = fmtTokens(snap.gross?.exact);
1670
1682
  panel.querySelector("[data-offsets]").textContent = `-${fmtTokens(snap.offsets?.exact)}`;
1683
+ const ctxBar = panel.querySelector("[data-ctxbar]");
1684
+ const ctxPct = panel.querySelector("[data-ctxpct]");
1685
+ const ctxPctNum = typeof snap.context?.pct === "number" ? snap.context.pct : null;
1686
+ if (ctxPctNum === null) {
1687
+ ctxBar.style.width = "0%";
1688
+ ctxPct.textContent = "–";
1689
+ } else {
1690
+ ctxBar.style.width = `${Math.min(100, Math.round(ctxPctNum * 100))}%`;
1691
+ ctxBar.parentElement?.classList.toggle("hot", ctxPctNum >= .7);
1692
+ ctxPct.textContent = `${Math.round(ctxPctNum * 100)}%`;
1693
+ }
1671
1694
  const hit = snap.usage?.cacheHitRate;
1672
1695
  panel.querySelector("[data-cache]").textContent = typeof hit === "number" ? `${Math.round(hit * 100)}%` : "–";
1673
1696
  const pricing = snap.pricing;
@@ -1811,6 +1834,8 @@ window.__ModuleLoader__.load({
1811
1834
  "monitor.panel.net": "净节省",
1812
1835
  "monitor.panel.gross": "毛节省",
1813
1836
  "monitor.panel.offsets": "抵消",
1837
+ "monitor.panel.context": "上下文占用",
1838
+ "monitor.panel.suggest": "上下文占用已达 {pct}%——临近灾难性遗忘区,建议压缩或裁剪历史",
1814
1839
  "monitor.panel.cacheHit": "缓存命中率",
1815
1840
  "monitor.panel.cost": "成本(实际 / 省估)",
1816
1841
  "monitor.panel.intent": "意图摘要",
@@ -1947,6 +1972,8 @@ window.__ModuleLoader__.load({
1947
1972
  "monitor.panel.net": "Net savings",
1948
1973
  "monitor.panel.gross": "Gross savings",
1949
1974
  "monitor.panel.offsets": "Offsets",
1975
+ "monitor.panel.context": "Context occupancy",
1976
+ "monitor.panel.suggest": "Context occupancy reached {pct}% — nearing the catastrophic-forgetting zone; consider compressing or trimming history",
1950
1977
  "monitor.panel.cacheHit": "Cache hit rate",
1951
1978
  "monitor.panel.cost": "Cost (actual / saved est.)",
1952
1979
  "monitor.panel.intent": "Intent summary",
@@ -2085,6 +2112,8 @@ window.__ModuleLoader__.load({
2085
2112
  "monitor.panel.net": "Nettoeinsparung",
2086
2113
  "monitor.panel.gross": "Bruttoeinsparung",
2087
2114
  "monitor.panel.offsets": "Ausgleiche",
2115
+ "monitor.panel.context": "Kontextbelegung",
2116
+ "monitor.panel.suggest": "Kontextbelegung bei {pct}% — nahe der katastrophalen Vergessenszone; Komprimieren oder Kürzen des Verlaufs empfohlen",
2088
2117
  "monitor.panel.cacheHit": "Cache-Trefferquote",
2089
2118
  "monitor.panel.cost": "Kosten (ist / gespart gesch.)",
2090
2119
  "monitor.panel.intent": "Intent-Zusammenfassung",
@@ -2223,6 +2252,8 @@ window.__ModuleLoader__.load({
2223
2252
  "monitor.panel.net": "Ahorro neto",
2224
2253
  "monitor.panel.gross": "Ahorro bruto",
2225
2254
  "monitor.panel.offsets": "Compensaciones",
2255
+ "monitor.panel.context": "Ocupación del contexto",
2256
+ "monitor.panel.suggest": "La ocupación del contexto alcanzó el {pct} % — cerca de la zona de olvido catastrófico; se recomienda comprimir o recortar el historial",
2226
2257
  "monitor.panel.cacheHit": "Tasa de acierto de caché",
2227
2258
  "monitor.panel.cost": "Coste (real / ahorro est.)",
2228
2259
  "monitor.panel.intent": "Resumen de intención",
@@ -2361,6 +2392,8 @@ window.__ModuleLoader__.load({
2361
2392
  "monitor.panel.net": "Économie nette",
2362
2393
  "monitor.panel.gross": "Économie brute",
2363
2394
  "monitor.panel.offsets": "Compensations",
2395
+ "monitor.panel.context": "Occupation du contexte",
2396
+ "monitor.panel.suggest": "Occupation du contexte à {pct} % — zone de perte de contexte imminente ; pensez à lancer une compression ou à réduire les anciens échanges",
2364
2397
  "monitor.panel.cacheHit": "Taux de réussite du cache",
2365
2398
  "monitor.panel.cost": "Coût (réel / écon. est.)",
2366
2399
  "monitor.panel.intent": "Résumé d'intention",
@@ -2499,6 +2532,8 @@ window.__ModuleLoader__.load({
2499
2532
  "monitor.panel.net": "Risparmio netto",
2500
2533
  "monitor.panel.gross": "Risparmio lordo",
2501
2534
  "monitor.panel.offsets": "Compensazioni",
2535
+ "monitor.panel.context": "Occupazione del contesto",
2536
+ "monitor.panel.suggest": "Occupazione del contesto al {pct}% — vicini alla zona di dimenticanza catastrofica; consigliato comprimere o tagliare la cronologia",
2502
2537
  "monitor.panel.cacheHit": "Tasso di hit della cache",
2503
2538
  "monitor.panel.cost": "Costo (effettivo / stimo)",
2504
2539
  "monitor.panel.intent": "Riepilogo di intento",
@@ -2637,6 +2672,8 @@ window.__ModuleLoader__.load({
2637
2672
  "monitor.panel.net": "正味節約",
2638
2673
  "monitor.panel.gross": "総節約",
2639
2674
  "monitor.panel.offsets": "相殺",
2675
+ "monitor.panel.context": "コンテキスト占有",
2676
+ "monitor.panel.suggest": "コンテキスト占有が {pct}% に達しました——壊滅的忘却ゾーンに近づいています。圧縮または履歴の削減を推奨",
2640
2677
  "monitor.panel.cacheHit": "キャッシュ ヒット率",
2641
2678
  "monitor.panel.cost": "コスト(実績 / 節約概算)",
2642
2679
  "monitor.panel.intent": "インテント要約",
@@ -2775,6 +2812,8 @@ window.__ModuleLoader__.load({
2775
2812
  "monitor.panel.net": "순 절감",
2776
2813
  "monitor.panel.gross": "총 절감",
2777
2814
  "monitor.panel.offsets": "상쇄",
2815
+ "monitor.panel.context": "컨텍스트 점유",
2816
+ "monitor.panel.suggest": "컨텍스트 점유가 {pct}%에 도달——치명적 망각 구간에 근접, 압축이나 기록 정리를 권장",
2778
2817
  "monitor.panel.cacheHit": "캐시 적중률",
2779
2818
  "monitor.panel.cost": "비용 (실제 / 절감 추정)",
2780
2819
  "monitor.panel.intent": "인텐트 요약",
@@ -2913,6 +2952,8 @@ window.__ModuleLoader__.load({
2913
2952
  "monitor.panel.net": "Чистая экономия",
2914
2953
  "monitor.panel.gross": "Валовая экономия",
2915
2954
  "monitor.panel.offsets": "Компенсации",
2955
+ "monitor.panel.context": "Заполнение контекста",
2956
+ "monitor.panel.suggest": "Заполнение контекста достигло {pct}% — близко к зоне катастрофического забывания; рекомендуется сжать или обрезать историю",
2916
2957
  "monitor.panel.cacheHit": "Процент попаданий кэша",
2917
2958
  "monitor.panel.cost": "Стоимость (факт / эконом. оценка)",
2918
2959
  "monitor.panel.intent": "Итог намерения",
@@ -3125,25 +3166,30 @@ window.__ModuleLoader__.load({
3125
3166
  return false;
3126
3167
  }
3127
3168
  };
3128
- initMonitorFab({
3129
- t: tNav,
3130
- sessionIdOf: () => void 0,
3131
- enabledOf: () => readMonitorPanelEnabled(),
3132
- fetchSnapshot: async (sessionId) => {
3133
- const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
3134
- const response = await fetch(`/api/dsh-context-compression-improved/monitor${query}`, { headers: { "cache-control": "no-cache" } });
3135
- if (!response.ok) throw new Error(`monitor snapshot ${response.status}`);
3136
- return await response.json();
3137
- },
3138
- applyOverride: async (sessionId, action) => {
3139
- const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
3140
- await fetch(`/api/dsh-context-compression-improved/monitor${query}`, {
3141
- method: "POST",
3142
- headers: { "content-type": "application/json" },
3143
- body: JSON.stringify({ action })
3144
- });
3145
- }
3146
- });
3169
+ let latestSessionId;
3170
+ try {
3171
+ initMonitorFab({
3172
+ t: tNav,
3173
+ sessionIdOf: () => latestSessionId,
3174
+ enabledOf: () => readMonitorPanelEnabled(),
3175
+ fetchSnapshot: async (sessionId) => {
3176
+ const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
3177
+ const response = await fetch(`/api/dsh-context-compression-improved/monitor${query}`, { headers: { "cache-control": "no-cache" } });
3178
+ if (!response.ok) throw new Error(`monitor snapshot ${response.status}`);
3179
+ return await response.json();
3180
+ },
3181
+ applyOverride: async (sessionId, action) => {
3182
+ const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
3183
+ await fetch(`/api/dsh-context-compression-improved/monitor${query}`, {
3184
+ method: "POST",
3185
+ headers: { "content-type": "application/json" },
3186
+ body: JSON.stringify({ action })
3187
+ });
3188
+ }
3189
+ });
3190
+ } catch (error) {
3191
+ console.warn("[dsh-context-compression-improved] 监控浮动球挂载失败(不影响设置分节):", error);
3192
+ }
3147
3193
  const injected = () => {
3148
3194
  const form = ctx.configForms.get(ENTRY_ID);
3149
3195
  const readDoc = () => decodeSettings(form.getSnapshot().value?.settings);
@@ -3233,6 +3279,19 @@ window.__ModuleLoader__.load({
3233
3279
  } catch (error) {
3234
3280
  console.warn("[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):", error);
3235
3281
  }
3282
+ try {
3283
+ ctx.slots.inject("conversation.input.left", () => ctx.slots.register({
3284
+ name: "conversation.input.left",
3285
+ id: "context-compression-session-bind",
3286
+ order: 170,
3287
+ inject: (sessionId) => {
3288
+ latestSessionId = sessionId;
3289
+ return {};
3290
+ }
3291
+ }, () => null));
3292
+ } catch (error) {
3293
+ console.warn("[dsh-context-compression-improved] conversation.input.left 注册失败(旧宿主无该槽,浮动面板保持聚合口径):", error);
3294
+ }
3236
3295
  }
3237
3296
  //#endregion
3238
3297
  exports.apply = apply;
@@ -634,6 +634,150 @@ function evaluateIntentGate(input) {
634
634
  return snapshot(true, "passed");
635
635
  }
636
636
  //#endregion
637
+ //#region src/runtime/monitor.ts
638
+ /**
639
+ * 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
640
+ * 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
641
+ * (默认 80%)——提前一档给出人工干预窗口。
642
+ */
643
+ const MONITOR_SUGGEST_PCT = .7;
644
+ /**
645
+ * Savings snapshot plus the intent-summary control block. Ledger is
646
+ * injectable so tests seed a private instance instead of the process
647
+ * singleton.
648
+ */
649
+ function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
650
+ const scopeKey = sessionId ?? "";
651
+ const override = getSummaryOverride(scopeKey);
652
+ const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
653
+ const contextBlock = observedContext === void 0 ? void 0 : {
654
+ liveTokens: observedContext.liveTokens,
655
+ contextWindow: observedContext.contextWindow,
656
+ pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
657
+ sessionId: observedContext.sessionId
658
+ };
659
+ const suggestion = contextBlock === void 0 || contextBlock.pct === null ? void 0 : {
660
+ suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
661
+ thresholdPct: MONITOR_SUGGEST_PCT,
662
+ occupancyPct: contextBlock.pct
663
+ };
664
+ return {
665
+ ...ledger.snapshot(sessionId),
666
+ ...contextBlock === void 0 ? {} : { context: contextBlock },
667
+ ...suggestion === void 0 ? {} : { suggestion },
668
+ intent: {
669
+ override,
670
+ observedEnabled: getObservedIntentEnabled(scopeKey),
671
+ gate: {
672
+ floorFraction: INTENT_GATE_FLOOR_FRACTION,
673
+ growthTokens: INTENT_GATE_GROWTH_TOKENS
674
+ },
675
+ lastFold: getLastIntentFold(scopeKey)
676
+ },
677
+ sessionScope: sessionId ?? null
678
+ };
679
+ }
680
+ /** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
681
+ const contextUsageBySession = /* @__PURE__ */ new Map();
682
+ const CONTEXT_USAGE_CAP = 64;
683
+ /**
684
+ * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
685
+ * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
686
+ */
687
+ function observeContextUsage(sessionId, liveTokens, contextWindow) {
688
+ if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
689
+ if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
690
+ const oldest = contextUsageBySession.keys().next().value;
691
+ if (oldest !== void 0) contextUsageBySession.delete(oldest);
692
+ }
693
+ contextUsageBySession.set(sessionId, {
694
+ liveTokens,
695
+ contextWindow,
696
+ at: Date.now(),
697
+ seq: ++observeSeq
698
+ });
699
+ }
700
+ function getContextUsage(sessionId) {
701
+ const entry = contextUsageBySession.get(sessionId);
702
+ return entry === void 0 ? void 0 : {
703
+ liveTokens: entry.liveTokens,
704
+ contextWindow: entry.contextWindow,
705
+ sessionId
706
+ };
707
+ }
708
+ let observeSeq = 0;
709
+ function latestObservedContextUsage() {
710
+ let latest;
711
+ for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
712
+ sessionId,
713
+ liveTokens: entry.liveTokens,
714
+ contextWindow: entry.contextWindow,
715
+ seq: entry.seq
716
+ };
717
+ return latest;
718
+ }
719
+ function isSessionOverrideAction(value) {
720
+ return value === "on" || value === "off" || value === "clear";
721
+ }
722
+ /**
723
+ * Drive the `/ctx-summary` override state machine: `on`/`off` pin the
724
+ * session, `clear` returns it to settings-driven. The resulting override is
725
+ * handed back so the route can echo the post-action truth.
726
+ */
727
+ function applySessionOverride(sessionId, action) {
728
+ setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
729
+ return { override: getSummaryOverride(sessionId) };
730
+ }
731
+ /**
732
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
733
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
734
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
735
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
736
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
737
+ * (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
738
+ */
739
+ function estimateSavingsPricing(readService, snapshot) {
740
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
741
+ const selection = readService("agentDefaultModel")?.currentSelection?.();
742
+ const provider = typeof selection?.provider === "string" ? selection.provider : "";
743
+ const modelId = typeof selection?.model === "string" ? selection.model : "";
744
+ if (provider !== "deepseek-official") return void 0;
745
+ const now = /* @__PURE__ */ new Date();
746
+ const startedAt = new Date(snapshot.startedAt);
747
+ const base = {
748
+ provider,
749
+ baseUrlClass: "official-public",
750
+ apiRoute: "chat-completions",
751
+ modelId,
752
+ currency: "USD",
753
+ startedAt,
754
+ completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
755
+ };
756
+ const actual = priceOfficialDeepSeekUsage({
757
+ ...base,
758
+ usage: {
759
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
760
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
761
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
762
+ }
763
+ });
764
+ const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
765
+ ...base,
766
+ usage: {
767
+ cacheReadTokens: 0,
768
+ cacheMissTokens: Math.round(snapshot.net.exact),
769
+ outputTokens: 0
770
+ }
771
+ }) : void 0;
772
+ const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
773
+ if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
774
+ return {
775
+ currency: "USD",
776
+ ...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
777
+ ...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
778
+ };
779
+ }
780
+ //#endregion
637
781
  //#region src/runtime/types.ts
638
782
  /** User-facing mixed strategy profile. */
639
783
  const COMPRESSION_PROFILES = [
@@ -1566,4 +1710,4 @@ function assertNonNegativeInteger(name, value) {
1566
1710
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
1567
1711
  }
1568
1712
  //#endregion
1569
- export { recordIntentFold as A, evaluateIntentGate as C, getSummaryOverride as D, getObservedIntentEnabled as E, decimalRateNanoUnits as F, priceOfficialDeepSeekUsage as I, resolveOfficialDeepSeekPrice as L, recordScore as M, setSummaryOverride as N, invalidateOnTaskChange as O, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as P, getSavingsLedger as R, INTENT_GATE_GROWTH_TOKENS as S, getLastIntentFold as T, 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, recordRecertified as j, observeIntentEnabled 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, getAdvisorState as w, INTENT_GATE_FLOOR_FRACTION as x, deepFreeze as y };
1713
+ 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 { D as getSummaryOverride, E as getObservedIntentEnabled, I as priceOfficialDeepSeekUsage, N as setSummaryOverride, R as getSavingsLedger, S as INTENT_GATE_GROWTH_TOKENS, T as getLastIntentFold, a as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, w as getAdvisorState, x as INTENT_GATE_FLOOR_FRACTION } from "./config.js";
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 { A as recordIntentFold, C as evaluateIntentGate, D as getSummaryOverride, F as decimalRateNanoUnits, I as priceOfficialDeepSeekUsage, L as resolveOfficialDeepSeekPrice, M as recordScore, O as invalidateOnTaskChange, P as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, R as getSavingsLedger, _ 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, j as recordRecertified, k as observeIntentEnabled, 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, w as getAdvisorState, y as deepFreeze } from "./config.js";
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";
@@ -4064,6 +4064,9 @@ var ToolResultPruner = class extends Service {
4064
4064
  this.auditFailure(agent.session, "fresh", "terminal-pass", error);
4065
4065
  ctx.logger.warn("context-compression terminal pass failed open: %o", error);
4066
4066
  }
4067
+ try {
4068
+ observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
4069
+ } catch {}
4067
4070
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4068
4071
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4069
4072
  this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
@@ -119,9 +119,12 @@ export function apply(ctx: ClientContext): void {
119
119
  return false
120
120
  }
121
121
  }
122
- initMonitorFab({
122
+ // 浮动面板会话绑定:跟随输入栏座位的 inject 回调(裸 sessionId,pm longtask 同款)。
123
+ let latestSessionId: string | undefined
124
+ try {
125
+ initMonitorFab({
123
126
  t: tNav,
124
- sessionIdOf: () => undefined, // v1: 全会话聚合(savings 卡同口径);会话级绑定待输入栏座位
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,8 @@ 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',
78
+ 'monitor.panel.suggest': 'Kontextbelegung bei {pct}% — nahe der katastrophalen Vergessenszone; Komprimieren oder Kürzen des Verlaufs empfohlen',
77
79
  'monitor.panel.cacheHit': 'Cache-Trefferquote',
78
80
  'monitor.panel.cost': 'Kosten (ist / gespart gesch.)',
79
81
  'monitor.panel.intent': 'Intent-Zusammenfassung',
@@ -74,6 +74,8 @@ 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',
78
+ 'monitor.panel.suggest': 'La ocupación del contexto alcanzó el {pct} % — cerca de la zona de olvido catastrófico; se recomienda comprimir o recortar el historial',
77
79
  'monitor.panel.cacheHit': 'Tasa de acierto de caché',
78
80
  'monitor.panel.cost': 'Coste (real / ahorro est.)',
79
81
  'monitor.panel.intent': 'Resumen de intención',
@@ -74,6 +74,8 @@ 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',
78
+ 'monitor.panel.suggest': 'Occupation du contexte à {pct} % — zone de perte de contexte imminente ; pensez à lancer une compression ou à réduire les anciens échanges',
77
79
  'monitor.panel.cacheHit': 'Taux de réussite du cache',
78
80
  'monitor.panel.cost': 'Coût (réel / écon. est.)',
79
81
  'monitor.panel.intent': 'Résumé d\'intention',
@@ -74,6 +74,8 @@ 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',
78
+ 'monitor.panel.suggest': 'Occupazione del contesto al {pct}% — vicini alla zona di dimenticanza catastrofica; consigliato comprimere o tagliare la cronologia',
77
79
  'monitor.panel.cacheHit': 'Tasso di hit della cache',
78
80
  'monitor.panel.cost': 'Costo (effettivo / stimo)',
79
81
  'monitor.panel.intent': 'Riepilogo di intento',
@@ -74,6 +74,8 @@ export const ja = {
74
74
  'monitor.panel.net': '正味節約',
75
75
  'monitor.panel.gross': '総節約',
76
76
  'monitor.panel.offsets': '相殺',
77
+ 'monitor.panel.context': 'コンテキスト占有',
78
+ 'monitor.panel.suggest': 'コンテキスト占有が {pct}% に達しました——壊滅的忘却ゾーンに近づいています。圧縮または履歴の削減を推奨',
77
79
  'monitor.panel.cacheHit': 'キャッシュ ヒット率',
78
80
  'monitor.panel.cost': 'コスト(実績 / 節約概算)',
79
81
  'monitor.panel.intent': 'インテント要約',
@@ -74,6 +74,8 @@ export const ko = {
74
74
  'monitor.panel.net': '순 절감',
75
75
  'monitor.panel.gross': '총 절감',
76
76
  'monitor.panel.offsets': '상쇄',
77
+ 'monitor.panel.context': '컨텍스트 점유',
78
+ 'monitor.panel.suggest': '컨텍스트 점유가 {pct}%에 도달——치명적 망각 구간에 근접, 압축이나 기록 정리를 권장',
77
79
  'monitor.panel.cacheHit': '캐시 적중률',
78
80
  'monitor.panel.cost': '비용 (실제 / 절감 추정)',
79
81
  'monitor.panel.intent': '인텐트 요약',
@@ -74,6 +74,8 @@ export const ru = {
74
74
  'monitor.panel.net': 'Чистая экономия',
75
75
  'monitor.panel.gross': 'Валовая экономия',
76
76
  'monitor.panel.offsets': 'Компенсации',
77
+ 'monitor.panel.context': 'Заполнение контекста',
78
+ 'monitor.panel.suggest': 'Заполнение контекста достигло {pct}% — близко к зоне катастрофического забывания; рекомендуется сжать или обрезать историю',
77
79
  'monitor.panel.cacheHit': 'Процент попаданий кэша',
78
80
  'monitor.panel.cost': 'Стоимость (факт / эконом. оценка)',
79
81
  'monitor.panel.intent': 'Итог намерения',
@@ -72,6 +72,8 @@ export const zh = {
72
72
  'monitor.panel.net': '净节省',
73
73
  'monitor.panel.gross': '毛节省',
74
74
  'monitor.panel.offsets': '抵消',
75
+ 'monitor.panel.context': '上下文占用',
76
+ 'monitor.panel.suggest': '上下文占用已达 {pct}%——临近灾难性遗忘区,建议压缩或裁剪历史',
75
77
  'monitor.panel.cacheHit': '缓存命中率',
76
78
  'monitor.panel.cost': '成本(实际 / 省估)',
77
79
  'monitor.panel.intent': '意图摘要',
@@ -214,6 +216,8 @@ export const en = {
214
216
  'monitor.panel.net': 'Net savings',
215
217
  'monitor.panel.gross': 'Gross savings',
216
218
  'monitor.panel.offsets': 'Offsets',
219
+ 'monitor.panel.context': 'Context occupancy',
220
+ 'monitor.panel.suggest': 'Context occupancy reached {pct}% — nearing the catastrophic-forgetting zone; consider compressing or trimming history',
217
221
  'monitor.panel.cacheHit': 'Cache hit rate',
218
222
  'monitor.panel.cost': 'Cost (actual / saved est.)',
219
223
  'monitor.panel.intent': 'Intent summary',
@@ -37,6 +37,8 @@ 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 }
41
+ suggestion?: { suggest?: unknown; thresholdPct?: unknown; occupancyPct?: unknown }
40
42
  recentOffsets?: Array<{ component?: unknown; tokens?: unknown }>
41
43
  sessionScope?: string | null
42
44
  }
@@ -91,6 +93,9 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
91
93
  #${PANEL_ID} button.ghost { background: transparent; }
92
94
  #${PANEL_ID} button:disabled { opacity: .45; cursor: default; }
93
95
  #${PANEL_ID} .stale { padding: 4px 14px 8px; color: #ffd60a; display: none; }
96
+ #${PANEL_ID} .hint { margin: 0; padding: 8px 14px; color: #ffd60a; display: none;
97
+ border-bottom: 1px solid rgba(255,255,255,.09); }
98
+ #${PANEL_ID} .hint.show { display: block; }
94
99
  #${PANEL_ID} .stale.show { display: block; }
95
100
  #${PANEL_ID} .recent { max-height: 132px; overflow: auto; padding: 2px 14px 8px;
96
101
  color: rgba(245,245,247,.8); white-space: pre-wrap; }
@@ -108,9 +113,11 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
108
113
  panel.hidden = true;
109
114
  panel.innerHTML = `
110
115
  <h4>${t('monitor.panel.title')}</h4>
116
+ <div class="hint" data-hint></div>
111
117
  <div class="row"><span class="label">${t('monitor.panel.net')}</span><span data-net>–</span></div>
112
118
  <div class="row"><span class="label">${t('monitor.panel.gross')}</span><span data-gross class="muted">–</span></div>
113
119
  <div class="row"><span class="label">${t('monitor.panel.offsets')}</span><span data-offsets class="muted">–</span></div>
120
+ <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
121
  <div class="row"><span class="label">${t('monitor.panel.cacheHit')}</span><span data-cache class="muted">–</span></div>
115
122
  <div class="row"><span class="label">${t('monitor.panel.cost')}</span><span data-cost class="muted">–</span></div>
116
123
  <div class="row"><span class="label">${t('monitor.panel.intent')}</span><span data-intent class="muted">–</span></div>
@@ -210,11 +217,33 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
210
217
  last = snap;
211
218
  const net = num(snap.net?.exact) + num(snap.net?.estimated);
212
219
  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)` : ''}`;
220
+ netEl.textContent = `${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ''}`;
214
221
  netEl.classList.toggle('neg', net < 0);
215
- fab.classList.toggle('lit', net < 0);
222
+ const suggest = snap.suggestion?.suggest === true;
223
+ fab.classList.toggle('lit', suggest || net < 0);
224
+ const hint = panel.querySelector('[data-hint]') as HTMLElement;
225
+ if (suggest) {
226
+ const pct = typeof snap.suggestion?.occupancyPct === 'number'
227
+ ? Math.round(snap.suggestion.occupancyPct * 100)
228
+ : null;
229
+ hint.textContent = (t('monitor.panel.suggest') as string).replace('{pct}', String(pct ?? '–'));
230
+ hint.classList.add('show');
231
+ } else {
232
+ hint.classList.remove('show');
233
+ }
216
234
  (panel.querySelector('[data-gross]') as HTMLElement).textContent = fmtTokens(snap.gross?.exact);
217
235
  (panel.querySelector('[data-offsets]') as HTMLElement).textContent = `-${fmtTokens(snap.offsets?.exact)}`;
236
+ const ctxBar = panel.querySelector('[data-ctxbar]') as HTMLElement;
237
+ const ctxPct = panel.querySelector('[data-ctxpct]') as HTMLElement;
238
+ const ctxPctNum = typeof snap.context?.pct === 'number' ? snap.context.pct : null;
239
+ if (ctxPctNum === null) {
240
+ ctxBar.style.width = '0%';
241
+ ctxPct.textContent = '–';
242
+ } else {
243
+ ctxBar.style.width = `${Math.min(100, Math.round(ctxPctNum * 100))}%`;
244
+ ctxBar.parentElement?.classList.toggle('hot', ctxPctNum >= 0.7);
245
+ ctxPct.textContent = `${Math.round(ctxPctNum * 100)}%`;
246
+ }
218
247
  const hit = snap.usage?.cacheHitRate;
219
248
  (panel.querySelector('[data-cache]') as HTMLElement).textContent =
220
249
  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,
@@ -345,6 +346,15 @@ export class ToolResultPruner extends Service {
345
346
  this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
346
347
  ctx.logger.warn('context-compression terminal pass failed open: %o', error)
347
348
  }
349
+ // 压缩监控观测:每回合无条件记录上下文占用——面板占用条与
350
+ // 灾难性遗忘区建议的数据源,与 intentSummary 门控解耦(门关也可观测)。
351
+ try {
352
+ observeContextUsage(
353
+ String(agent.session.id),
354
+ measureForCompaction(this.ctx, agent.session).totalTokens,
355
+ this.contextWindowForRequest(agent.session),
356
+ )
357
+ } catch { /* 观测失败静默:面板显示陈旧/空态 */ }
348
358
  // TokenPilot-inspired E1: advisory estimator pass, strictly off the
349
359
  // synchronous chain. Verdicts only feed the next pressure pass.
350
360
  void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
@@ -37,6 +37,13 @@ import {
37
37
  } from './tokenpilot/advisor-state.ts'
38
38
  import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
39
39
 
40
+ /**
41
+ * 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
42
+ * 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
43
+ * (默认 80%)——提前一档给出人工干预窗口。
44
+ */
45
+ export const MONITOR_SUGGEST_PCT = 0.7
46
+
40
47
  export interface MonitorIntentBlock {
41
48
  /** Session-scoped override; absent = settings-driven. */
42
49
  override: 'on' | 'off' | undefined
@@ -46,8 +53,27 @@ export interface MonitorIntentBlock {
46
53
  lastFold: IntentFoldRecord | undefined
47
54
  }
48
55
 
56
+ export interface MonitorContextBlock {
57
+ liveTokens: number
58
+ contextWindow: number | undefined
59
+ /** liveTokens / contextWindow, rounded to 3 decimals; null when the window is unknown. */
60
+ pct: number | null
61
+ sessionId: string
62
+ }
63
+
64
+ export interface MonitorSuggestionBlock {
65
+ /** 占用达到建议阈值——客户端点亮悬浮球并展示提示行。 */
66
+ suggest: boolean
67
+ thresholdPct: number
68
+ occupancyPct: number | null
69
+ }
70
+
49
71
  export type MonitorSnapshot = SavingsSnapshot & {
50
72
  intent: MonitorIntentBlock
73
+ /** Latest observed context occupancy; undefined until the pruner observes a turn. */
74
+ context?: MonitorContextBlock
75
+ /** 灾难性遗忘区建议;未观测前 absent。 */
76
+ suggestion?: MonitorSuggestionBlock
51
77
  /** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
52
78
  sessionScope: string | null
53
79
  }
@@ -61,19 +87,79 @@ export function buildMonitorSnapshot(
61
87
  sessionId?: string,
62
88
  ledger: SavingsLedger = getSavingsLedger(),
63
89
  ): MonitorSnapshot {
64
- const override = getSummaryOverride(sessionId ?? '')
90
+ const scopeKey = sessionId ?? ''
91
+ const override = getSummaryOverride(scopeKey)
92
+ const observedContext = scopeKey.length > 0
93
+ ? getContextUsage(scopeKey)
94
+ : latestObservedContextUsage()
95
+ const contextBlock = observedContext === undefined
96
+ ? undefined
97
+ : {
98
+ liveTokens: observedContext.liveTokens,
99
+ contextWindow: observedContext.contextWindow,
100
+ pct: observedContext.contextWindow !== undefined && observedContext.contextWindow > 0
101
+ ? Math.round((observedContext.liveTokens / observedContext.contextWindow) * 1000) / 1000
102
+ : null,
103
+ sessionId: observedContext.sessionId,
104
+ }
105
+ const suggestion = contextBlock === undefined || contextBlock.pct === null
106
+ ? undefined
107
+ : {
108
+ suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
109
+ thresholdPct: MONITOR_SUGGEST_PCT,
110
+ occupancyPct: contextBlock.pct,
111
+ }
65
112
  return {
66
113
  ...ledger.snapshot(sessionId),
114
+ ...(contextBlock === undefined ? {} : { context: contextBlock }),
115
+ ...(suggestion === undefined ? {} : { suggestion }),
67
116
  intent: {
68
117
  override,
69
- observedEnabled: getObservedIntentEnabled(sessionId ?? ''),
118
+ observedEnabled: getObservedIntentEnabled(scopeKey),
70
119
  gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
71
- lastFold: getLastIntentFold(sessionId ?? ''),
120
+ lastFold: getLastIntentFold(scopeKey),
72
121
  },
73
122
  sessionScope: sessionId ?? null,
74
123
  }
75
124
  }
76
125
 
126
+ export interface ContextUsageObservation {
127
+ liveTokens: number
128
+ contextWindow: number | undefined
129
+ }
130
+
131
+ /** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
132
+ const contextUsageBySession = new Map<string, ContextUsageObservation & { at: number; seq: number }>()
133
+ const CONTEXT_USAGE_CAP = 64
134
+
135
+ /**
136
+ * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
137
+ * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
138
+ */
139
+ export function observeContextUsage(sessionId: string, liveTokens: number, contextWindow: number | undefined): void {
140
+ if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return
141
+ if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
142
+ const oldest = contextUsageBySession.keys().next().value
143
+ if (oldest !== undefined) contextUsageBySession.delete(oldest)
144
+ }
145
+ contextUsageBySession.set(sessionId, { liveTokens, contextWindow, at: Date.now(), seq: ++observeSeq })
146
+ }
147
+
148
+ export function getContextUsage(sessionId: string): (ContextUsageObservation & { sessionId: string }) | undefined {
149
+ const entry = contextUsageBySession.get(sessionId)
150
+ return entry === undefined ? undefined : { liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, sessionId }
151
+ }
152
+
153
+ let observeSeq = 0
154
+
155
+ function latestObservedContextUsage(): (ContextUsageObservation & { sessionId: string }) | undefined {
156
+ let latest: (ContextUsageObservation & { sessionId: string; seq: number }) | undefined
157
+ for (const [sessionId, entry] of contextUsageBySession) {
158
+ if (latest === undefined || entry.seq > latest.seq) latest = { sessionId, liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, seq: entry.seq }
159
+ }
160
+ return latest
161
+ }
162
+
77
163
  export type SessionOverrideAction = 'on' | 'off' | 'clear'
78
164
 
79
165
  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
  },
@@ -107,6 +107,27 @@ describe('monitor fab (body-level overlay)', () => {
107
107
  await waitFor(() => (deps.fetchSnapshot as ReturnType<typeof vi.fn>).mock.calls.length >= 2)
108
108
  })
109
109
 
110
+ it('灾难性遗忘区建议:点亮悬浮球并展示提示行', async () => {
111
+ const deps = makeDeps({
112
+ snapshots: [snapshotPatch({
113
+ net: { exact: 0, estimated: 0 },
114
+ context: { liveTokens: 90_000, contextWindow: 100_000, pct: 0.9 },
115
+ suggestion: { suggest: true, thresholdPct: 0.7, occupancyPct: 0.9 },
116
+ })],
117
+ })
118
+ initMonitorFab(deps)
119
+ await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
120
+ const hint = document.querySelector('[data-hint]') as HTMLElement
121
+ expect(hint.classList.contains('show')).toBe(true)
122
+ expect(hint.textContent).toBe('monitor.panel.suggest')
123
+ })
124
+
125
+ it('无建议时提示行隐藏', async () => {
126
+ initMonitorFab(makeDeps())
127
+ await waitFor(() => (document.querySelector('[data-net]') as HTMLElement).textContent !== '')
128
+ expect(document.querySelector('[data-hint]')?.classList.contains('show')).toBe(false)
129
+ })
130
+
110
131
  it('position persists across drag-free re-init via localStorage', () => {
111
132
  localStorage.setItem('dsh.cci.monitor.pos', JSON.stringify({ x: 40, y: 60 }))
112
133
  initMonitorFab(makeDeps())
@@ -3,6 +3,8 @@ import { parseContextCompressionSettings, DEFAULT_CONTEXT_COMPRESSION_SETTINGS }
3
3
  import { SavingsLedger } from '../../src/runtime/savings.ts'
4
4
  import {
5
5
  applySessionOverride,
6
+ MONITOR_SUGGEST_PCT,
7
+ observeContextUsage,
6
8
  buildMonitorSnapshot,
7
9
  estimateSavingsPricing,
8
10
  isSessionOverrideAction,
@@ -234,3 +236,66 @@ describe('monitorPanel settings parsing (schema surface, mirrors intentSummary c
234
236
  .toThrow(/monitorPanel must be a plain object/)
235
237
  })
236
238
  })
239
+
240
+ describe('context occupancy observation (task_6.2)', () => {
241
+ it('scoped snapshot carries the observed occupancy block', () => {
242
+ const sessionId = uniqueSession()
243
+ observeContextUsage(sessionId, 60_000, 128_000)
244
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
245
+ expect(snap.context).toEqual({ liveTokens: 60_000, contextWindow: 128_000, pct: 0.469, sessionId })
246
+ })
247
+
248
+ it('aggregate snapshot carries the most recently observed session', () => {
249
+ const a = uniqueSession()
250
+ const b = uniqueSession()
251
+ observeContextUsage(a, 10_000, 100_000)
252
+ observeContextUsage(b, 90_000, 100_000)
253
+ const snap = buildMonitorSnapshot(undefined, new SavingsLedger())
254
+ expect(snap.context?.sessionId).toBe(b)
255
+ expect(snap.context?.pct).toBe(0.9)
256
+ })
257
+
258
+ it('no observation yet — context block absent', () => {
259
+ const snap = buildMonitorSnapshot(uniqueSession(), new SavingsLedger())
260
+ expect(snap.context).toBeUndefined()
261
+ })
262
+
263
+ it('observation cap keeps the newest 64 sessions', () => {
264
+ for (let i = 0; i < 70; i++) observeContextUsage(`cap-${i}`, i, 1000)
265
+ const snap = buildMonitorSnapshot('cap-69', new SavingsLedger())
266
+ expect(snap.context?.sessionId).toBe('cap-69')
267
+ })
268
+
269
+ it('empty session id and non-finite tokens are ignored', () => {
270
+ observeContextUsage('', 5, 100)
271
+ observeContextUsage('fin-check', Number.NaN, 100)
272
+ expect(buildMonitorSnapshot('fin-check', new SavingsLedger()).context).toBeUndefined()
273
+ })
274
+ })
275
+
276
+ describe('catastrophic-forgetting suggestion (task: 建议压缩)', () => {
277
+ it('occupancy past the threshold suggests compression', () => {
278
+ const sessionId = uniqueSession()
279
+ observeContextUsage(sessionId, 90_000, 100_000)
280
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
281
+ expect(snap.suggestion?.suggest).toBe(true)
282
+ expect(snap.suggestion?.thresholdPct).toBe(MONITOR_SUGGEST_PCT)
283
+ expect(snap.suggestion?.occupancyPct).toBe(0.9)
284
+ })
285
+
286
+ it('below the threshold stays silent', () => {
287
+ const sessionId = uniqueSession()
288
+ observeContextUsage(sessionId, 50_000, 100_000)
289
+ const snap = buildMonitorSnapshot(sessionId, new SavingsLedger())
290
+ expect(snap.suggestion?.suggest).toBe(false)
291
+ })
292
+
293
+ it('threshold sits below the host auto-compact default (提前一档人工干预窗口)', () => {
294
+ expect(MONITOR_SUGGEST_PCT).toBeLessThan(0.8)
295
+ })
296
+
297
+ it('unobserved sessions carry no suggestion block', () => {
298
+ expect(buildMonitorSnapshot(uniqueSession(), new SavingsLedger()).suggestion).toBeUndefined()
299
+ })
300
+ })
301
+
@@ -64,16 +64,17 @@ function collectRegistrations(
64
64
  return { declared, registrations }
65
65
  }
66
66
 
67
- describe('settings-seat contract (standalone settings.section only)', () => {
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 seat and nothing else', () => {
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(1)
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 the seat (so the degradation is "loud", not a silent no-op)…
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 {