dsh-context-compression-improved 0.15.1 → 0.15.2

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,12 +1,16 @@
1
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";
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";
4
5
  import z from "@deepseek-ai/schemastery";
5
- import path from "node:path";
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
7
+ import path, { join } from "node:path";
6
8
  import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
7
9
  import fs from "node:fs/promises";
8
10
  import { Service } from "@deepseek-ai/cordis";
9
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
+ //#region \0rolldown/runtime.js
13
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
10
14
  z.object({
11
15
  maxChars: z.number().step(1).min(1).default(12e3),
12
16
  maxScanChars: z.number().step(1).min(1).default(25e4),
@@ -4511,6 +4515,55 @@ function renderIntentFoldBlock(pending, seq) {
4511
4515
  const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
4512
4516
  return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
4513
4517
  }
4518
+ /**
4519
+ * Check whether a candidate cut has sufficient net gain to be published.
4520
+ *
4521
+ * @param tokensBefore - tokens of the original content
4522
+ * @param tokensAfter - tokens of the replacement card/pointer
4523
+ * @param minNetGain - minimum required net savings (0 = disabled)
4524
+ * @returns true if the cut should proceed, false if it should be skipped
4525
+ */
4526
+ function checkNetGain(tokensBefore, tokensAfter, minNetGain) {
4527
+ if (minNetGain <= 0) return true;
4528
+ return tokensBefore - tokensAfter - 80 >= minNetGain;
4529
+ }
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
+ }
4514
4567
  //#endregion
4515
4568
  //#region src/runtime/adaptive-cost.ts
4516
4569
  /**
@@ -6590,6 +6643,8 @@ var ToolResultPruner = class extends Service {
6590
6643
  }
6591
6644
  land(session, plan) {
6592
6645
  const { candidate } = plan;
6646
+ const minNetGain = this.activeSettings(session).minNetGain ?? 0;
6647
+ if (minNetGain > 0 && !checkNetGain(plan.tokensBefore, plan.tokensAfter, minNetGain)) return null;
6593
6648
  const resultView = viewToolResult(candidate.event.data.message);
6594
6649
  const message = freezeMessage({
6595
6650
  ...candidate.event.data.message,
@@ -6660,6 +6715,19 @@ var ToolResultPruner = class extends Service {
6660
6715
  basis: plan.measurementBasis,
6661
6716
  replacementSeq: Number(replacement.seq)
6662
6717
  });
6718
+ appendCut({
6719
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
6720
+ sessionId: String(session.id),
6721
+ strategy: plan.stage === "fresh" ? plan.reducer.includes("skeleton") ? "skeleton" : "small-knife" : "small-knife",
6722
+ component: plan.component,
6723
+ eventSeqs: [candidate.seq],
6724
+ tokensBefore: plan.tokensBefore,
6725
+ tokensAfter: plan.tokensAfter,
6726
+ netGain: plan.tokensBefore - plan.tokensAfter - 80,
6727
+ cacheRecomputeEst: 0,
6728
+ cardRef: `session://${String(session.id)}/event/${candidate.seq}`,
6729
+ profile: this.activeSettings(session).profile
6730
+ });
6663
6731
  return {
6664
6732
  originalSeq: candidate.seq,
6665
6733
  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.2",
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 (%)',
@@ -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