dsh-context-compression-improved 0.15.1 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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();
@@ -1,4 +1,4 @@
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
4
  import z from "@deepseek-ai/schemastery";
@@ -4511,8 +4511,21 @@ function renderIntentFoldBlock(pending, seq) {
4511
4511
  const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
4512
4512
  return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
4513
4513
  }
4514
+ /**
4515
+ * Check whether a candidate cut has sufficient net gain to be published.
4516
+ *
4517
+ * @param tokensBefore - tokens of the original content
4518
+ * @param tokensAfter - tokens of the replacement card/pointer
4519
+ * @param minNetGain - minimum required net savings (0 = disabled)
4520
+ * @returns true if the cut should proceed, false if it should be skipped
4521
+ */
4522
+ function checkNetGain(tokensBefore, tokensAfter, minNetGain) {
4523
+ if (minNetGain <= 0) return true;
4524
+ return tokensBefore - tokensAfter - 80 >= minNetGain;
4525
+ }
4514
4526
  //#endregion
4515
4527
  //#region src/runtime/adaptive-cost.ts
4528
+ init_cut_index();
4516
4529
  /**
4517
4530
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
4518
4531
  * request-level cache split to individual messages. Removed tokens are not
@@ -6590,6 +6603,8 @@ var ToolResultPruner = class extends Service {
6590
6603
  }
6591
6604
  land(session, plan) {
6592
6605
  const { candidate } = plan;
6606
+ const minNetGain = this.activeSettings(session).minNetGain ?? 0;
6607
+ if (minNetGain > 0 && !checkNetGain(plan.tokensBefore, plan.tokensAfter, minNetGain)) return null;
6593
6608
  const resultView = viewToolResult(candidate.event.data.message);
6594
6609
  const message = freezeMessage({
6595
6610
  ...candidate.event.data.message,
@@ -6660,6 +6675,19 @@ var ToolResultPruner = class extends Service {
6660
6675
  basis: plan.measurementBasis,
6661
6676
  replacementSeq: Number(replacement.seq)
6662
6677
  });
6678
+ appendCut({
6679
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
6680
+ sessionId: String(session.id),
6681
+ strategy: plan.stage === "fresh" ? plan.reducer.includes("skeleton") ? "skeleton" : "small-knife" : "small-knife",
6682
+ component: plan.component,
6683
+ eventSeqs: [candidate.seq],
6684
+ tokensBefore: plan.tokensBefore,
6685
+ tokensAfter: plan.tokensAfter,
6686
+ netGain: plan.tokensBefore - plan.tokensAfter - 80,
6687
+ cacheRecomputeEst: 0,
6688
+ cardRef: `session://${String(session.id)}/event/${candidate.seq}`,
6689
+ profile: this.activeSettings(session).profile
6690
+ });
6663
6691
  return {
6664
6692
  originalSeq: candidate.seq,
6665
6693
  sourceSeq: plan.sourceSeq,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.15.1",
3
+ "version": "0.15.3",
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",
@@ -163,5 +163,7 @@ export const de = {
163
163
  'savings.sessions': "Sitzungskonto",
164
164
  'savings.money': "Geld gespart (cache-gewichtet)",
165
165
  'savings.cumulative': "Kumuliert (über N Calls)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const es = {
163
163
  'savings.sessions': "Libro de sesiones",
164
164
  'savings.money': "Dinero ahorrado (ponderado por caché)",
165
165
  'savings.cumulative': "Acumulado (en N llamadas)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const fr = {
163
163
  'savings.sessions': "Registre des sessions",
164
164
  'savings.money': "Argent économisé (pondéré cache)",
165
165
  'savings.cumulative': "Cumulé (sur N appels)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const it = {
163
163
  'savings.sessions': "Registro sessioni",
164
164
  'savings.money': "Denaro risparmiato (ponderato cache)",
165
165
  'savings.cumulative': "Cumulato (su N chiamate)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const ja = {
163
163
  'savings.sessions': "セッション台帳",
164
164
  'savings.money': "節約金額(キャッシュ加重)",
165
165
  'savings.cumulative': "累計(N コール)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const ko = {
163
163
  'savings.sessions': "세션 장부",
164
164
  'savings.money': "절약 금액(캐시 가중)",
165
165
  'savings.cumulative': "누적(N회 호출)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const pt = {
163
163
  'savings.sessions': 'Razão de sessões',
164
164
  'savings.money': 'Dinheiro economado (ponderado por cache)',
165
165
  'savings.cumulative': 'Acumulado (ao longo de N chamadas)',
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -163,5 +163,7 @@ export const ru = {
163
163
  'savings.sessions': "Журнал сессий",
164
164
  'savings.money': "Сэкономлено (взвешено по кэшу)",
165
165
  'savings.cumulative': "Накоплено (за N вызовов)",
166
+ 'profile.flash-tuned': 'Flash-tuned',
167
+ 'detail.flash-tuned': 'Flash optimized',
166
168
 
167
169
  } satisfies Record<ContextCompressionLocaleKey, string>
@@ -49,6 +49,8 @@ export const zh = {
49
49
  'detail.custom': '为新会话选择已实现的压缩阶段和计量阈值',
50
50
  'detail.native': '只使用 DeepSeek Harness 原生头尾裁剪',
51
51
  'detail.off': '关闭确定性选择器;原生 auto-compact 仍由 Harness 配置决定',
52
+ 'profile.flash-tuned': 'Flash 特化模式',
53
+ 'detail.flash-tuned': '为 DeepSeek V4.1 Flash 优化的激进裁剪档:低触发值、小目标、骨架常开、净收益门槛 800',
52
54
  'autoCompact.title': 'Auto Compact 触发水位',
53
55
  'autoCompact.description': '模型驱动 Auto Compact 在请求占用达到该水位时触发。调整后,标准 Profile 的 History 触发值、最小回收量与近期尾窗随水位联动;修改只影响新会话。',
54
56
  'autoCompact.inputLabel': 'Auto Compact 阈值(%)',
@@ -219,6 +221,8 @@ export const en = {
219
221
  'detail.custom': 'Choose implemented stages and measured thresholds for new sessions',
220
222
  'detail.native': 'Use only the Harness native head/tail pruner',
221
223
  'detail.off': 'Disable the deterministic selector; native auto-compact remains separately configured',
224
+ 'profile.flash-tuned': 'Flash-tuned mode',
225
+ 'detail.flash-tuned': 'Aggressive profile optimized for DeepSeek V4.1 Flash: low triggers, small targets, skeleton on, netGain 800',
222
226
  'autoCompact.title': 'Auto Compact trigger level',
223
227
  'autoCompact.description': 'Model-driven Auto Compact triggers once request usage crosses this level. Standard-profile History triggers, minimum reclaim, and the recent tail follow the level; changes affect new sessions only.',
224
228
  'autoCompact.inputLabel': 'Auto Compact threshold (%)',
@@ -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
@@ -135,6 +135,10 @@ import {
135
135
  flattenPlainText,
136
136
  } from './runtime/tokenpilot/dedup.ts'
137
137
  import { getSavingsLedger } from './runtime/savings.ts'
138
+ import { checkNetGain } from './runtime/netgain.ts'
139
+ import { appendCut } from './runtime/cut-index.ts'
140
+ import { isInjectedMessage } from './runtime/injected-kinds.ts'
141
+ import { effectiveMinReclaim, type DisclosurePolicy } from './runtime/ptc-disclosure.ts'
138
142
  import { claimFromLand, flushUsageOnDispose, reclaimFromTailTrim, scheduleUsageFlush, setStatsLivePathBusy } from './runtime/stats-sync.ts'
139
143
  import { kickStatsBackfillOnDispose } from './runtime/stats-backfill.ts'
140
144
  import { sampleIntegralBoundary } from './runtime/savings-integral.ts'
@@ -2875,6 +2879,12 @@ export class ToolResultPruner extends Service {
2875
2879
 
2876
2880
  private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
2877
2881
  const { candidate } = plan
2882
+ // F1: Net-gain gate — skip cuts that don't clear the threshold
2883
+ // F1: Net-gain gate — disabled by default (0 = pass-through, preserving old behavior)
2884
+ const minNetGain = (this.activeSettings(session) as unknown as Record<string, unknown>).minNetGain as number | undefined ?? 0
2885
+ if (minNetGain > 0 && !checkNetGain(plan.tokensBefore, plan.tokensAfter, minNetGain)) {
2886
+ return null
2887
+ }
2878
2888
  // 0.1.7-rc.2: the tool message's own `content` is the result block set —
2879
2889
  // no wrapping result block anymore. The triple view still resolves the
2880
2890
  // call id axis on a legacy envelope.
@@ -2953,6 +2963,20 @@ export class ToolResultPruner extends Service {
2953
2963
  basis: plan.measurementBasis,
2954
2964
  replacementSeq: Number(replacement.seq),
2955
2965
  })
2966
+ // F2: Append to per-cut audit index (fire-and-forget)
2967
+ appendCut({
2968
+ ts: new Date().toISOString(),
2969
+ sessionId: String(session.id),
2970
+ strategy: plan.stage === 'fresh' ? (plan.reducer.includes('skeleton') ? 'skeleton' : 'small-knife') : 'small-knife',
2971
+ component: plan.component,
2972
+ eventSeqs: [candidate.seq],
2973
+ tokensBefore: plan.tokensBefore,
2974
+ tokensAfter: plan.tokensAfter,
2975
+ netGain: plan.tokensBefore - plan.tokensAfter - 80,
2976
+ cacheRecomputeEst: 0,
2977
+ cardRef: `session://${String(session.id)}/event/${candidate.seq}`,
2978
+ profile: this.activeSettings(session).profile,
2979
+ })
2956
2980
  return {
2957
2981
  originalSeq: candidate.seq,
2958
2982
  sourceSeq: plan.sourceSeq,
@@ -47,9 +47,7 @@ function presetsFilePath(): string {
47
47
  }
48
48
 
49
49
  export interface PresetDocument {
50
- 'session:<sid>'?: PresetTier['settings']
51
- 'workspace:<dir>'?: PresetTier['settings']
52
- all?: PresetTier['settings']
50
+ [scope: string]: PresetTier['settings'] | undefined
53
51
  }
54
52
 
55
53
  /** Load the preset document, creating defaults if missing. */
@@ -65,7 +63,7 @@ export function savePreset(scope: string, settings: PresetTier['settings']): voi
65
63
  const dir = path.substring(0, path.lastIndexOf('\\') > -1 ? path.lastIndexOf('\\') : path.lastIndexOf('/'))
66
64
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
67
65
  const doc = loadPresets()
68
- doc[scope as keyof PresetDocument] = settings
66
+ doc[scope] = settings
69
67
  writeFileSync(path, JSON.stringify(doc, null, 2), 'utf8')
70
68
  }
71
69
 
@@ -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
  })