dsh-context-compression-improved 0.15.2 → 0.15.4

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.
@@ -1,13 +1,49 @@
1
1
  import { l as sessionEvents, n as viewToolResult, s as RUNTIME_TOOL_NAMES } from "./tool-result.js";
2
+ import { createRequire } from "node:module";
2
3
  import z from "@deepseek-ai/schemastery";
3
4
  import { createHash } from "node:crypto";
4
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
5
6
  import { homedir } from "node:os";
6
7
  import { dirname, join, resolve } from "node:path";
7
8
  import { Tokenizer } from "@huggingface/tokenizers";
8
9
  import zlib from "node:zlib";
9
10
  import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
10
11
  import { mkdir } from "node:fs/promises";
12
+ //#region \0rolldown/runtime.js
13
+ var __defProp = Object.defineProperty;
14
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
+ var __getOwnPropNames = Object.getOwnPropertyNames;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __esmMin = (fn, res, err) => () => {
18
+ if (err) throw err[0];
19
+ try {
20
+ return fn && (res = fn(fn = 0)), res;
21
+ } catch (e) {
22
+ throw err = [e], e;
23
+ }
24
+ };
25
+ var __exportAll = (all, no_symbols) => {
26
+ let target = {};
27
+ for (var name in all) __defProp(target, name, {
28
+ get: all[name],
29
+ enumerable: true
30
+ });
31
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
32
+ return target;
33
+ };
34
+ var __copyProps = (to, from, except, desc) => {
35
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
36
+ key = keys[i];
37
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
38
+ get: ((k) => from[k]).bind(null, key),
39
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
40
+ });
41
+ }
42
+ return to;
43
+ };
44
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
45
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
46
+ //#endregion
11
47
  //#region src/runtime/savings.ts
12
48
  /**
13
49
  * 节省统计账本(诚实口径)。
@@ -4696,4 +4732,84 @@ function formatFemtoUnits(value) {
4696
4732
  return fraction.length === 0 ? whole : `${whole}.${fraction}`;
4697
4733
  }
4698
4734
  //#endregion
4699
- export { isValidAutoCompactThresholdPercent as $, officialRequestUsage as A, recordIntentFold as At, unavailableCount as B, resolveStatsDshHome as C, evaluateIntentGate as Ct, dedupePlaceholder as D, getSummaryOverride as Dt, dedupeHash as E, getObservedIntentEnabled as Et, onlyTextBlocks as F, decimalRateNanoUnits as Ft, ContextCompressionSettingsSchema as G, countOmittedLines as H, pressureCost as I, priceOfficialDeepSeekUsage as It, PRUNE_MARKER as J, DEFAULTS as K, recoveryMarker as L, resolveOfficialDeepSeekPrice as Lt, emptyResult as M, recordScore as Mt, nativePruneContent as N, setSummaryOverride as Nt, flattenPlainText as O, invalidateOnTaskChange as Ot, onlyTextBlock as P, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as Pt, isCompressionProfile as Q, sameProviderMeasurementKey as R, getSavingsLedger as Rt, statsPersistenceState as S, INTENT_GATE_GROWTH_TOKENS as St, DedupeTable as T, getLastIntentFold as Tt, AUTO_COMPACT_THRESHOLD_LIMITS as U, CAPACITY_PRESSURE_RATIO as V, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as W, charsToTokens as X, charsForTokens as Y, codePointLength as Z, scheduleUsageFlush as _, isSessionOverrideAction as _t, getStatsBackfillStatus as a, resolveCustomPolicy as at, ensureStatsStore as b, setSedimentObservation as bt, pauseStatsBackfill as c, COMPRESSION_PROFILES as ct, claimFromLand as d, decodeSessionLogBytes as dt, parseContextCompressionSettings as et, claimOffset as f, deepSeekV4TokenizerForModel as ft, reclaimFromTailTrim as g, estimateSavingsPricing as gt, getStatsActiveSessionId as h, drsTotalsFragment as ht, discoverBackfillSessionLogs as i, DEFAULT_CUSTOM_COMPRESSION_POLICY as it, countToolContent as j, recordRecertified as jt, measureForCompaction as k, observeIntentEnabled as kt, resumeStatsBackfill as l, countExactCanonicalTextFields as lt, flushUsageOnDispose as m, buildMonitorSnapshot as mt, sampleIntegralBoundary as n, resolvePolicy as nt, kickStatsBackfillOnDispose as o, assertNever as ot, flushPendingUsageNow as p, applySessionOverride as pt, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as q, configureStatsBackfillTrigger as r, CustomCompressionPolicySchema as rt, kickStatsBackfillOnRouteHit as s, deepFreeze as st, estimateIntegralMoney as t, resolveConfig as tt, cancelPendingUsageFlushes as u, unavailableTokenCount as ut, setStatsLivePathBusy as v, mergeCompositionByComponent as vt, projectSessionSavings as w, getAdvisorState as wt, getStatsStore as x, INTENT_GATE_FLOOR_FRACTION as xt, closeStatsStore as y, observeContextUsage as yt, summarize as z };
4735
+ //#region src/runtime/cut-index.ts
4736
+ /**
4737
+ * Per-cut audit index (F2).
4738
+ *
4739
+ * Plan: cci-longterm-refactor v0.13.3
4740
+ *
4741
+ * Appends one JSON line per published cut to ~/.dsh/storages/dsh-context-compression/cuts-<sessionId>.jsonl.
4742
+ * Provides O(1) audit history without storing original content — only metadata.
4743
+ *
4744
+ * Fire-and-forget: write failure warns but never blocks the cut.
4745
+ *
4746
+ * @module dsh-context-compression-improved/runtime/cut-index
4747
+ */
4748
+ var cut_index_exports = /* @__PURE__ */ __exportAll({
4749
+ MAX_LINES_PER_SESSION: () => MAX_LINES_PER_SESSION,
4750
+ appendCut: () => appendCut,
4751
+ readCuts: () => readCuts
4752
+ });
4753
+ /** Storage directory resolver (lazy, creates if missing). */
4754
+ function getStagingDir() {
4755
+ const dshHome = process.env.DSH_HOME ?? join(process.env.USERPROFILE || process.env.HOME || "", ".dsh");
4756
+ return join(dshHome, "storages", "dsh-context-compression");
4757
+ }
4758
+ function cutsFilePath(sessionId) {
4759
+ return join(getStagingDir(), `cuts-${sessionId}.jsonl`);
4760
+ }
4761
+ /**
4762
+ * Append one cut entry to the session's index file.
4763
+ * Fire-and-forget: catches all errors, warns, never throws.
4764
+ */
4765
+ function appendCut(entry) {
4766
+ try {
4767
+ const dir = getStagingDir();
4768
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4769
+ const filePath = cutsFilePath(entry.sessionId);
4770
+ const line = JSON.stringify(entry) + "\n";
4771
+ appendFileSync(filePath, line, {
4772
+ encoding: "utf8",
4773
+ flag: "a"
4774
+ });
4775
+ enforceLimit(filePath);
4776
+ } catch (err) {
4777
+ console.warn("[cci-cut-index] write failed, skipping:", err instanceof Error ? err.message : String(err));
4778
+ }
4779
+ }
4780
+ /**
4781
+ * Read cut entries for a session (most recent first, up to limit).
4782
+ */
4783
+ function readCuts(sessionId, opts) {
4784
+ const filePath = cutsFilePath(sessionId);
4785
+ if (!existsSync(filePath)) return [];
4786
+ try {
4787
+ const lines = readFileSync(filePath, "utf8").split("\n").filter(Boolean);
4788
+ let entries = [];
4789
+ for (const line of lines) try {
4790
+ entries.push(JSON.parse(line));
4791
+ } catch {}
4792
+ entries.reverse();
4793
+ if (opts?.strategy !== void 0) entries = entries.filter((e) => e.strategy === opts.strategy);
4794
+ if (opts?.limit !== void 0 && opts.limit > 0) entries = entries.slice(0, opts.limit);
4795
+ return entries;
4796
+ } catch {
4797
+ return [];
4798
+ }
4799
+ }
4800
+ /** Enforce the per-session line limit by truncating oldest half. */
4801
+ function enforceLimit(filePath) {
4802
+ try {
4803
+ const lines = readFileSync(filePath, "utf8").split("\n").filter(Boolean);
4804
+ if (lines.length <= 2e3) return;
4805
+ const kept = lines.slice(Math.floor(lines.length / 2));
4806
+ const { writeFileSync } = __require("node:fs");
4807
+ writeFileSync(filePath, kept.join("\n") + "\n", "utf8");
4808
+ } catch {}
4809
+ }
4810
+ var MAX_LINES_PER_SESSION;
4811
+ var init_cut_index = __esmMin((() => {
4812
+ MAX_LINES_PER_SESSION = 2e3;
4813
+ }));
4814
+ //#endregion
4815
+ export { charsToTokens as $, dedupePlaceholder as A, getSummaryOverride as At, recoveryMarker as B, resolveOfficialDeepSeekPrice as Bt, ensureStatsStore as C, setSedimentObservation as Ct, projectSessionSavings as D, getAdvisorState as Dt, resolveStatsDshHome as E, evaluateIntentGate as Et, emptyResult as F, recordScore as Ft, countOmittedLines as G, summarize as H, __toCommonJS as Ht, nativePruneContent as I, setSummaryOverride as It, ContextCompressionSettingsSchema as J, AUTO_COMPACT_THRESHOLD_LIMITS as K, onlyTextBlock as L, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as Lt, measureForCompaction as M, observeIntentEnabled as Mt, officialRequestUsage as N, recordIntentFold as Nt, DedupeTable as O, getLastIntentFold as Ot, countToolContent as P, recordRecertified as Pt, charsForTokens as Q, onlyTextBlocks as R, decimalRateNanoUnits as Rt, closeStatsStore as S, observeContextUsage as St, statsPersistenceState as T, INTENT_GATE_GROWTH_TOKENS as Tt, unavailableCount as U, sameProviderMeasurementKey as V, getSavingsLedger as Vt, CAPACITY_PRESSURE_RATIO as W, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as X, DEFAULTS as Y, PRUNE_MARKER as Z, flushUsageOnDispose as _, buildMonitorSnapshot as _t, sampleIntegralBoundary as a, resolvePolicy as at, scheduleUsageFlush as b, isSessionOverrideAction as bt, getStatsBackfillStatus as c, resolveCustomPolicy as ct, pauseStatsBackfill as d, COMPRESSION_PROFILES as dt, codePointLength as et, resumeStatsBackfill as f, countExactCanonicalTextFields as ft, flushPendingUsageNow as g, applySessionOverride as gt, claimOffset as h, deepSeekV4TokenizerForModel as ht, estimateIntegralMoney as i, resolveConfig as it, flattenPlainText as j, invalidateOnTaskChange as jt, dedupeHash as k, getObservedIntentEnabled as kt, kickStatsBackfillOnDispose as l, assertNever as lt, claimFromLand as m, decodeSessionLogBytes as mt, cut_index_exports as n, isValidAutoCompactThresholdPercent as nt, configureStatsBackfillTrigger as o, CustomCompressionPolicySchema as ot, cancelPendingUsageFlushes as p, unavailableTokenCount as pt, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as q, init_cut_index as r, parseContextCompressionSettings as rt, discoverBackfillSessionLogs as s, DEFAULT_CUSTOM_COMPRESSION_POLICY as st, appendCut as t, isCompressionProfile as tt, kickStatsBackfillOnRouteHit as u, deepFreeze as ut, getStatsActiveSessionId as v, drsTotalsFragment as vt, getStatsStore as w, INTENT_GATE_FLOOR_FRACTION as wt, setStatsLivePathBusy as x, mergeCompositionByComponent as xt, reclaimFromTailTrim as y, estimateSavingsPricing as yt, pressureCost as z, priceOfficialDeepSeekUsage as zt };
@@ -1,4 +1,4 @@
1
- import { C as resolveStatsDshHome, Dt as getSummaryOverride, Et as getObservedIntentEnabled, G as ContextCompressionSettingsSchema, Lt as resolveOfficialDeepSeekPrice, Nt as setSummaryOverride, Rt as getSavingsLedger, S as statsPersistenceState, St as INTENT_GATE_GROWTH_TOKENS, Tt as getLastIntentFold, W as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, _t as isSessionOverrideAction, a as getStatsBackfillStatus, b as ensureStatsStore, c as pauseStatsBackfill, dt as decodeSessionLogBytes, ft as deepSeekV4TokenizerForModel, gt as estimateSavingsPricing, h as getStatsActiveSessionId, ht as drsTotalsFragment, i as discoverBackfillSessionLogs, l as resumeStatsBackfill, mt as buildMonitorSnapshot, p as flushPendingUsageNow, pt as applySessionOverride, q as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, r as configureStatsBackfillTrigger, s as kickStatsBackfillOnRouteHit, t as estimateIntegralMoney, u as cancelPendingUsageFlushes, ut as unavailableTokenCount, vt as mergeCompositionByComponent, wt as getAdvisorState, x as getStatsStore, xt as INTENT_GATE_FLOOR_FRACTION, y as closeStatsStore } from "./savings-integral.js";
1
+ import { At as getSummaryOverride, Bt as resolveOfficialDeepSeekPrice, C as ensureStatsStore, Dt as getAdvisorState, E as resolveStatsDshHome, Ht as __toCommonJS, It as setSummaryOverride, J as ContextCompressionSettingsSchema, Ot as getLastIntentFold, S as closeStatsStore, T as statsPersistenceState, Tt as INTENT_GATE_GROWTH_TOKENS, Vt as getSavingsLedger, X as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, _t as buildMonitorSnapshot, bt as isSessionOverrideAction, c as getStatsBackfillStatus, d as pauseStatsBackfill, f as resumeStatsBackfill, g as flushPendingUsageNow, gt as applySessionOverride, ht as deepSeekV4TokenizerForModel, i as estimateIntegralMoney, kt as getObservedIntentEnabled, mt as decodeSessionLogBytes, n as cut_index_exports, o as configureStatsBackfillTrigger, p as cancelPendingUsageFlushes, pt as unavailableTokenCount, q as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, r as init_cut_index, s as discoverBackfillSessionLogs, u as kickStatsBackfillOnRouteHit, v as getStatsActiveSessionId, vt as drsTotalsFragment, w as getStatsStore, wt as INTENT_GATE_FLOOR_FRACTION, xt as mergeCompositionByComponent, yt as estimateSavingsPricing } from "./cut-index.js";
2
2
  import { a as noteResolvedSettingsService, i as detectHostGeneration, r as compatLog } from "./tool-result.js";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import { createHash } from "node:crypto";
@@ -1597,6 +1597,7 @@ const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advis
1597
1597
  const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
1598
1598
  const MONITOR_ROUTES = ["/endpoint/dsh-context-compression-improved/monitor", "/api/dsh-context-compression-improved/monitor"];
1599
1599
  const SAVINGS_SESSIONS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings/sessions", "/api/dsh-context-compression-improved/savings/sessions"];
1600
+ const CUTS_ROUTES = ["/endpoint/dsh-context-compression-improved/cuts", "/api/dsh-context-compression-improved/cuts"];
1600
1601
  function sessionFor(readService, sessionId) {
1601
1602
  const agents = readService("agents");
1602
1603
  return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
@@ -2246,6 +2247,49 @@ const Config = z.object({
2246
2247
  advisorReportRoute: z.boolean().default(false),
2247
2248
  settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile()
2248
2249
  });
2250
+ /** F2: Register the per-cut audit index read-only route. */
2251
+ function registerCutsRoute(ctx) {
2252
+ const readService = (name) => {
2253
+ try {
2254
+ return ctx.get(name);
2255
+ } catch {
2256
+ return;
2257
+ }
2258
+ };
2259
+ const handler = (req, res) => {
2260
+ try {
2261
+ const url = new URL(req.url ?? "/", "http://localhost");
2262
+ const sessionId = url.searchParams.get("session") ?? "";
2263
+ const limit = Math.min(Number(url.searchParams.get("limit") ?? "500"), 2e3);
2264
+ const strategy = url.searchParams.get("strategy") ?? void 0;
2265
+ const { readCuts } = (init_cut_index(), __toCommonJS(cut_index_exports));
2266
+ jsonResponse(res, 200, sessionId ? readCuts(sessionId, {
2267
+ limit,
2268
+ ...strategy ? { strategy } : {}
2269
+ }) : []);
2270
+ } catch (err) {
2271
+ jsonResponse(res, 500, { error: String(err) });
2272
+ }
2273
+ };
2274
+ const webServer = readService("webServer");
2275
+ if (webServer?.register === void 0) {
2276
+ ctx.inject(["webServer"], (inj) => {
2277
+ const ws = inj.webServer;
2278
+ if (ws?.register === void 0) return;
2279
+ for (const path of CUTS_ROUTES) ws.register({
2280
+ kind: "exact",
2281
+ path,
2282
+ handler
2283
+ });
2284
+ });
2285
+ return;
2286
+ }
2287
+ for (const path of CUTS_ROUTES) webServer.register({
2288
+ kind: "exact",
2289
+ path,
2290
+ handler
2291
+ });
2292
+ }
2249
2293
  /** Register the persisted default read by the currently mounted root pruner. */
2250
2294
  function apply(ctx, config = {}) {
2251
2295
  ctx.inject?.(["commands"], (scope) => {
@@ -2270,6 +2314,7 @@ function apply(ctx, config = {}) {
2270
2314
  registerMonitorRoute(ctx);
2271
2315
  registerSavingsSessionsRoute(ctx);
2272
2316
  registerPanelCommand(ctx);
2317
+ registerCutsRoute(ctx);
2273
2318
  ctx.effect(() => () => {
2274
2319
  cancelPendingUsageFlushes();
2275
2320
  closeStatsStore();
@@ -166,6 +166,16 @@ interface ContextCompressionSettings {
166
166
  * F19 (v0.14.6): Enable self-update pre-download checking.
167
167
  */
168
168
  updateCheck?: boolean;
169
+ /**
170
+ * F3 (v0.13.4): CardMerge settings (中刀, default disabled).
171
+ */
172
+ cardMerge?: {
173
+ enabled: boolean;
174
+ mergeMaxCards?: number;
175
+ mergeMinTokens?: number;
176
+ mergeBreakEven?: number;
177
+ mergeCooldownMs?: number;
178
+ };
169
179
  }
170
180
  //#endregion
171
181
  export { PresetOptionsSettings as i, ContextCompressionSettings as n, CustomCompressionPolicy as r, CompressionProfile as t };
@@ -221,6 +221,18 @@ interface ContextCompressionSettings {
221
221
  monitorPanel?: MonitorPanelSettings;
222
222
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
223
223
  presetOptions?: PresetOptionsSettings;
224
+ /** F1 (v0.13.2): Minimum net-gain threshold; 0 disables. */
225
+ minNetGain?: number;
226
+ /** F8 (v0.15.5): Zero-copy mode — CCI never writes shadow copies. */
227
+ zeroCopy?: boolean;
228
+ /** F3 (v0.13.4): CardMerge settings (中刀). */
229
+ cardMerge?: {
230
+ enabled: boolean;
231
+ mergeMaxCards?: number;
232
+ mergeMinTokens?: number;
233
+ mergeBreakEven?: number;
234
+ mergeCooldownMs?: number;
235
+ };
224
236
  }
225
237
  /** Token-gated policy with character fields limited to reducer candidate shape. */
226
238
  interface ToolResultPruneConfig {
@@ -1,16 +1,12 @@
1
- import { $ as isValidAutoCompactThresholdPercent, A as officialRequestUsage, At as recordIntentFold, B as unavailableCount, Ct as evaluateIntentGate, D as dedupePlaceholder, Dt as getSummaryOverride, E as dedupeHash, F as onlyTextBlocks, Ft as decimalRateNanoUnits, G as ContextCompressionSettingsSchema, H as countOmittedLines, I as pressureCost, It as priceOfficialDeepSeekUsage, J as PRUNE_MARKER, K as DEFAULTS, L as recoveryMarker, Lt as resolveOfficialDeepSeekPrice, M as emptyResult, Mt as recordScore, N as nativePruneContent, O as flattenPlainText, Ot as invalidateOnTaskChange, P as onlyTextBlock, Pt as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, Q as isCompressionProfile, R as sameProviderMeasurementKey, Rt as getSavingsLedger, T as DedupeTable, U as AUTO_COMPACT_THRESHOLD_LIMITS, V as CAPACITY_PRESSURE_RATIO, W as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, X as charsToTokens, Y as charsForTokens, Z as codePointLength, _ as scheduleUsageFlush, at as resolveCustomPolicy, bt as setSedimentObservation, ct as COMPRESSION_PROFILES, d as claimFromLand, et as parseContextCompressionSettings, f as claimOffset, ft as deepSeekV4TokenizerForModel, g as reclaimFromTailTrim, it as DEFAULT_CUSTOM_COMPRESSION_POLICY, j as countToolContent, jt as recordRecertified, k as measureForCompaction, kt as observeIntentEnabled, lt as countExactCanonicalTextFields, m as flushUsageOnDispose, n as sampleIntegralBoundary, nt as resolvePolicy, o as kickStatsBackfillOnDispose, ot as assertNever, rt as CustomCompressionPolicySchema, st as deepFreeze, tt as resolveConfig, v as setStatsLivePathBusy, w as projectSessionSavings, wt as getAdvisorState, yt as observeContextUsage, z as summarize } from "./savings-integral.js";
1
+ import { $ as charsToTokens, A as dedupePlaceholder, At as getSummaryOverride, B as recoveryMarker, Bt as resolveOfficialDeepSeekPrice, Ct as setSedimentObservation, D as projectSessionSavings, Dt as getAdvisorState, Et as evaluateIntentGate, F as emptyResult, Ft as recordScore, G as countOmittedLines, H as summarize, I as nativePruneContent, J as ContextCompressionSettingsSchema, K as AUTO_COMPACT_THRESHOLD_LIMITS, L as onlyTextBlock, Lt as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, M as measureForCompaction, Mt as observeIntentEnabled, N as officialRequestUsage, Nt as recordIntentFold, O as DedupeTable, P as countToolContent, Pt as recordRecertified, Q as charsForTokens, R as onlyTextBlocks, Rt as decimalRateNanoUnits, St as observeContextUsage, U as unavailableCount, V as sameProviderMeasurementKey, Vt as getSavingsLedger, W as CAPACITY_PRESSURE_RATIO, Y as DEFAULTS, Z as PRUNE_MARKER, _ as flushUsageOnDispose, a as sampleIntegralBoundary, at as resolvePolicy, b as scheduleUsageFlush, ct as resolveCustomPolicy, dt as COMPRESSION_PROFILES, et as codePointLength, ft as countExactCanonicalTextFields, h as claimOffset, ht as deepSeekV4TokenizerForModel, it as resolveConfig, j as flattenPlainText, jt as invalidateOnTaskChange, k as dedupeHash, l as kickStatsBackfillOnDispose, lt as assertNever, m as claimFromLand, nt as isValidAutoCompactThresholdPercent, ot as CustomCompressionPolicySchema, q as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, r as init_cut_index, rt as parseContextCompressionSettings, st as DEFAULT_CUSTOM_COMPRESSION_POLICY, t as appendCut, tt as isCompressionProfile, ut as deepFreeze, x as setStatsLivePathBusy, y as reclaimFromTailTrim, z as pressureCost, zt as priceOfficialDeepSeekUsage } from "./cut-index.js";
2
2
  import { c as eventBySeq, l as sessionEvents, n as viewToolResult, o as PTC_BINDING_NOTE, s as RUNTIME_TOOL_NAMES, t as compressionMessageSource } from "./tool-result.js";
3
3
  import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as createUserMessage, r as tailTrimRef, s as freezeMessage, t as parseTailTrimRef } from "./tail-trim.js";
4
- import { createRequire } from "node:module";
5
4
  import z from "@deepseek-ai/schemastery";
6
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
7
- import path, { join } from "node:path";
5
+ import path from "node:path";
8
6
  import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
9
7
  import fs from "node:fs/promises";
10
8
  import { Service } from "@deepseek-ai/cordis";
11
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
- //#region \0rolldown/runtime.js
13
- var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
14
10
  z.object({
15
11
  maxChars: z.number().step(1).min(1).default(12e3),
16
12
  maxScanChars: z.number().step(1).min(1).default(25e4),
@@ -4527,45 +4523,9 @@ function checkNetGain(tokensBefore, tokensAfter, minNetGain) {
4527
4523
  if (minNetGain <= 0) return true;
4528
4524
  return tokensBefore - tokensAfter - 80 >= minNetGain;
4529
4525
  }
4530
- /** Storage directory resolver (lazy, creates if missing). */
4531
- function getStagingDir() {
4532
- const dshHome = process.env.DSH_HOME ?? join(process.env.USERPROFILE || process.env.HOME || "", ".dsh");
4533
- return join(dshHome, "storages", "dsh-context-compression");
4534
- }
4535
- function cutsFilePath(sessionId) {
4536
- return join(getStagingDir(), `cuts-${sessionId}.jsonl`);
4537
- }
4538
- /**
4539
- * Append one cut entry to the session's index file.
4540
- * Fire-and-forget: catches all errors, warns, never throws.
4541
- */
4542
- function appendCut(entry) {
4543
- try {
4544
- const dir = getStagingDir();
4545
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4546
- const filePath = cutsFilePath(entry.sessionId);
4547
- const line = JSON.stringify(entry) + "\n";
4548
- appendFileSync(filePath, line, {
4549
- encoding: "utf8",
4550
- flag: "a"
4551
- });
4552
- enforceLimit(filePath);
4553
- } catch (err) {
4554
- console.warn("[cci-cut-index] write failed, skipping:", err instanceof Error ? err.message : String(err));
4555
- }
4556
- }
4557
- /** Enforce the per-session line limit by truncating oldest half. */
4558
- function enforceLimit(filePath) {
4559
- try {
4560
- const lines = readFileSync(filePath, "utf8").split("\n").filter(Boolean);
4561
- if (lines.length <= 2e3) return;
4562
- const kept = lines.slice(Math.floor(lines.length / 2));
4563
- const { writeFileSync } = __require("node:fs");
4564
- writeFileSync(filePath, kept.join("\n") + "\n", "utf8");
4565
- } catch {}
4566
- }
4567
4526
  //#endregion
4568
4527
  //#region src/runtime/adaptive-cost.ts
4528
+ init_cut_index();
4569
4529
  /**
4570
4530
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
4571
4531
  * request-level cache split to individual messages. Removed tokens are not
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.15.2",
3
+ "version": "0.15.4",
4
4
  "description": "Token-saving context-compression selector bundle for DeepSeek Harness — fewer tool-result tokens on every turn, fully auditable",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -75,6 +75,12 @@ const SAVINGS_SESSIONS_ROUTES = [
75
75
  '/api/dsh-context-compression-improved/savings/sessions',
76
76
  ] as const
77
77
 
78
+ // F2 (v0.13.3): Per-cut audit index route (read-only).
79
+ const CUTS_ROUTES = [
80
+ '/endpoint/dsh-context-compression-improved/cuts',
81
+ '/api/dsh-context-compression-improved/cuts',
82
+ ] as const
83
+
78
84
  /** Minimal face of the agents service: session id → agent (carrying the session). */
79
85
  interface AgentsServiceLike {
80
86
  get?(id: unknown): { session?: unknown } | undefined
@@ -789,6 +795,37 @@ export const Config = z.object({
789
795
  settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
790
796
  }) as unknown as z<Config>
791
797
 
798
+ /** F2: Register the per-cut audit index read-only route. */
799
+ function registerCutsRoute(ctx: Context): void {
800
+ const readService = (name: string): unknown => {
801
+ try { return (ctx as unknown as { get: (s: string) => unknown }).get(name) } catch { return undefined }
802
+ }
803
+ const handler = (req: unknown, res: unknown) => {
804
+ try {
805
+ const url = new URL((req as { url?: string }).url ?? '/', 'http://localhost')
806
+ const sessionId = url.searchParams.get('session') ?? ''
807
+ const limit = Math.min(Number(url.searchParams.get('limit') ?? '500'), 2000)
808
+ const strategy = url.searchParams.get('strategy') ?? undefined
809
+ // Dynamic import to avoid circular dependency
810
+ const { readCuts } = require('./runtime/cut-index.ts') as { readCuts: (id: string, opts?: { limit?: number; strategy?: string }) => unknown[] }
811
+ const cuts = sessionId ? readCuts(sessionId, { limit, ...(strategy ? { strategy: strategy as never } : {}) }) : []
812
+ jsonResponse(res, 200, cuts)
813
+ } catch (err) {
814
+ jsonResponse(res, 500, { error: String(err) })
815
+ }
816
+ }
817
+ const webServer = readService('webServer') as { register?: (opts: { kind: string; path: string; handler: (...args: unknown[]) => void }) => (() => void) | void } | undefined
818
+ if (webServer?.register === undefined) {
819
+ ctx.inject(['webServer'], (inj) => {
820
+ const ws = (inj as { webServer?: { register?: (opts: { kind: string; path: string; handler: (...args: unknown[]) => void }) => (() => void) | void } }).webServer
821
+ if (ws?.register === undefined) return
822
+ for (const path of CUTS_ROUTES) ws.register({ kind: 'exact', path, handler: handler as never })
823
+ })
824
+ return
825
+ }
826
+ for (const path of CUTS_ROUTES) webServer.register({ kind: 'exact', path, handler: handler as never })
827
+ }
828
+
792
829
  /** Register the persisted default read by the currently mounted root pruner. */
793
830
  export function apply(ctx: Context, config: Config = {}): void {
794
831
  // ── dsh-tui 终端面:`/compress` ──────────────────────────────────
@@ -825,6 +862,7 @@ export function apply(ctx: Context, config: Config = {}): void {
825
862
  // T24:per-session 分页面板数据面;/ccip(T29)实时控制命令。
826
863
  registerSavingsSessionsRoute(ctx)
827
864
  registerPanelCommand(ctx)
865
+ registerCutsRoute(ctx)
828
866
 
829
867
  // 持久层主干生命周期(spec T5):open 后台 arm 不阻塞 apply(WAL 半事务
830
868
  // 由 SQLite 在 open 时自动恢复,故 recover 并入 open);close 挂 ctx.effect
@@ -467,6 +467,10 @@ export interface ContextCompressionSettings {
467
467
  * F19 (v0.14.6): Enable self-update pre-download checking.
468
468
  */
469
469
  updateCheck?: boolean
470
+ /**
471
+ * F3 (v0.13.4): CardMerge settings (中刀, default disabled).
472
+ */
473
+ cardMerge?: { enabled: boolean; mergeMaxCards?: number; mergeMinTokens?: number; mergeBreakEven?: number; mergeCooldownMs?: number }
470
474
  }
471
475
 
472
476
  /**
@@ -223,6 +223,12 @@ export interface ContextCompressionSettings {
223
223
  monitorPanel?: MonitorPanelSettings
224
224
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
225
225
  presetOptions?: PresetOptionsSettings
226
+ /** F1 (v0.13.2): Minimum net-gain threshold; 0 disables. */
227
+ minNetGain?: number
228
+ /** F8 (v0.15.5): Zero-copy mode — CCI never writes shadow copies. */
229
+ zeroCopy?: boolean
230
+ /** F3 (v0.13.4): CardMerge settings (中刀). */
231
+ cardMerge?: { enabled: boolean; mergeMaxCards?: number; mergeMinTokens?: number; mergeBreakEven?: number; mergeCooldownMs?: number }
226
232
  }
227
233
 
228
234
  /** Token-gated policy with character fields limited to reducer candidate shape. */
@@ -116,7 +116,7 @@ describe('estimator catalog route registration', () => {
116
116
  apply(runtime, { estimatorCatalogRoute: true })
117
117
  await settle()
118
118
 
119
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE])
119
+ expect(routes.map(route => route.path).sort()).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE, '/endpoint/dsh-context-compression-improved/cuts', '/api/dsh-context-compression-improved/cuts'].sort())
120
120
  expect(routes.every(route => route.kind === 'exact')).toBe(true)
121
121
  })
122
122
 
@@ -132,7 +132,7 @@ describe('estimator catalog route registration', () => {
132
132
  await mountWebServer(runtime, routes)
133
133
  await settle()
134
134
 
135
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE])
135
+ expect(routes.map(route => route.path).sort()).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE, '/endpoint/dsh-context-compression-improved/cuts', '/api/dsh-context-compression-improved/cuts'].sort())
136
136
  })
137
137
 
138
138
  it('registers nothing twice when the estimator services arrive later', async () => {
@@ -197,6 +197,6 @@ describe('estimator catalog route registration', () => {
197
197
  apply(runtime, { presetOverlay: false })
198
198
  await settle()
199
199
 
200
- expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE])
200
+ expect(routes.map(route => route.path).sort()).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE, SAVINGS_SESSIONS_LEGACY_ROUTE, SAVINGS_SESSIONS_ROUTE, SETTINGS_LEGACY_ROUTE, SETTINGS_ROUTE, '/endpoint/dsh-context-compression-improved/cuts', '/api/dsh-context-compression-improved/cuts'].sort())
201
201
  })
202
202
  })