dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.3

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.
@@ -285,7 +285,7 @@ window.__ModuleLoader__.load({
285
285
  }
286
286
  //#endregion
287
287
  //#region \0dsh-context-compression-css:466eb745356d-CompressionProfileSelector.module.css.mjs
288
- const css = ".rLocJG_settingsSection{max-width:720px;color:var(--dsw-alias-label-primary);flex-direction:column;gap:12px;display:flex}.rLocJG_settingsTitle{color:var(--dsw-alias-label-primary);margin:0;font-size:16px;font-weight:500;line-height:24px}.rLocJG_settingsDescription{color:var(--dsw-alias-label-tertiary);margin:0;font-size:14px;line-height:22px}.rLocJG_root{width:100%}.rLocJG_profileGrid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;display:grid}.rLocJG_profileCard{border:1px solid var(--dsw-alias-border-l2);min-height:112px;color:var(--dsw-alias-label-primary);cursor:pointer;text-align:left;background:0 0;border-radius:10px;flex-direction:column;gap:8px;padding:14px;display:flex}.rLocJG_profileCard:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.rLocJG_profileCard[aria-pressed=true]{border-color:var(--dsw-alias-label-primary)}.rLocJG_profileCard:active:not(:disabled){transform:scale(.99)}.rLocJG_profileCard:disabled{cursor:default;opacity:.6}.rLocJG_profileCard:focus-visible{outline-offset:2px;outline:2px solid}.rLocJG_profileCardTop{align-items:center;gap:8px;display:flex}.rLocJG_profileCardTitle{font-size:14px;font-weight:500;line-height:20px}.rLocJG_profileCurrent{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-base);border-radius:999px;padding:1px 6px;font-size:10px;line-height:14px}.rLocJG_profileCardDetail{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}.rLocJG_button{border:1px solid var(--dsw-alias-border-l2);width:100%;min-height:34px;color:var(--dsw-alias-label-primary);cursor:pointer;text-align:left;background:0 0;border-radius:10px;align-items:center;gap:8px;padding:6px 8px;display:flex}.rLocJG_button:hover{background:var(--dsw-alias-interactive-bg-hover)}.rLocJG_button:disabled{cursor:default;opacity:.6}.rLocJG_copy{flex:1;min-width:0}.rLocJG_label{color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:14px}.rLocJG_value{text-overflow:ellipsis;white-space:nowrap;font-size:13px;line-height:17px;overflow:hidden}.rLocJG_chevron{color:var(--dsw-alias-label-secondary);flex:none}.rLocJG_menuCopy{flex-direction:column;gap:2px;min-width:220px;display:flex}.rLocJG_menuTitle{font-size:13px;line-height:17px}.rLocJG_menuDetail{white-space:normal;max-width:290px;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:15px}.rLocJG_error{color:var(--dsw-alias-state-error-primary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_unavailable{color:var(--dsw-alias-label-tertiary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_settingsHint{color:var(--dsw-alias-label-secondary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_pricing{color:var(--dsw-alias-label-tertiary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_custom{border-top:1px solid var(--dsw-alias-border-l2);margin-top:16px;padding:16px 0 0}.rLocJG_customTitle{margin:0 0 6px;font-size:13px;line-height:17px}.rLocJG_customNote{color:var(--dsw-alias-label-tertiary);margin:4px 0;font-size:11px;line-height:15px}.rLocJG_stage{border:0;border-top:1px solid var(--dsw-alias-border-l2);margin:12px 0 0;padding:12px 0 0}.rLocJG_stageToggle{align-items:center;gap:6px;font-size:12px;line-height:16px;display:inline-flex}.rLocJG_fieldGrid{grid-template-columns:1fr;gap:8px;display:grid}.rLocJG_field{min-width:0;color:var(--dsw-alias-label-secondary);flex-direction:column;gap:4px;margin-top:8px;font-size:11px;line-height:15px;display:flex}.rLocJG_field input,.rLocJG_field select{box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);width:100%;min-width:0;min-height:30px;color:var(--dsw-alias-label-primary);border-radius:7px;padding:4px 6px}.rLocJG_field input:focus-visible,.rLocJG_field select:focus-visible,.rLocJG_actions button:focus-visible{outline-offset:2px;outline:2px solid}.rLocJG_actions{flex-wrap:wrap;gap:8px;margin-top:10px;display:flex}.rLocJG_actions button{border:1px solid var(--dsw-alias-border-l2);min-height:30px;color:var(--dsw-alias-label-primary);background:0 0;border-radius:7px;padding:4px 8px}.rLocJG_actions button:active:not(:disabled){transform:scale(.98)}.rLocJG_actions button:disabled{opacity:.6}@media (width<=560px){.rLocJG_profileGrid{grid-template-columns:1fr}}.rLocJG_autoCompact{border:1px solid #80808059;border-radius:8px;margin-top:24px;padding:16px}.rLocJG_autoCompactTitle{margin:0 0 8px;font-size:15px;font-weight:600}.rLocJG_autoCompactRisk{opacity:.9;margin:8px 0 0;font-size:12px}";
288
+ const css = ".rLocJG_settingsSection{max-width:720px;color:var(--dsw-alias-label-primary);flex-direction:column;gap:12px;display:flex}.rLocJG_settingsTitle{color:var(--dsw-alias-label-primary);margin:0;font-size:16px;font-weight:500;line-height:24px}.rLocJG_settingsDescription{color:var(--dsw-alias-label-tertiary);margin:0;font-size:14px;line-height:22px}.rLocJG_root{width:100%}.rLocJG_profileGrid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;display:grid}.rLocJG_profileCard{border:1px solid var(--dsw-alias-border-l2);min-height:112px;color:var(--dsw-alias-label-primary);cursor:pointer;text-align:left;background:0 0;border-radius:10px;flex-direction:column;gap:8px;padding:14px;display:flex}.rLocJG_profileCard:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.rLocJG_profileCard[aria-pressed=true]{border-color:var(--dsw-alias-label-primary)}.rLocJG_profileCard:active:not(:disabled){transform:scale(.99)}.rLocJG_profileCard:disabled{cursor:default;opacity:.6}.rLocJG_profileCard:focus-visible{outline-offset:2px;outline:2px solid}.rLocJG_profileCardTop{align-items:center;gap:8px;display:flex}.rLocJG_profileCardTitle{font-size:14px;font-weight:500;line-height:20px}.rLocJG_profileCurrent{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-base);border-radius:999px;padding:1px 6px;font-size:10px;line-height:14px}.rLocJG_profileCardDetail{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}.rLocJG_button{border:1px solid var(--dsw-alias-border-l2);width:100%;min-height:34px;color:var(--dsw-alias-label-primary);cursor:pointer;text-align:left;background:0 0;border-radius:10px;align-items:center;gap:8px;padding:6px 8px;display:flex}.rLocJG_button:hover{background:var(--dsw-alias-interactive-bg-hover)}.rLocJG_button:disabled{cursor:default;opacity:.6}.rLocJG_copy{flex:1;min-width:0}.rLocJG_label{color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:14px}.rLocJG_value{text-overflow:ellipsis;white-space:nowrap;font-size:13px;line-height:17px;overflow:hidden}.rLocJG_chevron{color:var(--dsw-alias-label-secondary);flex:none}.rLocJG_menuCopy{flex-direction:column;gap:2px;min-width:220px;display:flex}.rLocJG_menuTitle{font-size:13px;line-height:17px}.rLocJG_menuDetail{white-space:normal;max-width:290px;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:15px}.rLocJG_error{color:var(--dsw-alias-state-error-primary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_unavailable{color:var(--dsw-alias-label-tertiary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_settingsHint{color:var(--dsw-alias-label-secondary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_pricing{color:var(--dsw-alias-label-tertiary);padding:4px 8px 0;font-size:11px;line-height:15px}.rLocJG_custom{border-top:1px solid var(--dsw-alias-border-l2);margin-top:16px;padding:16px 0 0}.rLocJG_customTitle{margin:0 0 6px;font-size:13px;line-height:17px}.rLocJG_customNote{color:var(--dsw-alias-label-tertiary);margin:4px 0;font-size:11px;line-height:15px}.rLocJG_stage{border:0;border-top:1px solid var(--dsw-alias-border-l2);margin:12px 0 0;padding:12px 0 0}.rLocJG_stageToggle{align-items:center;gap:6px;font-size:12px;line-height:16px;display:inline-flex}.rLocJG_fieldGrid{grid-template-columns:1fr;gap:8px;display:grid}.rLocJG_field{min-width:0;color:var(--dsw-alias-label-secondary);flex-direction:column;gap:4px;margin-top:8px;font-size:11px;line-height:15px;display:flex}.rLocJG_field input,.rLocJG_field select{box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);width:100%;min-width:0;min-height:30px;color:var(--dsw-alias-label-primary);border-radius:7px;padding:4px 6px}.rLocJG_field input:focus-visible,.rLocJG_field select:focus-visible,.rLocJG_actions button:focus-visible{outline-offset:2px;outline:2px solid}.rLocJG_actions{flex-wrap:wrap;gap:8px;margin-top:10px;display:flex}.rLocJG_actions button{border:1px solid var(--dsw-alias-border-l2);min-height:30px;color:var(--dsw-alias-label-primary);background:0 0;border-radius:7px;padding:4px 8px}.rLocJG_actions button:active:not(:disabled){transform:scale(.98)}.rLocJG_actions button:disabled{opacity:.6}@media (width<=560px){.rLocJG_profileGrid{grid-template-columns:1fr}}.rLocJG_autoCompact{border:1px solid #80808059;border-radius:8px;margin-top:24px;padding:16px}.rLocJG_autoCompactTitle{margin:0 0 8px;font-size:15px;font-weight:600}.rLocJG_autoCompactRisk{opacity:.9;margin:8px 0 0;font-size:12px}.rLocJG_savingsCard{border:1px solid #ffffff1a;border-radius:8px;flex-direction:column;gap:4px;margin-top:14px;padding:10px 12px;display:flex}.rLocJG_savingsRow{justify-content:space-between;align-items:baseline;gap:12px;display:flex}.rLocJG_savingsNetPositive strong{color:#30d158}.rLocJG_savingsNetNegative strong{color:#ff9f0a}.rLocJG_savingsMuted{opacity:.66;font-size:.92em}.rLocJG_savingsBreakdown{border-top:1px solid #ffffff14;margin-top:4px;padding-top:4px}.rLocJG_savingsNote{opacity:.5;margin-top:4px;font-size:.85em}";
289
289
  const tagId = "dsh-context-compression-improved/CompressionProfileSelector.module.css";
290
290
  if (typeof document !== "undefined" && document.querySelector(`style[data-plugin-css="${tagId}"]`) === null) {
291
291
  const tag = document.createElement("style");
@@ -320,6 +320,13 @@ window.__ModuleLoader__.load({
320
320
  "profileCurrent": "rLocJG_profileCurrent",
321
321
  "profileGrid": "rLocJG_profileGrid",
322
322
  "root": "rLocJG_root",
323
+ "savingsBreakdown": "rLocJG_savingsBreakdown",
324
+ "savingsCard": "rLocJG_savingsCard",
325
+ "savingsMuted": "rLocJG_savingsMuted",
326
+ "savingsNetNegative": "rLocJG_savingsNetNegative",
327
+ "savingsNetPositive": "rLocJG_savingsNetPositive",
328
+ "savingsNote": "rLocJG_savingsNote",
329
+ "savingsRow": "rLocJG_savingsRow",
323
330
  "settingsDescription": "rLocJG_settingsDescription",
324
331
  "settingsHint": "rLocJG_settingsHint",
325
332
  "settingsSection": "rLocJG_settingsSection",
@@ -1024,6 +1031,189 @@ window.__ModuleLoader__.load({
1024
1031
  });
1025
1032
  }
1026
1033
  //#endregion
1034
+ //#region src/client/savings-card.tsx
1035
+ /**
1036
+ * 节省统计卡片(设置分节内,只读):净/毛/抵消 + 分项条。
1037
+ * 数据源 = `/api/.../savings` 只读快照路由(忙 2s / 闲 5s 自调度轮询,
1038
+ * 失败静默——统计卡片永不打扰设置页主功能)。
1039
+ *
1040
+ * @module dsh-context-compression-improved/client/savings-card
1041
+ */
1042
+ const SAVINGS_ROUTE = "/api/dsh-context-compression-improved/savings";
1043
+ function fmt(n) {
1044
+ return n.toLocaleString("en-US");
1045
+ }
1046
+ /** 节省统计卡片:口径分列(精确 tokenizer vs chars/4 估算),永不混算。 */
1047
+ function SavingsCard({ t }) {
1048
+ const [snap, setSnap] = (0, react.useState)(null);
1049
+ const stopped = (0, react.useRef)(false);
1050
+ (0, react.useEffect)(() => {
1051
+ stopped.current = false;
1052
+ const tick = async () => {
1053
+ try {
1054
+ const response = await fetch(SAVINGS_ROUTE, { headers: { "cache-control": "no-cache" } });
1055
+ if (response.ok) {
1056
+ const data = await response.json();
1057
+ if (data?.startedAt !== void 0 && !stopped.current) setSnap(data);
1058
+ }
1059
+ } catch {}
1060
+ if (!stopped.current) setTimeout(tick, 5e3);
1061
+ };
1062
+ tick();
1063
+ return () => {
1064
+ stopped.current = true;
1065
+ };
1066
+ }, []);
1067
+ if (snap === null || snap.gross.exact + snap.gross.estimated === 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1068
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.pricing,
1069
+ children: t("savings.empty")
1070
+ });
1071
+ const hasExact = snap.gross.exact > 0 || snap.offsets.exact > 0;
1072
+ const hasEstimated = snap.gross.estimated > 0 || snap.offsets.estimated > 0;
1073
+ const netTone = snap.net.exact + snap.net.estimated >= 0 ? _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsNetPositive : _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsNetNegative;
1074
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1075
+ className: `${_dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsCard}`,
1076
+ "data-testid": "savings-card",
1077
+ children: [
1078
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1079
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1080
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("savings.title") })
1081
+ }),
1082
+ hasExact ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1083
+ className: `${_dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow} ${netTone}`,
1084
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("savings.netExact") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: fmt(snap.net.exact) })]
1085
+ }) : null,
1086
+ hasEstimated ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1087
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1088
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("savings.netEstimated") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: fmt(snap.net.estimated) })]
1089
+ }) : null,
1090
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1091
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1092
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1093
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1094
+ children: t("savings.gross")
1095
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1096
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1097
+ children: [
1098
+ hasExact ? `✓ ${fmt(snap.gross.exact)}` : "",
1099
+ hasExact && hasEstimated ? " · " : "",
1100
+ hasEstimated ? `≈ ${fmt(snap.gross.estimated)}` : ""
1101
+ ]
1102
+ })]
1103
+ }),
1104
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1105
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1106
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1107
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1108
+ children: t("savings.offsets")
1109
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1110
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1111
+ children: [
1112
+ hasExact ? `−${fmt(snap.offsets.exact)}` : "",
1113
+ hasExact && hasEstimated ? " · " : "",
1114
+ hasEstimated ? `−${fmt(snap.offsets.estimated)}` : ""
1115
+ ]
1116
+ })]
1117
+ }),
1118
+ snap.usage !== void 0 && snap.usage.requests > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
1119
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1120
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1121
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1122
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1123
+ children: t("savings.requests")
1124
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1125
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1126
+ children: fmt(snap.usage.requests)
1127
+ })]
1128
+ }),
1129
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1130
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1131
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1132
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1133
+ children: t("savings.cacheHit")
1134
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1135
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1136
+ children: snap.usage.cacheHitRate === null ? "–" : `${Math.round(snap.usage.cacheHitRate * 100)}%`
1137
+ })]
1138
+ }),
1139
+ snap.pricing?.actualCost !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1140
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1141
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1142
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1143
+ children: t("savings.actualCost")
1144
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1145
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1146
+ children: [
1147
+ snap.pricing.currency,
1148
+ " ",
1149
+ snap.pricing.actualCost
1150
+ ]
1151
+ })]
1152
+ }) : null,
1153
+ snap.pricing?.estimatedSavedCost !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1154
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1155
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1156
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1157
+ children: t("savings.savedMoney")
1158
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1159
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1160
+ children: [
1161
+ snap.pricing.currency,
1162
+ " ",
1163
+ snap.pricing.estimatedSavedCost
1164
+ ]
1165
+ })]
1166
+ }) : null
1167
+ ] }) : null,
1168
+ snap.perSession !== void 0 && snap.perSession.length > 1 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1169
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsBreakdown,
1170
+ children: snap.perSession.slice(0, 5).map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1171
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1172
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1173
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1174
+ children: [
1175
+ t("savings.perSession"),
1176
+ " · ",
1177
+ row.sessionId.slice(0, 8),
1178
+ "…",
1179
+ row.requests > 0 ? ` · ${t("savings.cacheHit")} ${row.cacheHitRate === null ? "–" : `${Math.round(row.cacheHitRate * 100)}%`}` : ""
1180
+ ]
1181
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1182
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1183
+ children: fmt(row.net.exact)
1184
+ })]
1185
+ }, row.sessionId))
1186
+ }) : null,
1187
+ snap.perComponent.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1188
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsBreakdown,
1189
+ children: snap.perComponent.slice(0, 6).map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1190
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsRow,
1191
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1192
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1193
+ children: [
1194
+ row.kind === "offset" ? "−" : "+",
1195
+ " ",
1196
+ row.component,
1197
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("small", { children: [
1198
+ " (",
1199
+ row.basis === "exact-tokenizer" ? t("savings.basisExact") : t("savings.basisEstimated"),
1200
+ ")"
1201
+ ] })
1202
+ ]
1203
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1204
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsMuted,
1205
+ children: fmt(row.tokens)
1206
+ })]
1207
+ }, `${row.kind}:${row.component}:${row.basis}`))
1208
+ }) : null,
1209
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1210
+ className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.savingsNote,
1211
+ children: t("savings.basisNote")
1212
+ })
1213
+ ]
1214
+ });
1215
+ }
1216
+ //#endregion
1027
1217
  //#region src/client/settings-section.tsx
1028
1218
  /**
1029
1219
  * Full-page Settings surface backed by the same durable selector state.
@@ -1133,6 +1323,7 @@ window.__ModuleLoader__.load({
1133
1323
  settle,
1134
1324
  t
1135
1325
  }),
1326
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SavingsCard, { t }),
1136
1327
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1137
1328
  className: _dsh_context_compression_css_466eb745356d_CompressionProfileSelector_module_css_default.pricing,
1138
1329
  children: t("pricing.disclosure")
@@ -1279,7 +1470,21 @@ window.__ModuleLoader__.load({
1279
1470
  "custom.tailTrim.warning": "TailTrim 只在精确 tokenizer 可用时,把一个完整、已结束且非错误的纯工具组替换为可恢复引用;它与 History 共用近期工具调用数、工具结果尾窗和最小回收参数。它会改写已发送前缀,可能降低缓存命中。",
1280
1471
  "custom.save": "保存 Custom 策略",
1281
1472
  "custom.reset": "重置 Custom 策略",
1282
- "custom.invalid": "Custom 策略参数无效。"
1473
+ "custom.invalid": "Custom 策略参数无效。",
1474
+ "savings.title": "节省统计(本进程)",
1475
+ "savings.netExact": "净节省(精确口径)",
1476
+ "savings.netEstimated": "净节省(估算口径)",
1477
+ "savings.gross": "毛节省(压缩落盘时)",
1478
+ "savings.offsets": "负节省(压缩后再读全文的抵消)",
1479
+ "savings.empty": "尚无压缩记录——发生首次裁剪后这里会显示净节省。",
1480
+ "savings.basisExact": "精确",
1481
+ "savings.basisEstimated": "估算",
1482
+ "savings.basisNote": "口径分列不混算:精确 = DeepSeek tokenizer;估算 = chars/4。先取骨架后取全文会计负节省(净额可能为负)。",
1483
+ "savings.requests": "请求轮次",
1484
+ "savings.cacheHit": "缓存命中率",
1485
+ "savings.actualCost": "实际成本(官方牌价)",
1486
+ "savings.savedMoney": "估算节省金额(按输入价)",
1487
+ "savings.perSession": "会话"
1283
1488
  };
1284
1489
  /** English copy matching every simplified Chinese selector key. */
1285
1490
  const en = {
@@ -1375,7 +1580,21 @@ window.__ModuleLoader__.load({
1375
1580
  "custom.tailTrim.warning": "TailTrim requires the exact tokenizer and replaces at most one complete, finished, non-error tool-only group with a recoverable reference. It shares Protected recent tool calls, Protected recent tool-result tail, and Minimum reclaim with History. It rewrites a sent prefix and may reduce cache hits.",
1376
1581
  "custom.save": "Save Custom policy",
1377
1582
  "custom.reset": "Reset Custom policy",
1378
- "custom.invalid": "Custom policy values are invalid."
1583
+ "custom.invalid": "Custom policy values are invalid.",
1584
+ "savings.title": "Savings (this process)",
1585
+ "savings.netExact": "Net saved (exact basis)",
1586
+ "savings.netEstimated": "Net saved (estimated basis)",
1587
+ "savings.gross": "Gross saved (at publish time)",
1588
+ "savings.offsets": "Offsets (compressed content re-read in full)",
1589
+ "savings.empty": "No compression yet — net savings appear after the first reduction lands.",
1590
+ "savings.basisExact": "exact",
1591
+ "savings.basisEstimated": "estimated",
1592
+ "savings.basisNote": "Bases are reported separately, never merged: exact = DeepSeek tokenizer; estimated = chars/4. A skeleton followed by a full read counts as negative savings (net can go below zero).",
1593
+ "savings.requests": "Requests",
1594
+ "savings.cacheHit": "Cache hit rate",
1595
+ "savings.actualCost": "Actual cost (official prices)",
1596
+ "savings.savedMoney": "Estimated saved cost (input price)",
1597
+ "savings.perSession": "Session"
1379
1598
  };
1380
1599
  //#endregion
1381
1600
  //#region src/client/locales/de.ts
@@ -1473,7 +1692,21 @@ window.__ModuleLoader__.load({
1473
1692
  "custom.tailTrim.warning": "TailTrim erfordert den exakten Tokenizer und ersetzt höchstens eine vollständige, abgeschlossene, fehlerfreie Gruppe nur aus Tools durch eine wiederherstellbare Referenz. Es teilt sich mit History die geschützten letzten Tool-Aufrufe, das geschützte neue Ende der Tool-Ergebnisse und die Mindest-Freigabe. Es schreibt ein gesendetes Präfix um und kann Cache-Treffer verringern.",
1474
1693
  "custom.save": "Eigene Strategie speichern",
1475
1694
  "custom.reset": "Eigene Strategie zurücksetzen",
1476
- "custom.invalid": "Werte der eigenen Strategie sind ungültig."
1695
+ "custom.invalid": "Werte der eigenen Strategie sind ungültig.",
1696
+ "savings.title": "Einsparungen (dieser Prozess)",
1697
+ "savings.netExact": "Netto gespeichert (exakte Basis)",
1698
+ "savings.netEstimated": "Netto gespeichert (geschätzte Basis)",
1699
+ "savings.gross": "Brutto gespeichert (bei Veröffentlichung)",
1700
+ "savings.offsets": "Abschläge (komprimiert, später vollständig gelesen)",
1701
+ "savings.empty": "Noch keine Komprimierung — Nettoeinsparungen erscheinen nach der ersten Reduktion.",
1702
+ "savings.basisExact": "exakt",
1703
+ "savings.basisEstimated": "geschätzt",
1704
+ "savings.basisNote": "Basen werden getrennt ausgewiesen, nie gemischt: exakt = DeepSeek-Tokenizer; geschätzt = chars/4. Erst Skelett, dann Volltext zählt als negative Einsparung (Netto kann unter null fallen).",
1705
+ "savings.requests": "Requests",
1706
+ "savings.cacheHit": "Cache hit rate",
1707
+ "savings.actualCost": "Actual cost (official prices)",
1708
+ "savings.savedMoney": "Estimated saved cost (input price)",
1709
+ "savings.perSession": "Session"
1477
1710
  };
1478
1711
  //#endregion
1479
1712
  //#region src/client/locales/es.ts
@@ -1571,7 +1804,21 @@ window.__ModuleLoader__.load({
1571
1804
  "custom.tailTrim.warning": "TailTrim requiere el tokenizador exacto y sustituye como máximo un grupo completo, terminado y sin errores compuesto solo por herramientas por una referencia recuperable. Comparte con History las llamadas a herramientas recientes protegidas, la cola reciente de resultados de herramientas protegida y la recuperación mínima. Reescribe un prefijo enviado y puede reducir los aciertos de caché.",
1572
1805
  "custom.save": "Guardar la política personalizada",
1573
1806
  "custom.reset": "Restablecer la política personalizada",
1574
- "custom.invalid": "Los valores de la política personalizada no son válidos."
1807
+ "custom.invalid": "Los valores de la política personalizada no son válidos.",
1808
+ "savings.title": "Ahorro (este proceso)",
1809
+ "savings.netExact": "Ahorro neto (base exacta)",
1810
+ "savings.netEstimated": "Ahorro neto (base estimada)",
1811
+ "savings.gross": "Ahorro bruto (al publicar)",
1812
+ "savings.offsets": "Compensaciones (contenido comprimido y luego releído completo)",
1813
+ "savings.empty": "Aún sin compresión: el ahorro neto aparece tras la primera reducción.",
1814
+ "savings.basisExact": "exacta",
1815
+ "savings.basisEstimated": "estimada",
1816
+ "savings.basisNote": "Las bases se informan por separado, nunca mezcladas: exacta = tokenizador DeepSeek; estimada = chars/4. Esqueleto seguido de lectura completa cuenta como ahorro negativo (el neto puede ser negativo).",
1817
+ "savings.requests": "Anfragen",
1818
+ "savings.cacheHit": "Cache-Trefferquote",
1819
+ "savings.actualCost": "Tatsächliche Kosten (offizielle Preise)",
1820
+ "savings.savedMoney": "Geschätzte Einsparung (Eingabepreis)",
1821
+ "savings.perSession": "Sitzung"
1575
1822
  };
1576
1823
  //#endregion
1577
1824
  //#region src/client/locales/fr.ts
@@ -1669,7 +1916,21 @@ window.__ModuleLoader__.load({
1669
1916
  "custom.tailTrim.warning": "TailTrim exige le tokenizer exact et remplace au plus un groupe complet, terminé et sans erreur, composé uniquement d’outils, par une référence récupérable. Il partage avec History les appels d’outils récents protégés, la fin récente des résultats d’outils protégée et la récupération minimale. Il réécrit un préfixe envoyé et peut réduire les hits de cache.",
1670
1917
  "custom.save": "Enregistrer la stratégie personnalisée",
1671
1918
  "custom.reset": "Réinitialiser la stratégie personnalisée",
1672
- "custom.invalid": "Valeurs de la stratégie personnalisée invalides."
1919
+ "custom.invalid": "Valeurs de la stratégie personnalisée invalides.",
1920
+ "savings.title": "Économies (ce processus)",
1921
+ "savings.netExact": "Économie nette (base exacte)",
1922
+ "savings.netEstimated": "Économie nette (base estimée)",
1923
+ "savings.gross": "Économie brute (à la publication)",
1924
+ "savings.offsets": "Compensations (contenu compressé puis relu intégralement)",
1925
+ "savings.empty": "Aucune compression pour l’instant — l’économie nette apparaît après la première réduction.",
1926
+ "savings.basisExact": "exacte",
1927
+ "savings.basisEstimated": "estimée",
1928
+ "savings.basisNote": "Les bases sont présentées séparément, jamais mélangées : exacte = tokenizer DeepSeek ; estimée = chars/4. Un squelette suivi d’une lecture complète compte comme économie négative (le net peut être négatif).",
1929
+ "savings.requests": "Solicitudes",
1930
+ "savings.cacheHit": "Tasa de aciertos de caché",
1931
+ "savings.actualCost": "Coste real (precios oficiales)",
1932
+ "savings.savedMoney": "Ahorro estimado (precio de entrada)",
1933
+ "savings.perSession": "Sesión"
1673
1934
  };
1674
1935
  //#endregion
1675
1936
  //#region src/client/locales/it.ts
@@ -1767,7 +2028,21 @@ window.__ModuleLoader__.load({
1767
2028
  "custom.tailTrim.warning": "TailTrim richiede il tokenizer esatto e sostituisce al massimo un gruppo completo, concluso e senza errori composto solo da tool con un riferimento recuperabile. Condivide con History le chiamate ai tool recenti protette, la coda recente dei risultati dei tool protetta e il recupero minimo. Riscrive un prefisso inviato e può ridurre i hit della cache.",
1768
2029
  "custom.save": "Salva la politica personalizzata",
1769
2030
  "custom.reset": "Reimposta la politica personalizzata",
1770
- "custom.invalid": "I valori della politica personalizzata non sono validi."
2031
+ "custom.invalid": "I valori della politica personalizzata non sono validi.",
2032
+ "savings.title": "Risparmi (questo processo)",
2033
+ "savings.netExact": "Risparmio netto (base esatta)",
2034
+ "savings.netEstimated": "Risparmio netto (base stimata)",
2035
+ "savings.gross": "Risparmio lordo (alla pubblicazione)",
2036
+ "savings.offsets": "Compensazioni (contenuto compresso e poi riletto per intero)",
2037
+ "savings.empty": "Nessuna compressione — il risparmio netto appare dopo la prima riduzione.",
2038
+ "savings.basisExact": "esatta",
2039
+ "savings.basisEstimated": "stimata",
2040
+ "savings.basisNote": "Le basi sono riportate separatamente, mai miste: esatta = tokenizer DeepSeek; stimata = chars/4. Uno scheletro seguito dalla lettura completa conta come risparmio negativo (il netto può scendere sotto zero).",
2041
+ "savings.requests": "Requêtes",
2042
+ "savings.cacheHit": "Taux de cache",
2043
+ "savings.actualCost": "Coût réel (tarifs officiels)",
2044
+ "savings.savedMoney": "Économie estimée (prix d’entrée)",
2045
+ "savings.perSession": "Session"
1771
2046
  };
1772
2047
  //#endregion
1773
2048
  //#region src/client/locales/ja.ts
@@ -1865,7 +2140,21 @@ window.__ModuleLoader__.load({
1865
2140
  "custom.tailTrim.warning": "TailTrim は正確なトークナイザーが必要で、完全で終了済みかつエラーでないツールのみのグループを 1 つだけ回復可能な参照へ置き換えます。History と「保護する直近ツール呼び出し数」「保護するツール結果テール」「最小回収量」を共有します。送信済みプレフィックスを書き換えるため、キャッシュ命中が下がる可能性があります。",
1866
2141
  "custom.save": "カスタムポリシーを保存",
1867
2142
  "custom.reset": "カスタムポリシーをリセット",
1868
- "custom.invalid": "カスタムポリシーの値が不正です。"
2143
+ "custom.invalid": "カスタムポリシーの値が不正です。",
2144
+ "savings.title": "節約統計(このプロセス)",
2145
+ "savings.netExact": "純節約(正確口径)",
2146
+ "savings.netEstimated": "純節約(推定口径)",
2147
+ "savings.gross": "総節約(圧縮確定時)",
2148
+ "savings.offsets": "相殺(圧縮後に全文再読)",
2149
+ "savings.empty": "まだ圧縮がありません。最初の削減後に純節約が表示されます。",
2150
+ "savings.basisExact": "正確",
2151
+ "savings.basisEstimated": "推定",
2152
+ "savings.basisNote": "口径は分列し混算しません:正確 = DeepSeek トークナイザー、推定 = chars/4。スケルトン後に全文を読むと負の節約として計上されます(純額はマイナスになり得ます)。",
2153
+ "savings.requests": "Richieste",
2154
+ "savings.cacheHit": "Tasso di cache",
2155
+ "savings.actualCost": "Costo reale (prezzi ufficiali)",
2156
+ "savings.savedMoney": "Risparmio stimato (prezzo di input)",
2157
+ "savings.perSession": "Sessione"
1869
2158
  };
1870
2159
  //#endregion
1871
2160
  //#region src/client/locales/ko.ts
@@ -1963,7 +2252,21 @@ window.__ModuleLoader__.load({
1963
2252
  "custom.tailTrim.warning": "TailTrim은 정확한 토크나이저를 필요로 하며, 완결되고 오류 없는 도구 전용 그룹 하나를 복구 가능한 참조로 대체합니다. History와 「보호하는 최근 도구 호출 수」「보호하는 도구 결과 테일」「최소 회수량」을 공유합니다. 전송 접두사를 재작성하므로 캐시 적중이 낮아질 수 있습니다.",
1964
2253
  "custom.save": "커스텀 정책 저장",
1965
2254
  "custom.reset": "커스텀 정책 초기화",
1966
- "custom.invalid": "커스텀 정책 값이 올바르지 않습니다."
2255
+ "custom.invalid": "커스텀 정책 값이 올바르지 않습니다.",
2256
+ "savings.title": "절감 통계(이 프로세스)",
2257
+ "savings.netExact": "순 절감(정확 기준)",
2258
+ "savings.netEstimated": "순 절감(추정 기준)",
2259
+ "savings.gross": "총 절감(게시 시점)",
2260
+ "savings.offsets": "상쇄(압축 후 전체 재판돈)",
2261
+ "savings.empty": "아직 압축이 없습니다. 첫 번째 축소 후 순 절감이 표시됩니다.",
2262
+ "savings.basisExact": "정확",
2263
+ "savings.basisEstimated": "추정",
2264
+ "savings.basisNote": "기준은 분리 표기하며 혼합하지 않습니다: 정확 = DeepSeek 토크나이저, 추정 = chars/4. 스켈레톤 후 전체 판독은 음의 절감으로 계산됩니다(순액은 마이너스 가능).",
2265
+ "savings.requests": "リクエスト数",
2266
+ "savings.cacheHit": "キャッシュ ヒット率",
2267
+ "savings.actualCost": "実際コスト(公式価格)",
2268
+ "savings.savedMoney": "推定節約額(入力価格)",
2269
+ "savings.perSession": "セッション"
1967
2270
  };
1968
2271
  //#endregion
1969
2272
  //#region src/client/locales/ru.ts
@@ -2061,7 +2364,21 @@ window.__ModuleLoader__.load({
2061
2364
  "custom.tailTrim.warning": "TailTrim требует точный токенизатор и заменяет максимум одну полную, завершённую, без ошибок группу только из инструментов на восстанавливаемую ссылку. Он использует общие с History защищённые недавние вызовы инструментов, защищённый недавний хвост результатов инструментов и минимальное освобождение. Он переписывает отправленный префикс и может снизить попадания в кэш.",
2062
2365
  "custom.save": "Сохранить пользовательскую стратегию",
2063
2366
  "custom.reset": "Сбросить пользовательскую стратегию",
2064
- "custom.invalid": "Значения пользовательской стратегии недопустимы."
2367
+ "custom.invalid": "Значения пользовательской стратегии недопустимы.",
2368
+ "savings.title": "Экономия (этот процесс)",
2369
+ "savings.netExact": "Чистая экономия (точная база)",
2370
+ "savings.netEstimated": "Чистая экономия (оценочная база)",
2371
+ "savings.gross": "Валовая экономия (при публикации)",
2372
+ "savings.offsets": "Компенсации (сжатый контент затем прочитан полностью)",
2373
+ "savings.empty": "Сжатия пока не было — чистая экономия появится после первого сокращения.",
2374
+ "savings.basisExact": "точно",
2375
+ "savings.basisEstimated": "оценка",
2376
+ "savings.basisNote": "Базы приводятся раздельно и не смешиваются: точно = токенизатор DeepSeek; оценка = chars/4. Скелет с последующим полным чтением учитывается как отрицательная экономия (чистая может уйти в минус).",
2377
+ "savings.requests": "요청 수",
2378
+ "savings.cacheHit": "캐시 적중률",
2379
+ "savings.actualCost": "실제 비용(공식 가격)",
2380
+ "savings.savedMoney": "추정 절감액(입력 가격)",
2381
+ "savings.perSession": "세션"
2065
2382
  };
2066
2383
  //#endregion
2067
2384
  //#region src/client/preset-options.ts
@@ -1,7 +1,7 @@
1
- import { l as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, t as getAdvisorState } from "./advisor-state.js";
1
+ import { D as priceOfficialDeepSeekUsage, k as getSavingsLedger, l as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, t as getAdvisorState } from "./advisor-state.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
- import { AsyncLocalStorage } from "node:async_hooks";
4
3
  import { createHash } from "node:crypto";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
7
7
  import { isAbsolute, join } from "node:path";
@@ -504,6 +504,7 @@ function restoreMethod(presets, snapshot) {
504
504
  //#region src/index.ts
505
505
  const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
506
506
  const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advisor-report", "/api/dsh-context-compression-improved/advisor-report"];
507
+ const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
507
508
  function sessionFor(readService, sessionId) {
508
509
  const agents = readService("agents");
509
510
  return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
@@ -719,6 +720,124 @@ function registerEstimatorCatalogRoute(ctx) {
719
720
  log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
720
721
  }
721
722
  /**
723
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
724
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
725
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
726
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
727
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
728
+ */
729
+ function estimateSavingsPricing(readService, snapshot) {
730
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
731
+ const selection = readService("agentDefaultModel")?.currentSelection?.();
732
+ const provider = typeof selection?.provider === "string" ? selection.provider : "";
733
+ const modelId = typeof selection?.model === "string" ? selection.model : "";
734
+ if (provider !== "deepseek-official") return void 0;
735
+ const now = /* @__PURE__ */ new Date();
736
+ const startedAt = new Date(snapshot.startedAt);
737
+ const base = {
738
+ provider,
739
+ baseUrlClass: "official-public",
740
+ apiRoute: "chat-completions",
741
+ modelId,
742
+ currency: "USD",
743
+ startedAt,
744
+ completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
745
+ };
746
+ const actual = priceOfficialDeepSeekUsage({
747
+ ...base,
748
+ usage: {
749
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
750
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
751
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
752
+ }
753
+ });
754
+ const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
755
+ ...base,
756
+ usage: {
757
+ cacheReadTokens: 0,
758
+ cacheMissTokens: Math.round(snapshot.net.exact),
759
+ outputTokens: 0
760
+ }
761
+ }) : void 0;
762
+ const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
763
+ if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
764
+ return {
765
+ currency: "USD",
766
+ ...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
767
+ ...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
768
+ };
769
+ }
770
+ /**
771
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
772
+ * offsets (negative savings — compressed content later re-read in full), and net,
773
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
774
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
775
+ * channels for both service arrival orders, single guarded registration).
776
+ */
777
+ function registerSavingsRoute(ctx) {
778
+ const readService = (name) => {
779
+ try {
780
+ return ctx.get(name);
781
+ } catch {
782
+ return;
783
+ }
784
+ };
785
+ const log = (level, message, ...args) => {
786
+ console[level](message, ...args);
787
+ };
788
+ let registered = false;
789
+ const register = (webServer, channel) => {
790
+ if (registered) return;
791
+ const handler = (req, res) => {
792
+ const resTyped = res;
793
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
794
+ let sessionId;
795
+ try {
796
+ const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
797
+ if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
798
+ } catch {}
799
+ const snapshot = getSavingsLedger().snapshot(sessionId);
800
+ const pricing = estimateSavingsPricing(readService, snapshot);
801
+ resTyped.writeHead(200, {
802
+ "content-type": "application/json; charset=utf-8",
803
+ "cache-control": "no-cache"
804
+ });
805
+ resTyped.end(JSON.stringify({
806
+ ok: true,
807
+ ...snapshot,
808
+ ...pricing === void 0 ? {} : { pricing }
809
+ }));
810
+ };
811
+ try {
812
+ const disposers = SAVINGS_ROUTES.map((path) => webServer.register({
813
+ kind: "exact",
814
+ path,
815
+ handler
816
+ })).filter((off) => typeof off === "function");
817
+ registered = true;
818
+ ctx.effect(() => () => {
819
+ for (const off of disposers) off();
820
+ }, "contextCompressionSelector.savings route");
821
+ log("info", "context-compression savings route registered (%s): %s", channel, SAVINGS_ROUTES.join(", "));
822
+ } catch (error) {
823
+ log("warn", "context-compression savings route registration failed (%s): %o", channel, error);
824
+ }
825
+ };
826
+ const active = asWebServer(readService("webServer"));
827
+ if (active !== void 0) {
828
+ register(active, "direct");
829
+ if (registered) return;
830
+ }
831
+ ctx.inject(["webServer"], (injected) => {
832
+ const webServer = asWebServer(injected.webServer);
833
+ if (webServer === void 0) {
834
+ log("warn", "context-compression webServer exposes no register() — savings route not registered");
835
+ return;
836
+ }
837
+ register(webServer, "inject");
838
+ });
839
+ }
840
+ /**
722
841
  * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
723
842
  * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
724
843
  */
@@ -741,6 +860,7 @@ const Config = z.object({
741
860
  function apply(ctx, config = {}) {
742
861
  try {
743
862
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
863
+ registerSavingsRoute(ctx);
744
864
  if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
745
865
  if (config.presetOverlay !== true) return;
746
866
  ctx.inject(["agentPresets"], (presetsCtx) => {