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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/package.json +1 -1
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +23 -0
  5. package/packages/selector/lib/client.js +567 -3
  6. package/packages/selector/lib/{intent-gate.js → config.js} +285 -136
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +131 -50
  9. package/packages/selector/lib/profiles.d.ts +6 -0
  10. package/packages/selector/lib/pruner.d.ts +6 -0
  11. package/packages/selector/lib/pruner.js +5 -3
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
  14. package/packages/selector/src/client/decode.ts +5 -1
  15. package/packages/selector/src/client/index.ts +60 -0
  16. package/packages/selector/src/client/locales/de.ts +22 -0
  17. package/packages/selector/src/client/locales/es.ts +22 -0
  18. package/packages/selector/src/client/locales/fr.ts +22 -0
  19. package/packages/selector/src/client/locales/it.ts +22 -0
  20. package/packages/selector/src/client/locales/ja.ts +22 -0
  21. package/packages/selector/src/client/locales/ko.ts +22 -0
  22. package/packages/selector/src/client/locales/ru.ts +22 -0
  23. package/packages/selector/src/client/locales.ts +44 -0
  24. package/packages/selector/src/client/monitor-fab.ts +320 -0
  25. package/packages/selector/src/client/settings-section.tsx +9 -2
  26. package/packages/selector/src/index.ts +126 -60
  27. package/packages/selector/src/profiles.ts +17 -0
  28. package/packages/selector/src/pruner.ts +2 -0
  29. package/packages/selector/src/runtime/config.ts +26 -1
  30. package/packages/selector/src/runtime/monitor.ts +211 -0
  31. package/packages/selector/src/runtime/types.ts +7 -0
  32. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  33. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  34. package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
  35. package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
  36. package/packages/selector/tests/runtime/monitor.spec.ts +274 -0
  37. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  38. package/scripts/packed-install-e2e.mjs +1 -1
  39. package/scripts/verify-release.mjs +1 -1
@@ -1,4 +1,4 @@
1
- import { I as priceOfficialDeepSeekUsage, R as getSavingsLedger, a as getLastIntentFold, i as getAdvisorState, n as INTENT_GATE_GROWTH_TOKENS, o as getObservedIntentEnabled, p as setSummaryOverride, s as getSummaryOverride, t as INTENT_GATE_FLOOR_FRACTION, v as DEFAULT_CONTEXT_COMPRESSION_SETTINGS } from "./intent-gate.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";
@@ -595,6 +595,7 @@ function restoreMethod(presets, snapshot) {
595
595
  const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
596
596
  const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advisor-report", "/api/dsh-context-compression-improved/advisor-report"];
597
597
  const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
598
+ const MONITOR_ROUTES = ["/endpoint/dsh-context-compression-improved/monitor", "/api/dsh-context-compression-improved/monitor"];
598
599
  function sessionFor(readService, sessionId) {
599
600
  const agents = readService("agents");
600
601
  return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
@@ -717,6 +718,7 @@ function registerAdvisorReportRoute(ctx) {
717
718
  * never reasons to withhold the route.
718
719
  */
719
720
  const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
721
+ /** The estimator-side service the catalog handler enriches its response with. */
720
722
  function asWebServer(value) {
721
723
  if (typeof value !== "object" || value === null) return void 0;
722
724
  return typeof value.register === "function" ? value : void 0;
@@ -810,54 +812,6 @@ function registerEstimatorCatalogRoute(ctx) {
810
812
  log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
811
813
  }
812
814
  /**
813
- * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
814
- * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
815
- * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
816
- * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
817
- * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
818
- */
819
- function estimateSavingsPricing(readService, snapshot) {
820
- if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
821
- const selection = readService("agentDefaultModel")?.currentSelection?.();
822
- const provider = typeof selection?.provider === "string" ? selection.provider : "";
823
- const modelId = typeof selection?.model === "string" ? selection.model : "";
824
- if (provider !== "deepseek-official") return void 0;
825
- const now = /* @__PURE__ */ new Date();
826
- const startedAt = new Date(snapshot.startedAt);
827
- const base = {
828
- provider,
829
- baseUrlClass: "official-public",
830
- apiRoute: "chat-completions",
831
- modelId,
832
- currency: "USD",
833
- startedAt,
834
- completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
835
- };
836
- const actual = priceOfficialDeepSeekUsage({
837
- ...base,
838
- usage: {
839
- cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
840
- cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
841
- outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
842
- }
843
- });
844
- const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
845
- ...base,
846
- usage: {
847
- cacheReadTokens: 0,
848
- cacheMissTokens: Math.round(snapshot.net.exact),
849
- outputTokens: 0
850
- }
851
- }) : void 0;
852
- const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
853
- if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
854
- return {
855
- currency: "USD",
856
- ...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
857
- ...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
858
- };
859
- }
860
- /**
861
815
  * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
862
816
  * offsets (negative savings — compressed content later re-read in full), and net,
863
817
  * with exact-tokenizer and chars/4 bases reported separately and never merged.
@@ -928,6 +882,132 @@ function registerSavingsRoute(ctx) {
928
882
  });
929
883
  }
930
884
  /**
885
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
886
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
887
+ * pricing) — the payload shape the panel polls;
888
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
889
+ * driving the exact state machine `/ctx-summary` drives.
890
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
891
+ * single guarded registration); the handler branches on `req.method` because
892
+ * the registration surface is method-agnostic.
893
+ */
894
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
895
+ function registerMonitorRoute(ctx) {
896
+ const readService = (name) => {
897
+ try {
898
+ return ctx.get(name);
899
+ } catch {
900
+ return;
901
+ }
902
+ };
903
+ const log = (level, message, ...args) => {
904
+ console[level](message, ...args);
905
+ };
906
+ let registered = false;
907
+ const register = (webServer, channel) => {
908
+ if (registered) return;
909
+ const handler = (req, res) => {
910
+ const resTyped = res;
911
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
912
+ let sessionId;
913
+ try {
914
+ const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
915
+ if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
916
+ } catch {}
917
+ if (String(req?.method ?? "GET").toUpperCase() === "POST") {
918
+ const chunks = [];
919
+ let size = 0;
920
+ let done = false;
921
+ const respond = (status, body) => {
922
+ if (done) return;
923
+ done = true;
924
+ resTyped.writeHead(status, {
925
+ "content-type": "application/json; charset=utf-8",
926
+ "cache-control": "no-cache"
927
+ });
928
+ resTyped.end(JSON.stringify(body));
929
+ };
930
+ const reqTyped = req;
931
+ if (typeof reqTyped?.on !== "function") {
932
+ respond(400, {
933
+ ok: false,
934
+ error: "unreadable request body"
935
+ });
936
+ return;
937
+ }
938
+ reqTyped.on("data", (chunk) => {
939
+ size += chunk?.length ?? 0;
940
+ if (size <= 4096) chunks.push(Buffer.from(chunk ?? /* @__PURE__ */ new Uint8Array()));
941
+ });
942
+ reqTyped.on("end", () => {
943
+ let action;
944
+ try {
945
+ action = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}").action;
946
+ } catch {
947
+ respond(400, {
948
+ ok: false,
949
+ error: "monitor override action must be JSON"
950
+ });
951
+ return;
952
+ }
953
+ if (!isSessionOverrideAction(action)) {
954
+ respond(400, {
955
+ ok: false,
956
+ error: "monitor override action must be \"on\" | \"off\" | \"clear\""
957
+ });
958
+ return;
959
+ }
960
+ const { override } = applySessionOverride(sessionId ?? "", action);
961
+ respond(200, {
962
+ ok: true,
963
+ override: override ?? null,
964
+ sessionScope: sessionId ?? null
965
+ });
966
+ });
967
+ return;
968
+ }
969
+ const snapshot = buildMonitorSnapshot(sessionId);
970
+ const pricing = estimateSavingsPricing(readService, snapshot);
971
+ resTyped.writeHead(200, {
972
+ "content-type": "application/json; charset=utf-8",
973
+ "cache-control": "no-cache"
974
+ });
975
+ resTyped.end(JSON.stringify({
976
+ ok: true,
977
+ ...snapshot,
978
+ ...pricing === void 0 ? {} : { pricing }
979
+ }));
980
+ };
981
+ try {
982
+ const disposers = MONITOR_ROUTES.map((path) => webServer.register({
983
+ kind: "exact",
984
+ path,
985
+ handler
986
+ })).filter((off) => typeof off === "function");
987
+ registered = true;
988
+ ctx.effect(() => () => {
989
+ for (const off of disposers) off();
990
+ }, "contextCompressionSelector.monitor route");
991
+ log("info", "context-compression monitor route registered (%s): %s", channel, MONITOR_ROUTES.join(", "));
992
+ } catch (error) {
993
+ log("warn", "context-compression monitor route registration failed (%s): %o", channel, error);
994
+ }
995
+ };
996
+ const active = asWebServer(readService("webServer"));
997
+ if (active !== void 0) {
998
+ register(active, "direct");
999
+ if (registered) return;
1000
+ }
1001
+ ctx.inject(["webServer"], (injected) => {
1002
+ const webServer = asWebServer(injected.webServer);
1003
+ if (webServer === void 0) {
1004
+ log("warn", "context-compression webServer exposes no register() — monitor route not registered");
1005
+ return;
1006
+ }
1007
+ register(webServer, "inject");
1008
+ });
1009
+ }
1010
+ /**
931
1011
  * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
932
1012
  * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
933
1013
  */
@@ -951,6 +1031,7 @@ function apply(ctx, config = {}) {
951
1031
  try {
952
1032
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
953
1033
  registerSavingsRoute(ctx);
1034
+ registerMonitorRoute(ctx);
954
1035
  if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
955
1036
  registerSummaryCommand(ctx);
956
1037
  if (config.presetOverlay !== true) return;
@@ -983,4 +1064,4 @@ function resolveAutoCompactThresholdPercent(config, presetsCtx) {
983
1064
  }
984
1065
  }
985
1066
  //#endregion
986
- export { Config, apply };
1067
+ export { Config, apply, registerMonitorRoute };
@@ -75,6 +75,10 @@ interface CodeSkeletonSettings {
75
75
  interface IntentSummarySettings {
76
76
  enabled: boolean;
77
77
  }
78
+ /** Floating compression-monitor panel (FAB); visibility switch. */
79
+ interface MonitorPanelSettings {
80
+ enabled: boolean;
81
+ }
78
82
  /** Browser-safe mirror of the runtime presetOptions section. */
79
83
  interface PresetOptionsSettings {
80
84
  readonly dedupeToolResults?: boolean;
@@ -107,6 +111,8 @@ interface ContextCompressionSettings {
107
111
  codeSkeleton: CodeSkeletonSettings;
108
112
  /** Turn-tail intent-summary gate captured independently of `profile`. */
109
113
  intentSummary: IntentSummarySettings;
114
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
115
+ monitorPanel?: MonitorPanelSettings;
110
116
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
111
117
  presetOptions?: PresetOptionsSettings;
112
118
  }
@@ -143,6 +143,10 @@ interface CodeSkeletonSettings {
143
143
  interface IntentSummarySettings {
144
144
  enabled: boolean;
145
145
  }
146
+ /** Floating compression-monitor panel (FAB); visibility switch. */
147
+ interface MonitorPanelSettings {
148
+ enabled: boolean;
149
+ }
146
150
  /**
147
151
  * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
148
152
  * Absent fields inherit the preset defaults; the section is only meaningful
@@ -184,6 +188,8 @@ interface ContextCompressionSettings {
184
188
  codeSkeleton: CodeSkeletonSettings;
185
189
  /** Turn-tail intent-summary gate snapped independently of `profile`. */
186
190
  intentSummary: IntentSummarySettings;
191
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
192
+ monitorPanel?: MonitorPanelSettings;
187
193
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
188
194
  presetOptions?: PresetOptionsSettings;
189
195
  }
@@ -1,4 +1,4 @@
1
- import { A as resolveCustomPolicy, C as isCompressionProfile, D as resolvePolicy, E as resolveConfig, F as decimalRateNanoUnits, I as priceOfficialDeepSeekUsage, L as resolveOfficialDeepSeekPrice, M as deepFreeze, N as COMPRESSION_PROFILES, O as CustomCompressionPolicySchema, P as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, R as getSavingsLedger, S as codePointLength, T as parseContextCompressionSettings, _ as DEFAULTS, b as charsForTokens, c as invalidateOnTaskChange, d as recordRecertified, f as recordScore, g as ContextCompressionSettingsSchema, h as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, i as getAdvisorState, j as assertNever, k as DEFAULT_CUSTOM_COMPRESSION_POLICY, l as observeIntentEnabled, m as AUTO_COMPACT_THRESHOLD_LIMITS, r as evaluateIntentGate, s as getSummaryOverride, u as recordIntentFold, w as isValidAutoCompactThresholdPercent, x as charsToTokens, y as PRUNE_MARKER } from "./intent-gate.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";
@@ -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
- if (!evaluateIntentGate({
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
- }).decision) return;
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) {
@@ -239,6 +239,39 @@ export function IntentSummaryControls({ value, disabled, save, settle, t }: Inte
239
239
  )
240
240
  }
241
241
 
242
+ interface MonitorPanelControlsProps {
243
+ value: boolean
244
+ disabled: boolean
245
+ save: (enabled: boolean) => Promise<void>
246
+ settle: (operation: () => Promise<void>) => void
247
+ t: (key: ContextCompressionLocaleKey) => string
248
+ }
249
+
250
+ /**
251
+ * Visibility switch of the floating compression-monitor panel (FAB). The
252
+ * panel itself is a body-level overlay driven by the monitor route; this card
253
+ * only decides whether it mounts.
254
+ */
255
+ export function MonitorPanelControls({ value, disabled, save, settle, t }: MonitorPanelControlsProps) {
256
+ return (
257
+ <section className={css.autoCompact} aria-labelledby="context-compression-monitorpanel-title">
258
+ <h3 id="context-compression-monitorpanel-title" className={css.autoCompactTitle}>{t('monitorPanel.title')}</h3>
259
+ <p className={css.customNote}>{t('monitorPanel.description')}</p>
260
+ <label className={css.field}>
261
+ <span>{t('monitorPanel.enabled')}</span>
262
+ <select
263
+ value={value ? 'on' : 'off'}
264
+ disabled={disabled}
265
+ onChange={(event) => { settle(() => save(event.currentTarget.value === 'on')) }}
266
+ >
267
+ <option value="on">{t('monitorPanel.enabled.on')}</option>
268
+ <option value="off">{t('monitorPanel.enabled.off')}</option>
269
+ </select>
270
+ </label>
271
+ </section>
272
+ )
273
+ }
274
+
242
275
  export function CodeSkeletonControls({ value, disabled, save, settle, t }: CodeSkeletonControlsProps) {
243
276
  return (
244
277
  <section className={css.autoCompact} aria-labelledby="context-compression-codeskeleton-title">
@@ -30,6 +30,7 @@ export interface CompressionSelectorInjected {
30
30
  saveAutoCompact: (thresholdPercent: number) => Promise<void>
31
31
  saveCodeSkeleton: (enabled: boolean) => Promise<void>
32
32
  saveIntentSummary: (enabled: boolean) => Promise<void>
33
+ saveMonitorPanel: (enabled: boolean) => Promise<void>
33
34
  /** Patch of `presetOptions` members; an explicit `undefined` clears that field. */
34
35
  savePresetOptions: (options: import('./preset-options.ts').PresetOptionsPatch) => Promise<void>
35
36
  }
@@ -6,6 +6,7 @@ import {
6
6
  decodeAutoCompactSettings,
7
7
  decodeCodeSkeletonSettings,
8
8
  decodeIntentSummarySettings,
9
+ decodeMonitorPanelSettings,
9
10
  decodePresetOptionsSettings,
10
11
  isCustomCompressionPolicy,
11
12
  isPlainRecord,
@@ -26,7 +27,7 @@ import {
26
27
  export function decodeSettings(value: unknown): ContextCompressionSettings | undefined {
27
28
  if (!isPlainRecord(value)) return undefined
28
29
  const keys = Object.keys(value)
29
- if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')) {
30
+ if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')) {
30
31
  return undefined
31
32
  }
32
33
  const profile = (value as { profile?: unknown }).profile
@@ -34,6 +35,7 @@ export function decodeSettings(value: unknown): ContextCompressionSettings | und
34
35
  const autoCompact = decodeAutoCompactSettings((value as { autoCompact?: unknown }).autoCompact)
35
36
  const codeSkeleton = decodeCodeSkeletonSettings((value as { codeSkeleton?: unknown }).codeSkeleton)
36
37
  const intentSummary = decodeIntentSummarySettings((value as { intentSummary?: unknown }).intentSummary)
38
+ const monitorPanel = decodeMonitorPanelSettings((value as { monitorPanel?: unknown }).monitorPanel)
37
39
  const presetOptions = decodePresetOptionsSettings((value as { presetOptions?: unknown }).presetOptions)
38
40
  return typeof profile === 'string'
39
41
  && (COMPRESSION_PROFILES as readonly string[]).includes(profile)
@@ -41,12 +43,14 @@ export function decodeSettings(value: unknown): ContextCompressionSettings | und
41
43
  && autoCompact !== undefined
42
44
  && codeSkeleton !== undefined
43
45
  && intentSummary !== undefined
46
+ && monitorPanel !== undefined
44
47
  ? {
45
48
  profile: profile as CompressionProfile,
46
49
  custom: canonicalizeCustomPolicy(custom),
47
50
  autoCompact,
48
51
  codeSkeleton,
49
52
  intentSummary,
53
+ ...monitorPanel === undefined ? {} : { monitorPanel },
50
54
  ...presetOptions === undefined ? {} : { presetOptions },
51
55
  }
52
56
  : undefined
@@ -10,6 +10,7 @@ import {
10
10
  } from './CompressionProfileSelector.tsx'
11
11
  import { DEFAULT_CUSTOM_COMPRESSION_POLICY } from '../profiles.ts'
12
12
  import { decodeSettings } from './decode.ts'
13
+ import { initMonitorFab } from './monitor-fab.ts'
13
14
  import { en, zh } from './locales.ts'
14
15
  import { de } from './locales/de.ts'
15
16
  import { es } from './locales/es.ts'
@@ -107,6 +108,42 @@ export function apply(ctx: ClientContext): void {
107
108
  // binder, so locale switches are still followed.
108
109
  const localeSvc = ctx.locale as { bind?: (n: string) => (key: string) => string } | undefined
109
110
  const tNav = localeSvc?.bind?.(NS) ?? ((key: string) => key)
111
+
112
+ // 浮动监控面板(FAB): body 级幂等单例。enabled 读取走设置文档——表单句柄的
113
+ // 激活规则与旧 bind 相同,故 apply 侧 try/catch 兜底,注入工厂内再刷新读取闭包。
114
+ let readMonitorPanelEnabled = (): boolean => {
115
+ try {
116
+ const form = ctx.configForms.get<Record<string, unknown>>(ENTRY_ID)
117
+ return decodeSettings(form.getSnapshot().value?.settings)?.monitorPanel?.enabled ?? false
118
+ } catch {
119
+ return false
120
+ }
121
+ }
122
+ // 浮动面板会话绑定:跟随输入栏座位的 inject 回调(裸 sessionId,pm longtask 同款)。
123
+ let latestSessionId: string | undefined
124
+ try {
125
+ initMonitorFab({
126
+ t: tNav,
127
+ sessionIdOf: () => latestSessionId,
128
+ enabledOf: () => readMonitorPanelEnabled(),
129
+ fetchSnapshot: async (sessionId) => {
130
+ const query = sessionId === undefined ? '' : `?sessionId=${encodeURIComponent(sessionId)}`
131
+ const response = await fetch(`/api/dsh-context-compression-improved/monitor${query}`, { headers: { 'cache-control': 'no-cache' } })
132
+ if (!response.ok) throw new Error(`monitor snapshot ${response.status}`)
133
+ return await response.json() as Parameters<typeof initMonitorFab>[0]['fetchSnapshot'] extends (...args: never[]) => Promise<infer T> ? T : never
134
+ },
135
+ applyOverride: async (sessionId, action) => {
136
+ const query = sessionId === undefined ? '' : `?sessionId=${encodeURIComponent(sessionId)}`
137
+ await fetch(`/api/dsh-context-compression-improved/monitor${query}`, {
138
+ method: 'POST',
139
+ headers: { 'content-type': 'application/json' },
140
+ body: JSON.stringify({ action }),
141
+ })
142
+ },
143
+ })
144
+ } catch (error) {
145
+ console.warn('[dsh-context-compression-improved] 监控浮动球挂载失败(不影响设置分节):', error)
146
+ }
110
147
  const injected = (): CompressionSelectorInjected => {
111
148
  // 0.1.7: the compression document rides the selector row's entry config as
112
149
  // the volatile `settings` field. The form handle is fetched per factory
@@ -116,6 +153,8 @@ export function apply(ctx: ClientContext): void {
116
153
  const form = ctx.configForms.get<Record<string, unknown>>(ENTRY_ID)
117
154
  const readDoc = (): ContextCompressionSettings | undefined =>
118
155
  decodeSettings(form.getSnapshot().value?.settings)
156
+ readMonitorPanelEnabled = (): boolean =>
157
+ decodeSettings(form.getSnapshot().value?.settings)?.monitorPanel?.enabled ?? false
119
158
  // useSyncExternalStore requires a getSnapshot that returns a STABLE
120
159
  // reference between changes — a fresh object per call is React error #185
121
160
  // (maximum update depth exceeded). Cache the projection keyed on the form
@@ -211,6 +250,10 @@ export function apply(ctx: ClientContext): void {
211
250
  () => scope.set('intentSummary', { enabled }),
212
251
  settings => settings.intentSummary.enabled === enabled,
213
252
  ),
253
+ saveMonitorPanel: enabled => writeAndConfirm(
254
+ () => scope.set('monitorPanel', { enabled }),
255
+ settings => settings.monitorPanel?.enabled === enabled,
256
+ ),
214
257
  savePresetOptions: options => {
215
258
  // Path-addressed so one field write cannot delete its siblings: the
216
259
  // previous whole-section set erased estimatorMode (and every other
@@ -240,6 +283,23 @@ export function apply(ctx: ClientContext): void {
240
283
  } catch (error) {
241
284
  console.warn('[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):', error)
242
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
+ }
243
303
  }
244
304
 
245
305
  export type {
@@ -69,6 +69,28 @@ export const de = {
69
69
  'intentSummary.enabled': 'Abschluss-Zusammenfassung',
70
70
  'intentSummary.enabled.on': 'Ein',
71
71
  'intentSummary.enabled.off': 'Aus (Standard)',
72
+ 'monitor.fab.title': 'Komprimierungs-Monitor',
73
+ 'monitor.panel.title': 'Komprimierungs-Monitor',
74
+ 'monitor.panel.net': 'Nettoeinsparung',
75
+ 'monitor.panel.gross': 'Bruttoeinsparung',
76
+ 'monitor.panel.offsets': 'Ausgleiche',
77
+ 'monitor.panel.context': 'Kontextbelegung',
78
+ 'monitor.panel.cacheHit': 'Cache-Trefferquote',
79
+ 'monitor.panel.cost': 'Kosten (ist / gespart gesch.)',
80
+ 'monitor.panel.intent': 'Intent-Zusammenfassung',
81
+ 'monitor.panel.overrideHint': 'Sitzungs-Übersteuerung',
82
+ 'monitor.panel.resume': 'Fortsetzen',
83
+ 'monitor.panel.disable': 'Deaktivieren',
84
+ 'monitor.panel.stateOn': 'ein',
85
+ 'monitor.panel.stateOff': 'aus',
86
+ 'monitor.panel.gateUnknown': 'noch nicht bewertet',
87
+ 'monitor.panel.lastFold': 'Letzte Faltung',
88
+ 'monitor.panel.stale': 'Snapshot nicht erreichbar — letzte Daten',
89
+ 'monitorPanel.title': 'Komprimierungs-Monitorpanel',
90
+ 'monitorPanel.description': 'Aktiviert erscheint neben dem Eingabebereich eine ziehbare Schwebekugel — öffne sie, um den Live-Komprimierungszustand zu beobachten: Nettoeinsparung (exakte Basis), Cache-Trefferquote, Kostenschätzung, das Turn-Tail-Gate und letzte Ausgleiche. Das Panel kann den Intent-Zusammenfassungsschalter der aktuellen Sitzung temporär übersteuern. Das Konto ist prozesslokal (Reset bei Host-Neustart).',
91
+ 'monitorPanel.enabled': 'Monitorpanel',
92
+ 'monitorPanel.enabled.on': 'Ein',
93
+ 'monitorPanel.enabled.off': 'Aus (Standard)',
72
94
  'custom.title': 'Eigene Strategie',
73
95
  'custom.settingsHint': 'Detaillierte Parameter unter Einstellungen > Kontextkomprimierung wählen bearbeiten.',
74
96
  'custom.sessionScope': 'Gespeicherte Änderungen greifen, wenn die aktuelle Compression-Runtime eine Sitzung zum ersten Mal beobachtet. Eine von dieser Runtime bereits beobachtete Sitzung behält ihre eingefrorene Strategie.',
@@ -69,6 +69,28 @@ export const es = {
69
69
  'intentSummary.enabled': 'Resumen de intención al cierre',
70
70
  'intentSummary.enabled.on': 'Sí',
71
71
  'intentSummary.enabled.off': 'No (predeterminado)',
72
+ 'monitor.fab.title': 'Monitor de compresión',
73
+ 'monitor.panel.title': 'Monitor de compresión',
74
+ 'monitor.panel.net': 'Ahorro neto',
75
+ 'monitor.panel.gross': 'Ahorro bruto',
76
+ 'monitor.panel.offsets': 'Compensaciones',
77
+ 'monitor.panel.context': 'Ocupación del contexto',
78
+ 'monitor.panel.cacheHit': 'Tasa de acierto de caché',
79
+ 'monitor.panel.cost': 'Coste (real / ahorro est.)',
80
+ 'monitor.panel.intent': 'Resumen de intención',
81
+ 'monitor.panel.overrideHint': 'Invalidación de sesión',
82
+ 'monitor.panel.resume': 'Reanudar',
83
+ 'monitor.panel.disable': 'Desactivar',
84
+ 'monitor.panel.stateOn': 'sí',
85
+ 'monitor.panel.stateOff': 'no',
86
+ 'monitor.panel.gateUnknown': 'aún sin evaluar',
87
+ 'monitor.panel.lastFold': 'Último plegado',
88
+ 'monitor.panel.stale': 'Instantánea inalcanzable — se muestran los últimos datos',
89
+ 'monitorPanel.title': 'Panel de monitor de compresión',
90
+ 'monitorPanel.description': 'Al activarlo, junto al área de entrada aparece una burbuja flotante arrastrable — ábrela para observar el estado de compresión en vivo: ahorro neto (base exacta), tasa de acierto de caché, estimación de coste, la puerta de resumen de intención del turno y compensaciones recientes. El panel puede invalidar temporalmente el interruptor de resumen de intención de la sesión actual. El libro es por proceso (se reinicia al rearrancar el host).',
91
+ 'monitorPanel.enabled': 'Panel de monitor',
92
+ 'monitorPanel.enabled.on': 'Sí',
93
+ 'monitorPanel.enabled.off': 'No (predeterminado)',
72
94
  'custom.title': 'Política personalizada',
73
95
  'custom.settingsHint': 'Edita los parámetros detallados en Ajustes > Selector de compresión de contexto.',
74
96
  'custom.sessionScope': 'Los cambios guardados se aplican cuando el runtime de compresión actual observa una Session por primera vez. Una Session ya observada por ese runtime conserva su política congelada.',
@@ -69,6 +69,28 @@ export const fr = {
69
69
  'intentSummary.enabled': 'Résumé d\'intention en fin de tour',
70
70
  'intentSummary.enabled.on': 'Activé',
71
71
  'intentSummary.enabled.off': 'Désactivé (par défaut)',
72
+ 'monitor.fab.title': 'Monitor de compression',
73
+ 'monitor.panel.title': 'Monitor de compression',
74
+ 'monitor.panel.net': 'Économie nette',
75
+ 'monitor.panel.gross': 'Économie brute',
76
+ 'monitor.panel.offsets': 'Compensations',
77
+ 'monitor.panel.context': 'Occupation du contexte',
78
+ 'monitor.panel.cacheHit': 'Taux de réussite du cache',
79
+ 'monitor.panel.cost': 'Coût (réel / écon. est.)',
80
+ 'monitor.panel.intent': 'Résumé d\'intention',
81
+ 'monitor.panel.overrideHint': 'Priorité de session',
82
+ 'monitor.panel.resume': 'Reprendre',
83
+ 'monitor.panel.disable': 'Désactiver',
84
+ 'monitor.panel.stateOn': 'activé',
85
+ 'monitor.panel.stateOff': 'désactivé',
86
+ 'monitor.panel.gateUnknown': 'pas encore évalué',
87
+ 'monitor.panel.lastFold': 'Dernier pliage',
88
+ 'monitor.panel.stale': 'Instantané injoignable — dernières données',
89
+ 'monitorPanel.title': 'Panneau de monitorage de compression',
90
+ 'monitorPanel.description': 'Activé, une bulle flottante déplaçable apparaît près de la zone de saisie — ouvrez-la pour observer l\'état de compression en direct : économie nette (base exacte), taux de réussite du cache, estimation de coût, la porte de résumé d\'intention du tour et les compensations récentes. Le panneau peut contourner temporairement l\'interrupteur de résumé d\'intention de la session courante. Le registre est propre au processus (remis à zéro au redémarrage de l\'hôte).',
91
+ 'monitorPanel.enabled': 'Panneau de monitorage',
92
+ 'monitorPanel.enabled.on': 'Activé',
93
+ 'monitorPanel.enabled.off': 'Désactivé (par défaut)',
72
94
  'custom.title': 'Stratégie personnalisée',
73
95
  'custom.settingsHint': 'Modifiez les paramètres détaillés dans Réglages > Sélecteur de compression du contexte.',
74
96
  'custom.sessionScope': 'Les changements enregistrés s’appliquent quand le runtime de compression actuel observe une Session pour la première fois. Une Session déjà observée par ce runtime garde sa stratégie figée.',
@@ -69,6 +69,28 @@ export const it = {
69
69
  'intentSummary.enabled': 'Riepilogo di intento a fine turno',
70
70
  'intentSummary.enabled.on': 'On',
71
71
  'intentSummary.enabled.off': 'Off (predefinito)',
72
+ 'monitor.fab.title': 'Monitor compressione',
73
+ 'monitor.panel.title': 'Monitor compressione',
74
+ 'monitor.panel.net': 'Risparmio netto',
75
+ 'monitor.panel.gross': 'Risparmio lordo',
76
+ 'monitor.panel.offsets': 'Compensazioni',
77
+ 'monitor.panel.context': 'Occupazione del contesto',
78
+ 'monitor.panel.cacheHit': 'Tasso di hit della cache',
79
+ 'monitor.panel.cost': 'Costo (effettivo / stimo)',
80
+ 'monitor.panel.intent': 'Riepilogo di intento',
81
+ 'monitor.panel.overrideHint': 'Override di sessione',
82
+ 'monitor.panel.resume': 'Riprendi',
83
+ 'monitor.panel.disable': 'Disattiva',
84
+ 'monitor.panel.stateOn': 'on',
85
+ 'monitor.panel.stateOff': 'off',
86
+ 'monitor.panel.gateUnknown': 'non ancora valutato',
87
+ 'monitor.panel.lastFold': 'Ultima piegatura',
88
+ 'monitor.panel.stale': 'Snapshot non raggiungibile — ultimi dati',
89
+ 'monitorPanel.title': 'Pannello di monitoraggio compressione',
90
+ 'monitorPanel.description': 'Quando attivo, accanto all\'area di input appare una bolla flottante trascinabile — aprila per osservare lo stato di compressione in tempo reale: risparmio netto (base esatta), tasso di hit della cache, stima dei costi, la soglia del riepilogo di intento del turno e le compensazioni recenti. Il pannello può ignorare temporaneamente l\'interruttore del riepilogo di intento della sessione corrente. Il registro è per processo (azzerato al riavvio dell\'host).',
91
+ 'monitorPanel.enabled': 'Pannello di monitoraggio',
92
+ 'monitorPanel.enabled.on': 'On',
93
+ 'monitorPanel.enabled.off': 'Off (predefinito)',
72
94
  'custom.title': 'Politica personalizzata',
73
95
  'custom.settingsHint': 'Modifica i parametri dettagliati in Impostazioni > Selettore di compressione del contesto.',
74
96
  'custom.sessionScope': 'Le modifiche salvate si applicano quando l’attuale runtime di compressione osserva una Sessione per la prima volta. Una Sessione già osservata da quel runtime mantiene la sua politica congelata.',
@@ -69,6 +69,28 @@ export const ja = {
69
69
  'intentSummary.enabled': 'ターン末尾インテント要約',
70
70
  'intentSummary.enabled.on': 'オン',
71
71
  'intentSummary.enabled.off': 'オフ(既定)',
72
+ 'monitor.fab.title': '圧縮モニター',
73
+ 'monitor.panel.title': '圧縮モニター',
74
+ 'monitor.panel.net': '正味節約',
75
+ 'monitor.panel.gross': '総節約',
76
+ 'monitor.panel.offsets': '相殺',
77
+ 'monitor.panel.context': 'コンテキスト占有',
78
+ 'monitor.panel.cacheHit': 'キャッシュ ヒット率',
79
+ 'monitor.panel.cost': 'コスト(実績 / 節約概算)',
80
+ 'monitor.panel.intent': 'インテント要約',
81
+ 'monitor.panel.overrideHint': 'セッション上書き',
82
+ 'monitor.panel.resume': '再開',
83
+ 'monitor.panel.disable': '停止',
84
+ 'monitor.panel.stateOn': 'オン',
85
+ 'monitor.panel.stateOff': 'オフ',
86
+ 'monitor.panel.gateUnknown': '未評価',
87
+ 'monitor.panel.lastFold': '最後の折り畳み',
88
+ 'monitor.panel.stale': 'スナップショット到達不能——前回データを表示',
89
+ 'monitorPanel.title': '圧縮モニター パネル',
90
+ 'monitorPanel.description': '有効にすると、入力欄のそばにドラッグできるフローティング バブルが現れます。開くとライブの圧縮状態を監視できます。正味節約(正確 basis)、キャッシュ ヒット率、コスト概算、ターン末尾インテント要約ゲート、最近の相殺。パネルから現セッションのインテント要約スイッチを一時的に上書きできます。台帳はプロセス単位(ホスト再起動でリセット)。',
91
+ 'monitorPanel.enabled': 'モニター パネル',
92
+ 'monitorPanel.enabled.on': 'オン',
93
+ 'monitorPanel.enabled.off': 'オフ(既定)',
72
94
  'custom.title': 'カスタムポリシー',
73
95
  'custom.settingsHint': '詳細パラメーターは「設定 > コンテキスト圧縮セレクター」で編集してください。',
74
96
  'custom.sessionScope': '保存した変更は、現在の圧縮ランタイムが次に Session を初めて観測したときに適用されます。そのランタイムに既に観測された Session は凍結済みポリシーを使い続けます。',