dsh-context-compression-improved 0.9.0 → 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 (38) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/package.json +2 -1
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +1 -0
  5. package/packages/selector/lib/client.js +86 -32
  6. package/packages/selector/lib/config.js +71 -7
  7. package/packages/selector/lib/index.js +120 -20
  8. package/packages/selector/lib/pruner.d.ts +158 -107
  9. package/packages/selector/lib/pruner.js +336 -21
  10. package/packages/selector/package.json +1 -1
  11. package/packages/selector/src/client/index.ts +55 -20
  12. package/packages/selector/src/client/locales/de.ts +1 -0
  13. package/packages/selector/src/client/locales/es.ts +1 -0
  14. package/packages/selector/src/client/locales/fr.ts +1 -0
  15. package/packages/selector/src/client/locales/it.ts +1 -0
  16. package/packages/selector/src/client/locales/ja.ts +1 -0
  17. package/packages/selector/src/client/locales/ko.ts +1 -0
  18. package/packages/selector/src/client/locales/ru.ts +1 -0
  19. package/packages/selector/src/client/locales.ts +2 -0
  20. package/packages/selector/src/client/monitor-fab.ts +19 -4
  21. package/packages/selector/src/preset-overlay.ts +145 -22
  22. package/packages/selector/src/pruner/content.ts +1 -1
  23. package/packages/selector/src/pruner/state.ts +4 -0
  24. package/packages/selector/src/pruner.ts +120 -16
  25. package/packages/selector/src/runtime/config.ts +1 -1
  26. package/packages/selector/src/runtime/measurement.ts +14 -1
  27. package/packages/selector/src/runtime/reducers.ts +81 -1
  28. package/packages/selector/src/runtime/retrieve.ts +4 -3
  29. package/packages/selector/src/runtime/savings-projection.ts +226 -0
  30. package/packages/selector/src/runtime/savings.ts +83 -3
  31. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  32. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  33. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
  34. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  35. package/packages/selector/tests/runtime/savings.spec.ts +22 -3
  36. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  37. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
  38. package/scripts/cell-browser-e2e.mjs +354 -0
@@ -1,10 +1,10 @@
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";
5
5
  import { Service } from "@deepseek-ai/cordis";
6
6
  import { createUserMessage, freezeMessage } from "@deepseek-ai/dsh-llm";
7
- import { SessionSeq, deriveEventMessage } from "@deepseek-ai/dsh-session";
7
+ import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
8
8
  import { readFileSync } from "node:fs";
9
9
  import { Tokenizer } from "@huggingface/tokenizers";
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -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.
@@ -469,6 +469,8 @@ function emptyResult() {
469
469
  }
470
470
  //#endregion
471
471
  //#region src/runtime/measurement.ts
472
+ const dshSessionSoft$1 = dshSessionNamespace;
473
+ const deriveEventMessage = dshSessionSoft$1.deriveEventMessage ?? dshSessionSoft$1.default?.deriveEventMessage ?? (() => null);
472
474
  /**
473
475
  * Character pressure of one model-visible content array, measured on the same
474
476
  * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
@@ -730,17 +732,17 @@ function countSurfaceCounts(counts, subject) {
730
732
  });
731
733
  }
732
734
  z.object({
733
- maxChars: z.number().step(1).min(1).default(5e4),
735
+ maxChars: z.number().step(1).min(1).default(12e3),
734
736
  maxScanChars: z.number().step(1).min(1).default(25e4),
735
737
  maxQueryChars: z.number().step(1).min(1).default(256)
736
738
  });
737
739
  const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/;
738
740
  const MAX_LINES = 1e3;
739
- const DEFAULT_MAX_CHARS = 5e4;
741
+ const DEFAULT_MAX_CHARS = 12e3;
740
742
  const DEFAULT_MAX_SCAN_CHARS = 25e4;
741
743
  const DEFAULT_MAX_QUERY_CHARS = 256;
742
744
  const TRUNCATION_MARKER = "\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n";
743
- 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.";
744
746
  const OUTPUT = {
745
747
  schema: { type: "string" },
746
748
  render: (_args, value) => [{
@@ -1368,6 +1370,11 @@ const ADJACENT_REPEAT_MARKER = "[previous line repeated";
1368
1370
  const NON_ADJACENT_FOLD_THRESHOLD = 3;
1369
1371
  /** Read-output line-number gutter added unconditionally by the host's `formatReadOutput`. */
1370
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;
1371
1378
  /**
1372
1379
  * Block-level read-gutter detection (GF-1). The host prefixes read output with
1373
1380
  * `N: ` line numbers unconditionally and cannot be configured off. The gutter
@@ -1426,7 +1433,8 @@ function reduceFreshToolResult(input, ranking) {
1426
1433
  const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
1427
1434
  const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
1428
1435
  const candidates = [];
1429
- 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));
1430
1438
  if (looksLikeMinified(normalized.contentText)) candidates.push(() => reduceBundledJs(prepared));
1431
1439
  if (toolClass === "search") candidates.push(() => reduceSearch(prepared, ranking?.files));
1432
1440
  if (isGitCommand(name, command)) candidates.push(() => reduceGit(prepared, command));
@@ -1789,6 +1797,76 @@ function reduceJson(input) {
1789
1797
  };
1790
1798
  return null;
1791
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
+ }
1792
1870
  function shrinkJson(value, depth) {
1793
1871
  if (depth >= 5) {
1794
1872
  if (Array.isArray(value)) return `[array length=${String(value.length)} omitted]`;
@@ -3824,6 +3902,177 @@ function dedupePlaceholder(entry, originalChars) {
3824
3902
  ].join(" ");
3825
3903
  }
3826
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
3827
4076
  //#region src/runtime/adaptive-cost.ts
3828
4077
  /**
3829
4078
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
@@ -3965,10 +4214,41 @@ function emitCompressionAudit(logger, record) {
3965
4214
  *
3966
4215
  * @module dsh-context-compression-improved-runtime
3967
4216
  */
4217
+ const dshSessionSoft = dshSessionNamespace;
4218
+ const SessionSeq = dshSessionSoft.SessionSeq ?? dshSessionSoft.default?.SessionSeq ?? ((value) => value);
3968
4219
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
3969
4220
  function originalTextForSavings(candidate) {
3970
4221
  return flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
3971
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
+ }
3972
4252
  /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
3973
4253
  var ToolResultPruner = class extends Service {
3974
4254
  static inject = ["tokenMeter"];
@@ -4013,6 +4293,8 @@ var ToolResultPruner = class extends Service {
4013
4293
  turnClocks: /* @__PURE__ */ new WeakMap(),
4014
4294
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
4015
4295
  advisorChannels: /* @__PURE__ */ new WeakMap(),
4296
+ intentChannels: /* @__PURE__ */ new WeakMap(),
4297
+ projectedSavings: /* @__PURE__ */ new WeakSet(),
4016
4298
  pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4017
4299
  intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4018
4300
  intentBaselines: /* @__PURE__ */ new WeakMap()
@@ -4068,6 +4350,10 @@ var ToolResultPruner = class extends Service {
4068
4350
  try {
4069
4351
  observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
4070
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 {}
4071
4357
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4072
4358
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4073
4359
  this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
@@ -4156,12 +4442,13 @@ var ToolResultPruner = class extends Service {
4156
4442
  if (frozen !== void 0) return frozen;
4157
4443
  const settingsHost = this.ctx.get("settings");
4158
4444
  const settings = settingsHost?.describe?.().find((d) => String(d.ns) === "context-compression-improved-bundle")?.value ?? settingsHost?.get?.("context-compression");
4445
+ const unwrapped = unwrapSettingsEntry(settings);
4159
4446
  let resolved;
4160
4447
  let settingsSource = settings === void 0 ? "plugin-config-fallback" : "host-settings";
4161
4448
  let autoCompactThresholdSource = settings === void 0 ? "schema-default" : "host-settings";
4162
4449
  let settingsInvalidFallback;
4163
4450
  try {
4164
- 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);
4165
4452
  } catch (error) {
4166
4453
  const reason = error instanceof Error ? error.message : String(error);
4167
4454
  this.auditFailure(session, "pressure", "policy-resolution", error);
@@ -4271,7 +4558,7 @@ var ToolResultPruner = class extends Service {
4271
4558
  for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
4272
4559
  if (samples.length >= 3) break;
4273
4560
  if (candidate.event.data.turn === void 0) continue;
4274
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) continue;
4561
+ if (freshBelowTrigger(candidate, policy)) continue;
4275
4562
  const path = toolCallPath(candidate.call.arguments);
4276
4563
  if (path === void 0) continue;
4277
4564
  if (isSupersededRead(events, candidate.seq, path)) continue;
@@ -4402,6 +4689,20 @@ var ToolResultPruner = class extends Service {
4402
4689
  else if (outcome !== void 0) advisorState.failures = void 0;
4403
4690
  }
4404
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
+ /**
4405
4706
  * Fire-and-forget postflight: evaluate the growth gate, and only when it
4406
4707
  * passes, select the consumed increment OUTSIDE the protected working set,
4407
4708
  * mask it to semantic-role records, and spend ONE summary-writer call. The
@@ -4434,7 +4735,20 @@ var ToolResultPruner = class extends Service {
4434
4735
  }).decision) return;
4435
4736
  const settingsPreset = settings.presetOptions;
4436
4737
  if (settingsPreset === void 0) return;
4437
- 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)) {
4438
4752
  emitCompressionAudit(this.ctx.logger, {
4439
4753
  schemaVersion: 1,
4440
4754
  kind: "intent-summary-outcome",
@@ -4473,14 +4787,14 @@ var ToolResultPruner = class extends Service {
4473
4787
  if (records.length === 0) return;
4474
4788
  const events = sessionEvents(session);
4475
4789
  const task = collectTaskSemantics(events);
4476
- let channel = this.state.advisorChannels.get(session);
4790
+ let channel = this.state.intentChannels.get(session);
4477
4791
  if (channel === void 0) {
4478
4792
  channel = new SideChannel(this.ctx, settingsPreset, {
4479
- mode: "direct",
4793
+ mode: estimatorMode,
4480
4794
  timeoutMs: 3e4,
4481
4795
  maxTokens: 512
4482
4796
  });
4483
- this.state.advisorChannels.set(session, channel);
4797
+ this.state.intentChannels.set(session, channel);
4484
4798
  }
4485
4799
  const answer = await channel.ask({
4486
4800
  system: buildIntentSummarySystemPrompt(),
@@ -4944,8 +5258,7 @@ var ToolResultPruner = class extends Service {
4944
5258
  const plans = /* @__PURE__ */ new Map();
4945
5259
  let freshPlanned = 0;
4946
5260
  const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
4947
- const candidateChars = candidates.map((candidate) => candidate.characterPressure);
4948
- 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)));
4949
5262
  if (policy.freshEnabled) {
4950
5263
  if (candidates.some((candidate) => candidate.call.name !== "context_compression_retrieve" && candidate.count.kind !== "exact-tokenizer")) this.warnExactUnavailable(session, view, "fresh");
4951
5264
  for (const candidate of candidates) {
@@ -4988,9 +5301,9 @@ var ToolResultPruner = class extends Service {
4988
5301
  const landed = this.landAll(session, this.adviseReplacements(session, policy, freshCandidates, "fresh"));
4989
5302
  const freshLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "fresh");
4990
5303
  const aggregateLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "aggregate");
4991
- 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", {
4992
5305
  measurementKind: "characters",
4993
- ...maxCandidateChars === void 0 ? {} : { currentTokens: charsToTokens(maxCandidateChars) },
5306
+ ...maxCandidateTokens === void 0 ? {} : { currentTokens: maxCandidateTokens },
4994
5307
  triggerTokens: policy.freshTriggerTokens,
4995
5308
  targetTokens: policy.freshTargetTokens
4996
5309
  });
@@ -5065,7 +5378,7 @@ var ToolResultPruner = class extends Service {
5065
5378
  if (typeof candidate.event.surfaceOp === "object") return null;
5066
5379
  const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
5067
5380
  if (text === void 0) return null;
5068
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null;
5381
+ if (freshBelowTrigger(candidate, policy)) return null;
5069
5382
  let table = this.state.dedupeTables.get(session);
5070
5383
  if (table === void 0) {
5071
5384
  table = new DedupeTable();
@@ -5093,7 +5406,7 @@ var ToolResultPruner = class extends Service {
5093
5406
  planFresh(candidate, session, policy, view) {
5094
5407
  if (typeof candidate.event.surfaceOp === "object") return null;
5095
5408
  const resultView = viewToolResult(candidate.event.data.message);
5096
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null;
5409
+ if (freshBelowTrigger(candidate, policy)) return null;
5097
5410
  const sourceSeq = candidate.seq;
5098
5411
  const sourceRef$1 = sourceRef(session, sourceSeq);
5099
5412
  const textBlock = onlyTextBlock(resultView.blocks);
@@ -5136,7 +5449,7 @@ var ToolResultPruner = class extends Service {
5136
5449
  "[Tool result reduced to satisfy the completed-step aggregate budget]",
5137
5450
  `tool: ${candidate.call.name}`,
5138
5451
  `source: ${sourceRef$2}`,
5139
- "Use context_compression_retrieve with this source if the omitted evidence is necessary."
5452
+ "Retrieve a narrow slice via context_compression_retrieve if needed."
5140
5453
  ].join("\n");
5141
5454
  const plan = this.plan(candidate, [{
5142
5455
  type: "text",
@@ -5469,6 +5782,7 @@ var ToolResultPruner = class extends Service {
5469
5782
  tokensAfter,
5470
5783
  basis: exact ? "exact-tokenizer" : "characters",
5471
5784
  sourceSeq: manifestSeq,
5785
+ replacementSeq: Number(replacement.seq),
5472
5786
  originalText: groupText
5473
5787
  });
5474
5788
  return;
@@ -5610,6 +5924,7 @@ var ToolResultPruner = class extends Service {
5610
5924
  tokensAfter: plan.tokensAfter,
5611
5925
  basis: plan.measurementBasis,
5612
5926
  sourceSeq: plan.sourceSeq,
5927
+ replacementSeq: Number(replacement.seq),
5613
5928
  ...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
5614
5929
  });
5615
5930
  return {
@@ -5782,4 +6097,4 @@ var ToolResultPruner = class extends Service {
5782
6097
  }
5783
6098
  };
5784
6099
  //#endregion
5785
- 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.0",
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",