dsh-context-compression-improved 0.9.3 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +1 -1
  2. package/packages/selector/dsh.plugin.json +1 -1
  3. package/packages/selector/lib/client.d.ts +1 -0
  4. package/packages/selector/lib/client.js +63 -10
  5. package/packages/selector/lib/config.js +71 -7
  6. package/packages/selector/lib/index.js +120 -20
  7. package/packages/selector/lib/pruner.d.ts +158 -107
  8. package/packages/selector/lib/pruner.js +331 -20
  9. package/packages/selector/package.json +1 -1
  10. package/packages/selector/src/client/index.ts +29 -2
  11. package/packages/selector/src/client/locales/de.ts +1 -0
  12. package/packages/selector/src/client/locales/es.ts +1 -0
  13. package/packages/selector/src/client/locales/fr.ts +1 -0
  14. package/packages/selector/src/client/locales/it.ts +1 -0
  15. package/packages/selector/src/client/locales/ja.ts +1 -0
  16. package/packages/selector/src/client/locales/ko.ts +1 -0
  17. package/packages/selector/src/client/locales/ru.ts +1 -0
  18. package/packages/selector/src/client/locales.ts +2 -0
  19. package/packages/selector/src/client/monitor-fab.ts +19 -4
  20. package/packages/selector/src/preset-overlay.ts +145 -22
  21. package/packages/selector/src/pruner/content.ts +1 -1
  22. package/packages/selector/src/pruner/state.ts +4 -0
  23. package/packages/selector/src/pruner.ts +104 -15
  24. package/packages/selector/src/runtime/config.ts +1 -1
  25. package/packages/selector/src/runtime/reducers.ts +81 -1
  26. package/packages/selector/src/runtime/retrieve.ts +4 -3
  27. package/packages/selector/src/runtime/savings-projection.ts +226 -0
  28. package/packages/selector/src/runtime/savings.ts +83 -3
  29. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  30. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  31. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
  32. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  33. package/packages/selector/tests/runtime/savings.spec.ts +22 -3
  34. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  35. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
@@ -1,4 +1,4 @@
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";
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, W as savingsHash, _ 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, c as eventBySeq, i as tailTrimStub, l as sessionEvents, n as tailTrimMessage, o as compressionMessageSource, r as tailTrimRef, s as viewToolResult, t as parseTailTrimRef } from "./tail-trim.js";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import { createHash } from "node:crypto";
@@ -385,7 +385,7 @@ function unavailableCount(reason) {
385
385
  });
386
386
  }
387
387
  function recoveryMarker(sourceRef, label, startLine) {
388
- return `\n\n[... ${label}; source=${sourceRef}; ${startLine === void 0 ? "use context_compression_retrieve if needed" : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`} ...]\n\n`;
388
+ return `\n\n[... ${label}; source=${sourceRef}; ${startLine === void 0 ? "use context_compression_retrieve with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)" : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`} ...]\n\n`;
389
389
  }
390
390
  /**
391
391
  * Measure text content in Unicode code points; non-text blocks cost zero.
@@ -732,17 +732,17 @@ function countSurfaceCounts(counts, subject) {
732
732
  });
733
733
  }
734
734
  z.object({
735
- maxChars: z.number().step(1).min(1).default(5e4),
735
+ maxChars: z.number().step(1).min(1).default(12e3),
736
736
  maxScanChars: z.number().step(1).min(1).default(25e4),
737
737
  maxQueryChars: z.number().step(1).min(1).default(256)
738
738
  });
739
739
  const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/;
740
740
  const MAX_LINES = 1e3;
741
- const DEFAULT_MAX_CHARS = 5e4;
741
+ const DEFAULT_MAX_CHARS = 12e3;
742
742
  const DEFAULT_MAX_SCAN_CHARS = 25e4;
743
743
  const DEFAULT_MAX_QUERY_CHARS = 256;
744
744
  const TRUNCATION_MARKER = "\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n";
745
- const PROMPT = "When a compacted tool result contains a session://<session-id>/event/<seq> reference, or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref and a narrow line range or query if the omitted evidence is necessary. The returned event content comes from the append-only session log, which is the source of truth.";
745
+ const PROMPT = "When a compacted tool result contains a session://<session-id>/event/<seq> reference, or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref and a narrow line range or query if the omitted evidence is necessary. Prefer a query or a tight start_line/max_lines over re-reading the whole result: every recovery re-enters the context and is charged against the savings, so a targeted slice keeps the rest of the reduction. The returned event content comes from the append-only session log, which is the source of truth.";
746
746
  const OUTPUT = {
747
747
  schema: { type: "string" },
748
748
  render: (_args, value) => [{
@@ -1370,6 +1370,11 @@ const ADJACENT_REPEAT_MARKER = "[previous line repeated";
1370
1370
  const NON_ADJACENT_FOLD_THRESHOLD = 3;
1371
1371
  /** Read-output line-number gutter added unconditionally by the host's `formatReadOutput`. */
1372
1372
  const READ_GUTTER_PATTERN = /^(\d+): ?/;
1373
+ /** JSONL/NDJSON preview: records kept from the head and tail of the stream. */
1374
+ const JSONL_HEAD_RECORDS = 3;
1375
+ const JSONL_TAIL_RECORDS = 2;
1376
+ /** JSONL detection validates a bounded prefix so a multi-MB stream stays cheap. */
1377
+ const JSONL_DETECT_SCAN = 512;
1373
1378
  /**
1374
1379
  * Block-level read-gutter detection (GF-1). The host prefixes read output with
1375
1380
  * `N: ` line numbers unconditionally and cannot be configured off. The gutter
@@ -1428,7 +1433,8 @@ function reduceFreshToolResult(input, ranking) {
1428
1433
  const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
1429
1434
  const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
1430
1435
  const candidates = [];
1431
- if (looksLikeJson(normalized.contentText)) candidates.push(() => reduceJson(prepared));
1436
+ if (looksLikeJsonl(normalized.contentText)) candidates.push(() => reduceJsonl(prepared));
1437
+ else if (looksLikeJson(normalized.contentText)) candidates.push(() => reduceJson(prepared));
1432
1438
  if (looksLikeMinified(normalized.contentText)) candidates.push(() => reduceBundledJs(prepared));
1433
1439
  if (toolClass === "search") candidates.push(() => reduceSearch(prepared, ranking?.files));
1434
1440
  if (isGitCommand(name, command)) candidates.push(() => reduceGit(prepared, command));
@@ -1791,6 +1797,76 @@ function reduceJson(input) {
1791
1797
  };
1792
1798
  return null;
1793
1799
  }
1800
+ /**
1801
+ * Reduce line-delimited JSON (JSONL/NDJSON): keep a head and tail sample of
1802
+ * records — each run through the same `shrinkJson` as the single-value branch —
1803
+ * and collapse the middle into an omitted-record count. Reads the gutter-
1804
+ * stripped content view so a host read listing (`N: ` prefix) still resolves.
1805
+ * Returns null when the sampled envelope cannot fit the budget (or when there
1806
+ * are too few records to omit anything), letting head/tail take over.
1807
+ */
1808
+ function reduceJsonl(input) {
1809
+ const recordLines = [];
1810
+ for (const line of input.contentText.split("\n")) {
1811
+ const trimmed = line.trim();
1812
+ if (trimmed !== "" && (trimmed.startsWith("{") || trimmed.startsWith("["))) recordLines.push(trimmed);
1813
+ }
1814
+ const total = recordLines.length;
1815
+ if (total < 2) return null;
1816
+ const parseRecord = (text) => {
1817
+ try {
1818
+ return JSON.parse(text);
1819
+ } catch {
1820
+ return text;
1821
+ }
1822
+ };
1823
+ const headCount = Math.min(JSONL_HEAD_RECORDS, total);
1824
+ const tailCount = total > headCount ? Math.min(JSONL_TAIL_RECORDS, total - headCount) : 0;
1825
+ const head = recordLines.slice(0, headCount).map((entry) => shrinkJson(parseRecord(entry), 0));
1826
+ const tail = tailCount > 0 ? recordLines.slice(total - tailCount).map((entry) => shrinkJson(parseRecord(entry), 0)) : [];
1827
+ const omitted = total - headCount - tailCount;
1828
+ const envelope = {
1829
+ $dsh_compression: {
1830
+ kind: "jsonl-preview",
1831
+ source: input.sourceRef,
1832
+ original_chars: codePointLength(input.text),
1833
+ records: total
1834
+ },
1835
+ head
1836
+ };
1837
+ if (omitted > 0) envelope.$dsh_omitted_records = omitted;
1838
+ if (tail.length > 0) envelope.tail = tail;
1839
+ const text = JSON.stringify(envelope, null, 2);
1840
+ if (codePointLength(text) >= codePointLength(input.text) || codePointLength(text) > input.budgetChars) return null;
1841
+ return {
1842
+ text,
1843
+ reducer: "jsonl-structure-preview",
1844
+ lossy: true
1845
+ };
1846
+ }
1847
+ /**
1848
+ * Detect JSONL/NDJSON: at least two non-empty lines, each of which parses on
1849
+ * its own as a JSON object or array. A pretty-printed single JSON fails this
1850
+ * (its interior lines are not standalone values), so the two forms never
1851
+ * collide. Only a bounded prefix is validated to keep multi-MB streams cheap.
1852
+ */
1853
+ function looksLikeJsonl(text) {
1854
+ let records = 0;
1855
+ for (const line of text.split("\n")) {
1856
+ const trimmed = line.trim();
1857
+ if (trimmed === "") continue;
1858
+ if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) return false;
1859
+ try {
1860
+ const parsed = JSON.parse(trimmed);
1861
+ if (typeof parsed !== "object" || parsed === null) return false;
1862
+ records += 1;
1863
+ } catch {
1864
+ return false;
1865
+ }
1866
+ if (records >= JSONL_DETECT_SCAN) break;
1867
+ }
1868
+ return records >= 2;
1869
+ }
1794
1870
  function shrinkJson(value, depth) {
1795
1871
  if (depth >= 5) {
1796
1872
  if (Array.isArray(value)) return `[array length=${String(value.length)} omitted]`;
@@ -3826,6 +3902,177 @@ function dedupePlaceholder(entry, originalChars) {
3826
3902
  ].join(" ");
3827
3903
  }
3828
3904
  //#endregion
3905
+ //#region src/runtime/savings-projection.ts
3906
+ const EMPTY = Object.freeze({
3907
+ savings: [],
3908
+ offsets: [],
3909
+ registry: []
3910
+ });
3911
+ function blocksOf(event) {
3912
+ if (event.type !== "tool/result") return void 0;
3913
+ return viewToolResult(event.data.message).blocks;
3914
+ }
3915
+ function textOf(event) {
3916
+ const blocks = blocksOf(event);
3917
+ return blocks === void 0 ? void 0 : flattenPlainText(blocks);
3918
+ }
3919
+ /** 与 pruner 的 `plan()` 同口径定价:全文本块可精确,否则字符口径。 */
3920
+ function priceEvent(event, countText) {
3921
+ const blocks = blocksOf(event);
3922
+ if (blocks === void 0) return void 0;
3923
+ const chars = pressureCost(blocks);
3924
+ if (chars <= 0) return void 0;
3925
+ const texts = blocks.map((block) => block.type === "text" ? block.text : void 0);
3926
+ if (texts.every((text) => text !== void 0)) {
3927
+ const count = countExactCanonicalTextFields(texts, countText, "savings projection");
3928
+ if (count.kind === "exact-tokenizer") return {
3929
+ tokens: count.tokens,
3930
+ basis: "exact-tokenizer",
3931
+ chars
3932
+ };
3933
+ }
3934
+ return {
3935
+ tokens: Math.max(1, charsToTokens(chars)),
3936
+ basis: "characters",
3937
+ chars
3938
+ };
3939
+ }
3940
+ /** 替换事件的被替换 span;非替换节点(或畸形 op)返回 undefined。 */
3941
+ function replacedSpan(event) {
3942
+ const op = event.surfaceOp;
3943
+ if (typeof op !== "object" || op === null || op.op !== "replace") return void 0;
3944
+ const start = Number(op.startSeq);
3945
+ const end = Number(op.endSeq);
3946
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return void 0;
3947
+ return {
3948
+ start,
3949
+ end
3950
+ };
3951
+ }
3952
+ function originalText(bySeq, span) {
3953
+ const parts = [];
3954
+ for (let seq = span.start; seq <= span.end; seq++) {
3955
+ const event = bySeq.get(seq);
3956
+ const text = event === void 0 ? void 0 : textOf(event);
3957
+ if (text !== void 0 && text.length > 0) parts.push(text);
3958
+ }
3959
+ return parts.join("\n");
3960
+ }
3961
+ /**
3962
+ * 一个替换节点"压掉了多少"(与实时 `plan()` 同口径:差额>0 才算)。
3963
+ * 原始价 = span 内原始事件之和;替换价 = 替换事件。
3964
+ */
3965
+ function computeDelta(bySeq, replacement, span, counter) {
3966
+ const after = priceEvent(replacement, counter);
3967
+ if (after === void 0) return void 0;
3968
+ let beforeChars = 0;
3969
+ let beforeExactTokens = 0;
3970
+ let beforeExact = true;
3971
+ let any = false;
3972
+ for (let seq = span.start; seq <= span.end; seq++) {
3973
+ const original = bySeq.get(seq);
3974
+ const priced = original === void 0 ? void 0 : priceEvent(original, counter);
3975
+ if (priced === void 0) continue;
3976
+ any = true;
3977
+ beforeChars += priced.chars;
3978
+ beforeExactTokens += priced.tokens;
3979
+ if (priced.basis !== "exact-tokenizer") beforeExact = false;
3980
+ }
3981
+ if (!any) return void 0;
3982
+ const exact = after.basis === "exact-tokenizer" && beforeExact;
3983
+ const basis = exact ? "exact-tokenizer" : "characters";
3984
+ const delta = (exact ? beforeExactTokens : charsToTokens(beforeChars)) - (exact ? after.tokens : charsToTokens(after.chars));
3985
+ if (delta <= 0) return void 0;
3986
+ return {
3987
+ tokens: delta,
3988
+ basis
3989
+ };
3990
+ }
3991
+ /**
3992
+ * 纯核心:给定事件流、当前 surface 节点与计价计数器,重算节省投影。
3993
+ * @param input - events/surfaceNodes/counter,均为实时路径的只读快照。
3994
+ * @returns savings(当前生效毛节省)/ offsets(每次重读惩罚)/ registry(原文配对键)。
3995
+ */
3996
+ function projectSavingsCore(input) {
3997
+ const { events, surfaceNodes, counter } = input;
3998
+ if (events.length === 0) return EMPTY;
3999
+ const bySeq = /* @__PURE__ */ new Map();
4000
+ for (const event of events) bySeq.set(Number(event.seq), event);
4001
+ const savings = [];
4002
+ for (const rawSeq of surfaceNodes) {
4003
+ const seq = Number(rawSeq);
4004
+ const replacement = bySeq.get(seq);
4005
+ if (replacement === void 0) continue;
4006
+ const span = replacedSpan(replacement);
4007
+ if (span === void 0) continue;
4008
+ const delta = computeDelta(bySeq, replacement, span, counter);
4009
+ if (delta === void 0) continue;
4010
+ savings.push({
4011
+ component: "projection",
4012
+ tokens: delta.tokens,
4013
+ basis: delta.basis,
4014
+ at: Number(replacement.time) || 0,
4015
+ replacementSeq: seq
4016
+ });
4017
+ }
4018
+ const offsets = [];
4019
+ const registry = [];
4020
+ const owned = /* @__PURE__ */ new Map();
4021
+ for (const event of events) {
4022
+ if (event.type !== "tool/result") continue;
4023
+ const span = replacedSpan(event);
4024
+ if (span !== void 0) {
4025
+ const groupText = originalText(bySeq, span);
4026
+ if (groupText.length === 0) continue;
4027
+ const delta = computeDelta(bySeq, event, span, counter);
4028
+ if (delta === void 0) continue;
4029
+ const hash = savingsHash(groupText);
4030
+ owned.set(hash, {
4031
+ claimedTokens: delta.tokens,
4032
+ basis: delta.basis,
4033
+ sourceSeq: span.start
4034
+ });
4035
+ registry.push({
4036
+ hash,
4037
+ claimedTokens: delta.tokens,
4038
+ basis: delta.basis,
4039
+ sourceSeq: span.start
4040
+ });
4041
+ continue;
4042
+ }
4043
+ const text = textOf(event);
4044
+ if (text === void 0 || text.length === 0) continue;
4045
+ const hit = owned.get(savingsHash(text));
4046
+ if (hit === void 0) continue;
4047
+ const priced = priceEvent(event, counter);
4048
+ if (priced === void 0) continue;
4049
+ offsets.push({
4050
+ component: "full-read",
4051
+ tokens: priced.tokens,
4052
+ basis: priced.basis,
4053
+ at: Number(event.time) || 0,
4054
+ note: `#${hit.sourceSeq} 的原文被全文重读(投影重建)`
4055
+ });
4056
+ }
4057
+ return {
4058
+ savings,
4059
+ offsets,
4060
+ registry
4061
+ };
4062
+ }
4063
+ /**
4064
+ * 从会话快照投影节省账。`measureForCompaction` 提供与实时同口径的 tokenizer
4065
+ * 计数器;失败时向上抛,由调用方 fail-open。
4066
+ */
4067
+ function projectSessionSavings(ctx, session) {
4068
+ const view = measureForCompaction(ctx, session);
4069
+ return projectSavingsCore({
4070
+ events: sessionEvents(session),
4071
+ surfaceNodes: session.surface.nodes,
4072
+ counter: (candidate) => view.countCanonicalText(candidate)
4073
+ });
4074
+ }
4075
+ //#endregion
3829
4076
  //#region src/runtime/adaptive-cost.ts
3830
4077
  /**
3831
4078
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
@@ -3973,6 +4220,35 @@ const SessionSeq = dshSessionSoft.SessionSeq ?? dshSessionSoft.default?.SessionS
3973
4220
  function originalTextForSavings(candidate) {
3974
4221
  return flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
3975
4222
  }
4223
+ /**
4224
+ * Cross-generation adaptation (0.2.0): the host `settings` service hands back
4225
+ * the WHOLE entry config `{ settings: <subtree> }` instead of the settings
4226
+ * subtree directly (older lines surfaced the subtree at the top level). The
4227
+ * parser requires `profile`+`custom` at the root, so the wrapped shape threw
4228
+ * "missing its complete shape" → the session failed open to `profile:'off'`,
4229
+ * silently disabling fresh/aggregate on the desktop. Descend exactly one
4230
+ * `{settings:<obj>}` wrapper ONLY when the root has no `profile`; every other
4231
+ * shape is passed through untouched so the "exotic Host value must fail open
4232
+ * to off" safety contract still holds.
4233
+ */
4234
+ function unwrapSettingsEntry(value) {
4235
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
4236
+ const record = value;
4237
+ if ("profile" in record) return value;
4238
+ const inner = record.settings;
4239
+ if (inner !== null && typeof inner === "object" && !Array.isArray(inner)) return inner;
4240
+ return value;
4241
+ }
4242
+ /**
4243
+ * Whether a fresh candidate is BELOW the fresh trigger. Uses the real token
4244
+ * count when an exact tokenizer is available (DeepSeek routes), and otherwise
4245
+ * falls back to the 4.0 chars/token estimate — byte-for-byte the pre-existing
4246
+ * behavior on routes without a bundled tokenizer (e.g. local Qwen).
4247
+ */
4248
+ function freshBelowTrigger(candidate, policy) {
4249
+ if (candidate.count.kind === "exact-tokenizer") return candidate.count.tokens <= policy.freshTriggerTokens;
4250
+ return candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens);
4251
+ }
3976
4252
  /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
3977
4253
  var ToolResultPruner = class extends Service {
3978
4254
  static inject = ["tokenMeter"];
@@ -4017,6 +4293,8 @@ var ToolResultPruner = class extends Service {
4017
4293
  turnClocks: /* @__PURE__ */ new WeakMap(),
4018
4294
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
4019
4295
  advisorChannels: /* @__PURE__ */ new WeakMap(),
4296
+ intentChannels: /* @__PURE__ */ new WeakMap(),
4297
+ projectedSavings: /* @__PURE__ */ new WeakSet(),
4020
4298
  pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4021
4299
  intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4022
4300
  intentBaselines: /* @__PURE__ */ new WeakMap()
@@ -4072,6 +4350,10 @@ var ToolResultPruner = class extends Service {
4072
4350
  try {
4073
4351
  observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
4074
4352
  } catch {}
4353
+ this.ensureSavingsProjection(agent.session);
4354
+ try {
4355
+ getSavingsLedger().observeActive(String(agent.session.id), new Set([...agent.session.surface.nodes].map(Number)));
4356
+ } catch {}
4075
4357
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4076
4358
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4077
4359
  this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
@@ -4160,12 +4442,13 @@ var ToolResultPruner = class extends Service {
4160
4442
  if (frozen !== void 0) return frozen;
4161
4443
  const settingsHost = this.ctx.get("settings");
4162
4444
  const settings = settingsHost?.describe?.().find((d) => String(d.ns) === "context-compression-improved-bundle")?.value ?? settingsHost?.get?.("context-compression");
4445
+ const unwrapped = unwrapSettingsEntry(settings);
4163
4446
  let resolved;
4164
4447
  let settingsSource = settings === void 0 ? "plugin-config-fallback" : "host-settings";
4165
4448
  let autoCompactThresholdSource = settings === void 0 ? "schema-default" : "host-settings";
4166
4449
  let settingsInvalidFallback;
4167
4450
  try {
4168
- resolved = settings === void 0 ? ContextCompressionSettingsSchema({ profile: this.state.config.profile }) : parseContextCompressionSettings(settings);
4451
+ resolved = settings === void 0 ? ContextCompressionSettingsSchema({ profile: this.state.config.profile }) : parseContextCompressionSettings(unwrapped);
4169
4452
  } catch (error) {
4170
4453
  const reason = error instanceof Error ? error.message : String(error);
4171
4454
  this.auditFailure(session, "pressure", "policy-resolution", error);
@@ -4275,7 +4558,7 @@ var ToolResultPruner = class extends Service {
4275
4558
  for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
4276
4559
  if (samples.length >= 3) break;
4277
4560
  if (candidate.event.data.turn === void 0) continue;
4278
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) continue;
4561
+ if (freshBelowTrigger(candidate, policy)) continue;
4279
4562
  const path = toolCallPath(candidate.call.arguments);
4280
4563
  if (path === void 0) continue;
4281
4564
  if (isSupersededRead(events, candidate.seq, path)) continue;
@@ -4406,6 +4689,20 @@ var ToolResultPruner = class extends Service {
4406
4689
  else if (outcome !== void 0) advisorState.failures = void 0;
4407
4690
  }
4408
4691
  /**
4692
+ * 重进/重启会话的懒重建:首次观测某会话时,若账本尚无该会话条目,则按会话
4693
+ * 日志投影播种(当前生效毛节省 + 每次重读惩罚 + 原文配对键)。只做一次,
4694
+ * fail-open;同一进程内的实时增量随后在同一条目集合上继续。
4695
+ */
4696
+ ensureSavingsProjection(session) {
4697
+ if (this.state.projectedSavings.has(session)) return;
4698
+ this.state.projectedSavings.add(session);
4699
+ const ledger = getSavingsLedger();
4700
+ if (ledger.hasSession(String(session.id))) return;
4701
+ try {
4702
+ ledger.seedProjected(String(session.id), projectSessionSavings(this.ctx, session));
4703
+ } catch {}
4704
+ }
4705
+ /**
4409
4706
  * Fire-and-forget postflight: evaluate the growth gate, and only when it
4410
4707
  * passes, select the consumed increment OUTSIDE the protected working set,
4411
4708
  * mask it to semantic-role records, and spend ONE summary-writer call. The
@@ -4438,7 +4735,20 @@ var ToolResultPruner = class extends Service {
4438
4735
  }).decision) return;
4439
4736
  const settingsPreset = settings.presetOptions;
4440
4737
  if (settingsPreset === void 0) return;
4441
- if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
4738
+ const estimatorMode = settingsPreset.estimatorMode ?? "";
4739
+ if (estimatorMode !== "host" && estimatorMode !== "direct") {
4740
+ emitCompressionAudit(this.ctx.logger, {
4741
+ schemaVersion: 1,
4742
+ kind: "intent-summary-outcome",
4743
+ sessionId,
4744
+ ok: false,
4745
+ reason: "no-estimator-channel",
4746
+ turnIndex: turn,
4747
+ latencyMs: Date.now() - started
4748
+ });
4749
+ return;
4750
+ }
4751
+ if (estimatorMode === "direct" && (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0)) {
4442
4752
  emitCompressionAudit(this.ctx.logger, {
4443
4753
  schemaVersion: 1,
4444
4754
  kind: "intent-summary-outcome",
@@ -4477,14 +4787,14 @@ var ToolResultPruner = class extends Service {
4477
4787
  if (records.length === 0) return;
4478
4788
  const events = sessionEvents(session);
4479
4789
  const task = collectTaskSemantics(events);
4480
- let channel = this.state.advisorChannels.get(session);
4790
+ let channel = this.state.intentChannels.get(session);
4481
4791
  if (channel === void 0) {
4482
4792
  channel = new SideChannel(this.ctx, settingsPreset, {
4483
- mode: "direct",
4793
+ mode: estimatorMode,
4484
4794
  timeoutMs: 3e4,
4485
4795
  maxTokens: 512
4486
4796
  });
4487
- this.state.advisorChannels.set(session, channel);
4797
+ this.state.intentChannels.set(session, channel);
4488
4798
  }
4489
4799
  const answer = await channel.ask({
4490
4800
  system: buildIntentSummarySystemPrompt(),
@@ -4948,8 +5258,7 @@ var ToolResultPruner = class extends Service {
4948
5258
  const plans = /* @__PURE__ */ new Map();
4949
5259
  let freshPlanned = 0;
4950
5260
  const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
4951
- const candidateChars = candidates.map((candidate) => candidate.characterPressure);
4952
- const maxCandidateChars = candidateChars.length === 0 ? void 0 : Math.max(...candidateChars);
5261
+ const maxCandidateTokens = candidates.length === 0 ? void 0 : Math.max(...candidates.map((candidate) => candidate.count.kind === "exact-tokenizer" ? candidate.count.tokens : charsToTokens(candidate.characterPressure)));
4953
5262
  if (policy.freshEnabled) {
4954
5263
  if (candidates.some((candidate) => candidate.call.name !== "context_compression_retrieve" && candidate.count.kind !== "exact-tokenizer")) this.warnExactUnavailable(session, view, "fresh");
4955
5264
  for (const candidate of candidates) {
@@ -4992,9 +5301,9 @@ var ToolResultPruner = class extends Service {
4992
5301
  const landed = this.landAll(session, this.adviseReplacements(session, policy, freshCandidates, "fresh"));
4993
5302
  const freshLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "fresh");
4994
5303
  const aggregateLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "aggregate");
4995
- if (!freshLanded) this.auditComponent(session, policy, "fresh", "fresh", policy.freshEnabled ? "skipped" : "disabled", !policy.freshEnabled ? "profile-policy" : (maxCandidateChars ?? 0) <= charsForTokens(policy.freshTriggerTokens) ? "at-or-below-trigger" : freshPlanned > 0 && aggregatePlanned > 0 ? "superseded-by-aggregate" : freshPlanned === 0 ? "no-valid-reduction" : "recovery-tool-unavailable", {
5304
+ if (!freshLanded) this.auditComponent(session, policy, "fresh", "fresh", policy.freshEnabled ? "skipped" : "disabled", !policy.freshEnabled ? "profile-policy" : (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? "at-or-below-trigger" : freshPlanned > 0 && aggregatePlanned > 0 ? "superseded-by-aggregate" : freshPlanned === 0 ? "no-valid-reduction" : "recovery-tool-unavailable", {
4996
5305
  measurementKind: "characters",
4997
- ...maxCandidateChars === void 0 ? {} : { currentTokens: charsToTokens(maxCandidateChars) },
5306
+ ...maxCandidateTokens === void 0 ? {} : { currentTokens: maxCandidateTokens },
4998
5307
  triggerTokens: policy.freshTriggerTokens,
4999
5308
  targetTokens: policy.freshTargetTokens
5000
5309
  });
@@ -5069,7 +5378,7 @@ var ToolResultPruner = class extends Service {
5069
5378
  if (typeof candidate.event.surfaceOp === "object") return null;
5070
5379
  const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
5071
5380
  if (text === void 0) return null;
5072
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null;
5381
+ if (freshBelowTrigger(candidate, policy)) return null;
5073
5382
  let table = this.state.dedupeTables.get(session);
5074
5383
  if (table === void 0) {
5075
5384
  table = new DedupeTable();
@@ -5097,7 +5406,7 @@ var ToolResultPruner = class extends Service {
5097
5406
  planFresh(candidate, session, policy, view) {
5098
5407
  if (typeof candidate.event.surfaceOp === "object") return null;
5099
5408
  const resultView = viewToolResult(candidate.event.data.message);
5100
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null;
5409
+ if (freshBelowTrigger(candidate, policy)) return null;
5101
5410
  const sourceSeq = candidate.seq;
5102
5411
  const sourceRef$1 = sourceRef(session, sourceSeq);
5103
5412
  const textBlock = onlyTextBlock(resultView.blocks);
@@ -5140,7 +5449,7 @@ var ToolResultPruner = class extends Service {
5140
5449
  "[Tool result reduced to satisfy the completed-step aggregate budget]",
5141
5450
  `tool: ${candidate.call.name}`,
5142
5451
  `source: ${sourceRef$2}`,
5143
- "Use context_compression_retrieve with this source if the omitted evidence is necessary."
5452
+ "Retrieve a narrow slice via context_compression_retrieve if needed."
5144
5453
  ].join("\n");
5145
5454
  const plan = this.plan(candidate, [{
5146
5455
  type: "text",
@@ -5473,6 +5782,7 @@ var ToolResultPruner = class extends Service {
5473
5782
  tokensAfter,
5474
5783
  basis: exact ? "exact-tokenizer" : "characters",
5475
5784
  sourceSeq: manifestSeq,
5785
+ replacementSeq: Number(replacement.seq),
5476
5786
  originalText: groupText
5477
5787
  });
5478
5788
  return;
@@ -5614,6 +5924,7 @@ var ToolResultPruner = class extends Service {
5614
5924
  tokensAfter: plan.tokensAfter,
5615
5925
  basis: plan.measurementBasis,
5616
5926
  sourceSeq: plan.sourceSeq,
5927
+ replacementSeq: Number(replacement.seq),
5617
5928
  ...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
5618
5929
  });
5619
5930
  return {
@@ -5786,4 +6097,4 @@ var ToolResultPruner = class extends Service {
5786
6097
  }
5787
6098
  };
5788
6099
  //#endregion
5789
- export { AUTO_COMPACT_THRESHOLD_LIMITS, COMPRESSION_PROFILES, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, ContextCompressionSettingsSchema, CustomCompressionPolicySchema, DEFAULTS, DEFAULT_CUSTOM_COMPRESSION_POLICY, PRUNE_MARKER, ToolResultPruner, ToolResultPruner as default, codePointLength, historicalPlaceholder, isCompressionProfile, isValidAutoCompactThresholdPercent, measureForCompaction, normalizeTerminalText, parseContextCompressionSettings, reduceFreshToolResult, resolveConfig, resolveCustomPolicy, resolvePolicy, verifyReduction };
6100
+ export { AUTO_COMPACT_THRESHOLD_LIMITS, COMPRESSION_PROFILES, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, ContextCompressionSettingsSchema, CustomCompressionPolicySchema, DEFAULTS, DEFAULT_CUSTOM_COMPRESSION_POLICY, PRUNE_MARKER, ToolResultPruner, ToolResultPruner as default, codePointLength, freshBelowTrigger, historicalPlaceholder, isCompressionProfile, isValidAutoCompactThresholdPercent, measureForCompaction, normalizeTerminalText, parseContextCompressionSettings, reduceFreshToolResult, resolveConfig, resolveCustomPolicy, resolvePolicy, unwrapSettingsEntry, verifyReduction };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.9.3",
3
+ "version": "0.9.5",
4
4
  "description": "One-install context-compression selector bundle for DeepSeek Harness",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -81,7 +81,14 @@ function sameCustomPolicy(
81
81
  }
82
82
 
83
83
  export function apply(ctx: ClientContext): void {
84
- ctx.locale.register(NS, { zh, en })
84
+ // 幂等:本插件可被两行同 name 挂载(bundle 行 + estimator-catalog 行,宿主侧靠
85
+ // 引用计数去重压缩栈),客户端 apply 会被调用多次。首注册必须容错,否则第二次
86
+ // 抛 'locale namespace ... already has locale "zh"' 会使整个客户端同步失败。
87
+ try {
88
+ ctx.locale.register(NS, { zh, en })
89
+ } catch (error) {
90
+ console.warn('[dsh-context-compression-improved] locale 默认包(zh/en) 已注册,跳过:', error)
91
+ }
85
92
  // de/es/fr/it/ja/ko/ru are not host built-ins (`BuiltInLocaleId` is zh|en), so
86
93
  // their dictionaries ride the single-locale untyped register overload, and each
87
94
  // needs an `addLanguage` definition to become selectable — the catalog owns
@@ -125,6 +132,8 @@ let configFormsHandle: ConfigFormsHandle | undefined
125
132
 
126
133
  /** Last monitorPanel.enabled seen through whichever scope is current (FAB 读数缓存). */
127
134
  let monitorPanelEnabledCache = false
135
+ /** configForms 臂是否已经成功读过一次文档(FAB 读数是否可信)。 */
136
+ let nativeMonitorReady = false
128
137
 
129
138
  /** 浮动监控面板(FAB): body 级幂等单例。enabled 读数走双臂 scope 的投影缓存。 */
130
139
  let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
@@ -161,7 +170,9 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
161
170
  bridgeScope.refresh()
162
171
  const bridgeReadEnabled = (): boolean =>
163
172
  decodeSettings(bridgeScope.getSnapshot().value)?.monitorPanel?.enabled ?? false
164
- readMonitorPanelEnabled = (): boolean => (configFormsHandle === undefined ? bridgeReadEnabled() : monitorPanelEnabledCache)
173
+ readMonitorPanelEnabled = (): boolean => (configFormsHandle !== undefined && nativeMonitorReady
174
+ ? monitorPanelEnabledCache
175
+ : bridgeReadEnabled())
165
176
  try {
166
177
  ctx.inject(['configForms'], (configFormsArg) => {
167
178
  // cordis passes the service's OWNER CONTEXT to inject callbacks (the
@@ -175,6 +186,21 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
175
186
  const svc = (configFormsArg as { configForms?: unknown } | undefined)?.configForms
176
187
  const face = (svc !== undefined && svc !== null ? svc : configFormsArg) as unknown as ConfigFormsHandle
177
188
  configFormsHandle = typeof face?.get === 'function' ? face : undefined
189
+ // 预热 FAB 读数:不看设置面板也要能读到 monitorPanel.enabled。此前缓存只
190
+ // 在设置分节渲染时刷新,导致浮动监控球必须先打开设置才出现。
191
+ if (configFormsHandle !== undefined) {
192
+ try {
193
+ const form = configFormsHandle.get(ENTRY_ID)
194
+ const refresh = (): void => {
195
+ monitorPanelEnabledCache = decodeSettings(form.getSnapshot().value?.settings)?.monitorPanel?.enabled ?? false
196
+ nativeMonitorReady = true
197
+ }
198
+ refresh()
199
+ form.subscribe(() => { try { refresh() } catch { /* ignore */ } })
200
+ } catch (error) {
201
+ console.warn('[dsh-context-compression-improved] FAB 读数预热失败(沿用桥面):', error)
202
+ }
203
+ }
178
204
  })
179
205
  } catch (error) {
180
206
  console.warn('[dsh-context-compression-improved] configForms 臂挂载失败(桥面继续服务):', error)
@@ -212,6 +238,7 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
212
238
  }
213
239
  }
214
240
  monitorPanelEnabledCache = projected.value?.monitorPanel?.enabled ?? false
241
+ nativeMonitorReady = true
215
242
  return projected
216
243
  },
217
244
  subscribe: (listener) => form.subscribe(listener),
@@ -80,6 +80,7 @@ export const de = {
80
80
  'monitor.panel.cost': 'Kosten (ist / gespart gesch.)',
81
81
  'monitor.panel.intent': 'Intent-Zusammenfassung',
82
82
  'monitor.panel.overrideHint': 'Sitzungs-Übersteuerung',
83
+ 'monitor.panel.overridePrefix': 'Sitzungs-Übersteuerung',
83
84
  'monitor.panel.resume': 'Fortsetzen',
84
85
  'monitor.panel.disable': 'Deaktivieren',
85
86
  'monitor.panel.stateOn': 'ein',
@@ -80,6 +80,7 @@ export const es = {
80
80
  'monitor.panel.cost': 'Coste (real / ahorro est.)',
81
81
  'monitor.panel.intent': 'Resumen de intención',
82
82
  'monitor.panel.overrideHint': 'Invalidación de sesión',
83
+ 'monitor.panel.overridePrefix': 'Invalidación de sesión',
83
84
  'monitor.panel.resume': 'Reanudar',
84
85
  'monitor.panel.disable': 'Desactivar',
85
86
  'monitor.panel.stateOn': 'sí',
@@ -80,6 +80,7 @@ export const fr = {
80
80
  'monitor.panel.cost': 'Coût (réel / écon. est.)',
81
81
  'monitor.panel.intent': 'Résumé d\'intention',
82
82
  'monitor.panel.overrideHint': 'Priorité de session',
83
+ 'monitor.panel.overridePrefix': 'Priorité de session',
83
84
  'monitor.panel.resume': 'Reprendre',
84
85
  'monitor.panel.disable': 'Désactiver',
85
86
  'monitor.panel.stateOn': 'activé',
@@ -80,6 +80,7 @@ export const it = {
80
80
  'monitor.panel.cost': 'Costo (effettivo / stimo)',
81
81
  'monitor.panel.intent': 'Riepilogo di intento',
82
82
  'monitor.panel.overrideHint': 'Override di sessione',
83
+ 'monitor.panel.overridePrefix': 'Override di sessione',
83
84
  'monitor.panel.resume': 'Riprendi',
84
85
  'monitor.panel.disable': 'Disattiva',
85
86
  'monitor.panel.stateOn': 'on',
@@ -80,6 +80,7 @@ export const ja = {
80
80
  'monitor.panel.cost': 'コスト(実績 / 節約概算)',
81
81
  'monitor.panel.intent': 'インテント要約',
82
82
  'monitor.panel.overrideHint': 'セッション上書き',
83
+ 'monitor.panel.overridePrefix': 'セッション上書き',
83
84
  'monitor.panel.resume': '再開',
84
85
  'monitor.panel.disable': '停止',
85
86
  'monitor.panel.stateOn': 'オン',
@@ -80,6 +80,7 @@ export const ko = {
80
80
  'monitor.panel.cost': '비용 (실제 / 절감 추정)',
81
81
  'monitor.panel.intent': '인텐트 요약',
82
82
  'monitor.panel.overrideHint': '세션 재정의',
83
+ 'monitor.panel.overridePrefix': '세션 재정의',
83
84
  'monitor.panel.resume': '재개',
84
85
  'monitor.panel.disable': '중지',
85
86
  'monitor.panel.stateOn': '켬',
@@ -80,6 +80,7 @@ export const ru = {
80
80
  'monitor.panel.cost': 'Стоимость (факт / эконом. оценка)',
81
81
  'monitor.panel.intent': 'Итог намерения',
82
82
  'monitor.panel.overrideHint': 'Приоритет сессии',
83
+ 'monitor.panel.overridePrefix': 'Приоритет сессии',
83
84
  'monitor.panel.resume': 'Возобновить',
84
85
  'monitor.panel.disable': 'Отключить',
85
86
  'monitor.panel.stateOn': 'вкл',