dsh-context-compression-improved 0.9.7 → 0.9.9-beta.0
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.
- package/LICENSE +21 -21
- package/README.md +15 -98
- package/README.zh.md +14 -92
- package/THIRD_PARTY_NOTICES.md +32 -14
- package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +27 -27
- package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
- package/{packages/selector/lib → lib}/client.d.ts +16 -0
- package/{packages/selector/lib → lib}/client.js +393 -116
- package/{packages/selector/lib → lib}/index.js +829 -10
- package/{packages/selector/lib → lib}/invariant.js +2 -1
- package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
- package/{packages/selector/lib → lib}/pruner.js +77 -983
- package/lib/savings-integral.js +4515 -0
- package/{packages/selector/lib → lib}/tail-trim.js +2 -90
- package/lib/tool-result.js +150 -0
- package/package.json +129 -116
- package/screenshots.json +3 -6
- package/.gitattributes +0 -2
- package/.githooks/pre-push +0 -37
- package/.github/workflows/ci.yml +0 -39
- package/CHANGELOG.de.md +0 -580
- package/CHANGELOG.es.md +0 -588
- package/CHANGELOG.fr.md +0 -576
- package/CHANGELOG.it.md +0 -577
- package/CHANGELOG.ja.md +0 -261
- package/CHANGELOG.ko.md +0 -254
- package/CHANGELOG.md +0 -532
- package/CHANGELOG.ru.md +0 -554
- package/CHANGELOG.zh.md +0 -236
- package/CONTRIBUTING.md +0 -22
- package/README.de.md +0 -96
- package/README.es.md +0 -96
- package/README.fr.md +0 -96
- package/README.it.md +0 -96
- package/README.ja.md +0 -102
- package/README.ko.md +0 -102
- package/README.ru.md +0 -96
- package/SECURITY.md +0 -18
- package/assets/board.png +0 -0
- package/assets/context.png +0 -0
- package/docs/assets/context-compression-selector-profiles.jpg +0 -0
- package/docs/assets/context-compression-selector-settings.png +0 -0
- package/docs/compat-0.1.5-report.md +0 -77
- package/docs/installation.de.md +0 -104
- package/docs/installation.es.md +0 -104
- package/docs/installation.fr.md +0 -104
- package/docs/installation.it.md +0 -104
- package/docs/installation.ja.md +0 -78
- package/docs/installation.ko.md +0 -78
- package/docs/installation.md +0 -103
- package/docs/installation.ru.md +0 -104
- package/docs/installation.zh.md +0 -100
- package/docs/repair-log.md +0 -657
- package/eslint.config.js +0 -30
- package/packages/selector/LICENSE +0 -21
- package/packages/selector/README.md +0 -26
- package/packages/selector/README.zh.md +0 -24
- package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
- package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
- package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
- package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
- package/packages/selector/lib/config.js +0 -1777
- package/packages/selector/lib/host-generation.js +0 -62
- package/packages/selector/lib/style.css +0 -350
- package/packages/selector/package.json +0 -174
- package/packages/selector/screenshots.json +0 -3
- package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
- package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
- package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
- package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
- package/packages/selector/src/client/EstimatorControls.tsx +0 -277
- package/packages/selector/src/client/bridge-scope.ts +0 -125
- package/packages/selector/src/client/decode.ts +0 -57
- package/packages/selector/src/client/index.ts +0 -421
- package/packages/selector/src/client/locales/de.ts +0 -142
- package/packages/selector/src/client/locales/es.ts +0 -142
- package/packages/selector/src/client/locales/fr.ts +0 -142
- package/packages/selector/src/client/locales/it.ts +0 -142
- package/packages/selector/src/client/locales/ja.ts +0 -142
- package/packages/selector/src/client/locales/ko.ts +0 -142
- package/packages/selector/src/client/locales/ru.ts +0 -142
- package/packages/selector/src/client/locales.ts +0 -284
- package/packages/selector/src/client/monitor-fab.ts +0 -349
- package/packages/selector/src/client/preset-options.ts +0 -88
- package/packages/selector/src/client/savings-card.tsx +0 -150
- package/packages/selector/src/client/scope-face.ts +0 -24
- package/packages/selector/src/client/settings-section.tsx +0 -140
- package/packages/selector/src/compat/host-generation.ts +0 -96
- package/packages/selector/src/compat/llm-messages.ts +0 -50
- package/packages/selector/src/compat/settings-lease.ts +0 -108
- package/packages/selector/src/compat/tool-result.ts +0 -91
- package/packages/selector/src/css-modules.d.ts +0 -6
- package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
- package/packages/selector/src/estimator-catalog.ts +0 -104
- package/packages/selector/src/index.ts +0 -655
- package/packages/selector/src/invariant.ts +0 -113
- package/packages/selector/src/preset-overlay.ts +0 -749
- package/packages/selector/src/profiles.ts +0 -431
- package/packages/selector/src/pruner/content.ts +0 -198
- package/packages/selector/src/pruner/session.ts +0 -97
- package/packages/selector/src/pruner/state.ts +0 -61
- package/packages/selector/src/pruner/tuning.ts +0 -23
- package/packages/selector/src/pruner/types.ts +0 -78
- package/packages/selector/src/pruner.ts +0 -2868
- package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
- package/packages/selector/src/runtime/audit.ts +0 -303
- package/packages/selector/src/runtime/config.ts +0 -756
- package/packages/selector/src/runtime/custom-policy.ts +0 -278
- package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
- package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
- package/packages/selector/src/runtime/measurement.ts +0 -444
- package/packages/selector/src/runtime/monitor.ts +0 -235
- package/packages/selector/src/runtime/reducers.ts +0 -1754
- package/packages/selector/src/runtime/retrieve.ts +0 -484
- package/packages/selector/src/runtime/savings-projection.ts +0 -226
- package/packages/selector/src/runtime/savings.ts +0 -417
- package/packages/selector/src/runtime/session-events.ts +0 -30
- package/packages/selector/src/runtime/summary-command.ts +0 -127
- package/packages/selector/src/runtime/tail-trim.ts +0 -176
- package/packages/selector/src/runtime/token-count.ts +0 -72
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
- package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
- package/packages/selector/src/runtime/toolclass.ts +0 -103
- package/packages/selector/src/runtime/types.ts +0 -365
- package/packages/selector/src/runtime/value.ts +0 -48
- package/packages/selector/src/settings-bridge.ts +0 -175
- package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
- package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
- package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
- package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
- package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
- package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
- package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
- package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
- package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
- package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
- package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
- package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
- package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
- package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
- package/packages/selector/tests/profiles.client.spec.tsx +0 -436
- package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
- package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
- package/packages/selector/tests/runtime/audit.spec.ts +0 -275
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
- package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
- package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
- package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
- package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
- package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
- package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
- package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
- package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
- package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
- package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
- package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
- package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
- package/packages/selector/tests/runtime/savings.spec.ts +0 -139
- package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
- package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
- package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
- package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
- package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
- package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
- package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
- package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
- package/packages/selector/tests/runtime/value.spec.ts +0 -23
- package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
- package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
- package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
- package/packages/selector/tests/support/mock-adapter.ts +0 -37
- package/packages/selector/tests/support/ui-primitives.tsx +0 -34
- package/packages/selector/tsconfig.json +0 -11
- package/packages/selector/tsdown.client.config.ts +0 -102
- package/packages/selector/tsdown.config.ts +0 -20
- package/pnpm-workspace.yaml +0 -72
- package/scripts/capture-profile-baseline.mjs +0 -42
- package/scripts/cell-browser-e2e.mjs +0 -354
- package/scripts/generate-tokenizer-fixtures.py +0 -81
- package/scripts/generate-vision-fixtures.py +0 -208
- package/scripts/hosts.mjs +0 -77
- package/scripts/packed-components-smoke.mjs +0 -763
- package/scripts/packed-install-e2e.mjs +0 -1346
- package/scripts/sync-hosts.mjs +0 -174
- package/scripts/toolclass-corpus-replay.mjs +0 -281
- package/scripts/verify-release.mjs +0 -335
- package/tests/TEST_INVENTORY.md +0 -41
- package/tsconfig.base.json +0 -18
- package/tsconfig.json +0 -7
- package/tsconfig.tests.json +0 -15
- package/vitest.built.config.ts +0 -9
- package/vitest.config.ts +0 -46
- /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
- /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
- /package/{packages/selector/lib → lib}/index.d.ts +0 -0
- /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
- /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
|
@@ -1,1777 +0,0 @@
|
|
|
1
|
-
import z from "@deepseek-ai/schemastery";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
//#region src/runtime/savings.ts
|
|
4
|
-
/**
|
|
5
|
-
* 节省统计账本(诚实口径)。
|
|
6
|
-
*
|
|
7
|
-
* 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
|
|
8
|
-
* 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
|
|
9
|
-
* tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
|
|
10
|
-
* 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
|
|
11
|
-
* 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
|
|
12
|
-
* 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
|
|
13
|
-
* 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
|
|
14
|
-
* 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
|
|
15
|
-
* 汇总,永不合并成一个数。
|
|
16
|
-
*
|
|
17
|
-
* 存储:进程内 per-session 账本(条目环形缓冲 + hash 注册表)。不落盘——
|
|
18
|
-
* 节省统计是运行期面板数据,重启归零是可接受语义(审计日志里已有全量原始记录)。
|
|
19
|
-
*
|
|
20
|
-
* @module dsh-context-compression-improved/runtime/savings
|
|
21
|
-
*/
|
|
22
|
-
const MAX_ENTRIES_PER_SESSION = 400;
|
|
23
|
-
const MAX_REGISTRY = 2048;
|
|
24
|
-
var SavingsLedger = class {
|
|
25
|
-
entries = /* @__PURE__ */ new Map();
|
|
26
|
-
registry = /* @__PURE__ */ new Map();
|
|
27
|
-
seenFullText = /* @__PURE__ */ new Set();
|
|
28
|
-
usage = /* @__PURE__ */ new Map();
|
|
29
|
-
startedAt = Date.now();
|
|
30
|
-
/**
|
|
31
|
-
* 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
|
|
32
|
-
* dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
|
|
33
|
-
*/
|
|
34
|
-
recordUsage(sessionId, usage) {
|
|
35
|
-
let total = this.usage.get(sessionId);
|
|
36
|
-
if (total === void 0) {
|
|
37
|
-
total = {
|
|
38
|
-
requests: 0,
|
|
39
|
-
inputTokens: 0,
|
|
40
|
-
outputTokens: 0,
|
|
41
|
-
cacheReadTokens: 0,
|
|
42
|
-
cacheWriteTokens: 0
|
|
43
|
-
};
|
|
44
|
-
this.usage.set(sessionId, total);
|
|
45
|
-
}
|
|
46
|
-
total.requests += 1;
|
|
47
|
-
total.inputTokens += positiveOrZero(usage.inputTokens);
|
|
48
|
-
total.outputTokens += positiveOrZero(usage.outputTokens);
|
|
49
|
-
total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens);
|
|
50
|
-
total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens);
|
|
51
|
-
}
|
|
52
|
-
totalsFor(scope) {
|
|
53
|
-
const sum = {
|
|
54
|
-
requests: 0,
|
|
55
|
-
inputTokens: 0,
|
|
56
|
-
outputTokens: 0,
|
|
57
|
-
cacheReadTokens: 0,
|
|
58
|
-
cacheWriteTokens: 0
|
|
59
|
-
};
|
|
60
|
-
for (const sid of scope) {
|
|
61
|
-
const t = this.usage.get(sid);
|
|
62
|
-
if (t === void 0) continue;
|
|
63
|
-
sum.requests += t.requests;
|
|
64
|
-
sum.inputTokens += t.inputTokens;
|
|
65
|
-
sum.outputTokens += t.outputTokens;
|
|
66
|
-
sum.cacheReadTokens += t.cacheReadTokens;
|
|
67
|
-
sum.cacheWriteTokens += t.cacheWriteTokens;
|
|
68
|
-
}
|
|
69
|
-
return sum;
|
|
70
|
-
}
|
|
71
|
-
/** 单行会话汇总(session/disposed 日志用)。 */
|
|
72
|
-
sessionSummaryLine(sessionId) {
|
|
73
|
-
const snap = this.snapshot(sessionId);
|
|
74
|
-
const hit = snap.usage.cacheHitRate;
|
|
75
|
-
return `net=${snap.net.exact}(exact)/${snap.net.estimated}(est) gross=${snap.gross.exact}/${snap.gross.estimated} offsets=${snap.offsets.exact}/${snap.offsets.estimated} requests=${snap.usage.requests} cacheHit=${hit === null ? "–" : `${Math.round(hit * 100)}%`}`;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。
|
|
79
|
-
*
|
|
80
|
-
* 仪表口径:该条目在替换事件离开当前 surface 前一直计入"当前生效毛节省"
|
|
81
|
-
* (由 {@link observeActive} 每回合收敛),不再一次性永久累加。
|
|
82
|
-
*/
|
|
83
|
-
recordSaving(input) {
|
|
84
|
-
const removed = input.tokensBefore - input.tokensAfter;
|
|
85
|
-
if (!Number.isFinite(removed) || removed <= 0) return;
|
|
86
|
-
this.push(input.sessionId, {
|
|
87
|
-
kind: "saving",
|
|
88
|
-
component: input.component,
|
|
89
|
-
tokens: removed,
|
|
90
|
-
basis: input.basis,
|
|
91
|
-
at: Date.now(),
|
|
92
|
-
...input.replacementSeq === void 0 ? {} : { replacementSeq: input.replacementSeq }
|
|
93
|
-
});
|
|
94
|
-
if (typeof input.originalText === "string" && input.originalText.length > 0) {
|
|
95
|
-
const hash = savingsHash(input.originalText);
|
|
96
|
-
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
|
|
97
|
-
const oldest = this.registry.keys().next().value;
|
|
98
|
-
if (oldest !== void 0) this.registry.delete(oldest);
|
|
99
|
-
}
|
|
100
|
-
this.registry.set(hash, {
|
|
101
|
-
sessionId: input.sessionId,
|
|
102
|
-
component: input.component,
|
|
103
|
-
claimedTokens: removed,
|
|
104
|
-
basis: input.basis,
|
|
105
|
-
sourceSeq: input.sourceSeq,
|
|
106
|
-
consumed: false
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
|
|
112
|
-
* 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
|
|
113
|
-
* @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
|
|
114
|
-
*/
|
|
115
|
-
noteFullText(input) {
|
|
116
|
-
if (typeof input.text !== "string" || input.text.length === 0) return;
|
|
117
|
-
const seenKey = `${input.sessionId}:${input.seq}`;
|
|
118
|
-
if (this.seenFullText.has(seenKey)) return;
|
|
119
|
-
this.seenFullText.add(seenKey);
|
|
120
|
-
if (this.seenFullText.size > MAX_REGISTRY * 4) {
|
|
121
|
-
this.seenFullText.clear();
|
|
122
|
-
this.seenFullText.add(seenKey);
|
|
123
|
-
}
|
|
124
|
-
const hit = this.registry.get(savingsHash(input.text));
|
|
125
|
-
if (hit === void 0 || hit.sessionId !== input.sessionId) return;
|
|
126
|
-
const { tokens, basis } = input.measure(input.text);
|
|
127
|
-
if (tokens <= 0) return;
|
|
128
|
-
this.push(input.sessionId, {
|
|
129
|
-
kind: "offset",
|
|
130
|
-
component: "full-read",
|
|
131
|
-
tokens,
|
|
132
|
-
basis,
|
|
133
|
-
at: Date.now(),
|
|
134
|
-
note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
/** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
|
|
138
|
-
recordOffset(input) {
|
|
139
|
-
if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
|
|
140
|
-
this.push(input.sessionId, {
|
|
141
|
-
kind: "offset",
|
|
142
|
-
component: input.component,
|
|
143
|
-
tokens: input.tokens,
|
|
144
|
-
basis: input.basis,
|
|
145
|
-
at: Date.now(),
|
|
146
|
-
...input.note === void 0 ? {} : { note: input.note }
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
sourceSeqOf(item) {
|
|
150
|
-
return item.sourceSeq;
|
|
151
|
-
}
|
|
152
|
-
push(sessionId, entry) {
|
|
153
|
-
let list = this.entries.get(sessionId);
|
|
154
|
-
if (list === void 0) {
|
|
155
|
-
list = [];
|
|
156
|
-
this.entries.set(sessionId, list);
|
|
157
|
-
}
|
|
158
|
-
list.push(entry);
|
|
159
|
-
if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION);
|
|
160
|
-
}
|
|
161
|
-
/**
|
|
162
|
-
* 仪表口径收敛:一个 'saving' 条目只在其替换事件仍位于当前 surface 时计为
|
|
163
|
-
* "当前生效毛节省"。pruner 每回合传入存活 seq 集合,离开 surface 的替换
|
|
164
|
-
* (被后续压缩/裁剪替换)即从毛节省中扣除,数字随压缩内容进出而涨落。
|
|
165
|
-
* 无 replacementSeq 的条目保持原样(无法追踪者不收敛)。
|
|
166
|
-
*/
|
|
167
|
-
observeActive(sessionId, liveSeqs) {
|
|
168
|
-
const list = this.entries.get(sessionId);
|
|
169
|
-
if (list === void 0) return;
|
|
170
|
-
const kept = list.filter((entry) => entry.kind !== "saving" || entry.replacementSeq === void 0 || liveSeqs.has(entry.replacementSeq));
|
|
171
|
-
if (kept.length !== list.length) this.entries.set(sessionId, kept);
|
|
172
|
-
}
|
|
173
|
-
/** 该会话是否已有账本条目(重进会话时用于避免投影与实时叠加)。 */
|
|
174
|
-
hasSession(sessionId) {
|
|
175
|
-
return this.entries.has(sessionId);
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* 用会话日志投影播种一个会话的账本(重进/重启会话时调用一次)。写入
|
|
179
|
-
* savings/offsets 条目及其原文配对 registry,后续实时增量(observeActive /
|
|
180
|
-
* noteFullText)在同一条目集合上继续工作。调用方负责只播种一次。
|
|
181
|
-
*/
|
|
182
|
-
seedProjected(sessionId, projection) {
|
|
183
|
-
for (const entry of projection.savings) {
|
|
184
|
-
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue;
|
|
185
|
-
this.push(sessionId, {
|
|
186
|
-
kind: "saving",
|
|
187
|
-
component: entry.component,
|
|
188
|
-
tokens: entry.tokens,
|
|
189
|
-
basis: entry.basis,
|
|
190
|
-
at: entry.at,
|
|
191
|
-
replacementSeq: entry.replacementSeq
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
for (const entry of projection.offsets) {
|
|
195
|
-
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue;
|
|
196
|
-
this.push(sessionId, {
|
|
197
|
-
kind: "offset",
|
|
198
|
-
component: entry.component,
|
|
199
|
-
tokens: entry.tokens,
|
|
200
|
-
basis: entry.basis,
|
|
201
|
-
at: entry.at,
|
|
202
|
-
...entry.note === void 0 ? {} : { note: entry.note }
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
for (const item of projection.registry) {
|
|
206
|
-
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(item.hash)) {
|
|
207
|
-
const oldest = this.registry.keys().next().value;
|
|
208
|
-
if (oldest !== void 0) this.registry.delete(oldest);
|
|
209
|
-
}
|
|
210
|
-
this.registry.set(item.hash, {
|
|
211
|
-
sessionId,
|
|
212
|
-
component: "projection",
|
|
213
|
-
claimedTokens: item.claimedTokens,
|
|
214
|
-
basis: item.basis,
|
|
215
|
-
sourceSeq: item.sourceSeq,
|
|
216
|
-
consumed: false
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
/** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
|
|
221
|
-
snapshot(sessionId) {
|
|
222
|
-
const scope = sessionId === void 0 ? [...this.entries.keys()] : [sessionId];
|
|
223
|
-
const totals = {
|
|
224
|
-
grossExact: 0,
|
|
225
|
-
grossEstimated: 0,
|
|
226
|
-
offsetExact: 0,
|
|
227
|
-
offsetEstimated: 0
|
|
228
|
-
};
|
|
229
|
-
const perComponent = /* @__PURE__ */ new Map();
|
|
230
|
-
const recentOffsets = [];
|
|
231
|
-
for (const sid of scope) for (const entry of this.entries.get(sid) ?? []) {
|
|
232
|
-
const exact = entry.basis === "exact-tokenizer";
|
|
233
|
-
if (entry.kind === "saving") {
|
|
234
|
-
if (exact) totals.grossExact += entry.tokens;
|
|
235
|
-
else totals.grossEstimated += entry.tokens;
|
|
236
|
-
} else {
|
|
237
|
-
if (exact) totals.offsetExact += entry.tokens;
|
|
238
|
-
else totals.offsetEstimated += entry.tokens;
|
|
239
|
-
recentOffsets.push(entry);
|
|
240
|
-
}
|
|
241
|
-
const key = `${entry.kind}:${entry.component}:${entry.basis}`;
|
|
242
|
-
const agg = perComponent.get(key);
|
|
243
|
-
if (agg === void 0) perComponent.set(key, {
|
|
244
|
-
component: entry.component,
|
|
245
|
-
tokens: entry.tokens,
|
|
246
|
-
basis: entry.basis,
|
|
247
|
-
kind: entry.kind
|
|
248
|
-
});
|
|
249
|
-
else agg.tokens += entry.tokens;
|
|
250
|
-
}
|
|
251
|
-
recentOffsets.sort((a, b) => b.at - a.at);
|
|
252
|
-
const usageTotals = this.totalsFor(scope);
|
|
253
|
-
const perSession = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...this.entries.keys(), ...this.usage.keys()])].map((sid) => {
|
|
254
|
-
const s = this.snapshot(sid);
|
|
255
|
-
return {
|
|
256
|
-
sessionId: sid,
|
|
257
|
-
gross: s.gross,
|
|
258
|
-
offsets: s.offsets,
|
|
259
|
-
net: s.net,
|
|
260
|
-
requests: s.usage.requests,
|
|
261
|
-
cacheHitRate: s.usage.cacheHitRate
|
|
262
|
-
};
|
|
263
|
-
}).sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated).slice(0, 8) : [];
|
|
264
|
-
return {
|
|
265
|
-
startedAt: new Date(this.startedAt).toISOString(),
|
|
266
|
-
sessions: sessionId === void 0 ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
|
|
267
|
-
gross: {
|
|
268
|
-
exact: totals.grossExact,
|
|
269
|
-
estimated: totals.grossEstimated
|
|
270
|
-
},
|
|
271
|
-
offsets: {
|
|
272
|
-
exact: totals.offsetExact,
|
|
273
|
-
estimated: totals.offsetEstimated
|
|
274
|
-
},
|
|
275
|
-
net: {
|
|
276
|
-
exact: totals.grossExact - totals.offsetExact,
|
|
277
|
-
estimated: totals.grossEstimated - totals.offsetEstimated
|
|
278
|
-
},
|
|
279
|
-
perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
|
|
280
|
-
recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
|
|
281
|
-
component: e.component,
|
|
282
|
-
tokens: e.tokens,
|
|
283
|
-
basis: e.basis,
|
|
284
|
-
at: new Date(e.at).toISOString(),
|
|
285
|
-
...e.note === void 0 ? {} : { note: e.note }
|
|
286
|
-
})),
|
|
287
|
-
usage: {
|
|
288
|
-
...usageTotals,
|
|
289
|
-
cacheHitRate: cacheHitRateOf(usageTotals)
|
|
290
|
-
},
|
|
291
|
-
perSession
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
/** 测试与停机清理。 */
|
|
295
|
-
clear() {
|
|
296
|
-
this.entries.clear();
|
|
297
|
-
this.registry.clear();
|
|
298
|
-
this.seenFullText.clear();
|
|
299
|
-
this.usage.clear();
|
|
300
|
-
this.startedAt = Date.now();
|
|
301
|
-
}
|
|
302
|
-
};
|
|
303
|
-
function cacheHitRateOf(t) {
|
|
304
|
-
const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens;
|
|
305
|
-
return denom <= 0 ? null : Math.round(t.cacheReadTokens / denom * 1e3) / 1e3;
|
|
306
|
-
}
|
|
307
|
-
/** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
|
|
308
|
-
function savingsHash(text) {
|
|
309
|
-
return createHash("sha256").update(text.replace(/\r\n?/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/(^\s+)|(\s+$)/g, ""), "utf8").digest("hex");
|
|
310
|
-
}
|
|
311
|
-
function positiveOrZero(v) {
|
|
312
|
-
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0;
|
|
313
|
-
}
|
|
314
|
-
const singleton = new SavingsLedger();
|
|
315
|
-
/** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
|
|
316
|
-
function getSavingsLedger() {
|
|
317
|
-
return singleton;
|
|
318
|
-
}
|
|
319
|
-
//#endregion
|
|
320
|
-
//#region src/runtime/deepseek-official-pricing.ts
|
|
321
|
-
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
322
|
-
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
323
|
-
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
324
|
-
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
325
|
-
const PRICES = Object.freeze({
|
|
326
|
-
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
327
|
-
"0.007",
|
|
328
|
-
"0.22",
|
|
329
|
-
"0.66"
|
|
330
|
-
], [
|
|
331
|
-
"0.014",
|
|
332
|
-
"0.44",
|
|
333
|
-
"1.32"
|
|
334
|
-
], [
|
|
335
|
-
"0.05",
|
|
336
|
-
"1.5",
|
|
337
|
-
"4.5"
|
|
338
|
-
], [
|
|
339
|
-
"0.10",
|
|
340
|
-
"3.0",
|
|
341
|
-
"9.0"
|
|
342
|
-
]),
|
|
343
|
-
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
344
|
-
"0.022",
|
|
345
|
-
"0.66",
|
|
346
|
-
"1.98"
|
|
347
|
-
], [
|
|
348
|
-
"0.044",
|
|
349
|
-
"1.32",
|
|
350
|
-
"3.96"
|
|
351
|
-
], [
|
|
352
|
-
"0.15",
|
|
353
|
-
"4.5",
|
|
354
|
-
"13.5"
|
|
355
|
-
], [
|
|
356
|
-
"0.30",
|
|
357
|
-
"9.0",
|
|
358
|
-
"27.0"
|
|
359
|
-
]),
|
|
360
|
-
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
361
|
-
"0.007",
|
|
362
|
-
"0.22",
|
|
363
|
-
"0.66"
|
|
364
|
-
], [
|
|
365
|
-
"0.014",
|
|
366
|
-
"0.44",
|
|
367
|
-
"1.32"
|
|
368
|
-
], [
|
|
369
|
-
"0.05",
|
|
370
|
-
"1.5",
|
|
371
|
-
"4.5"
|
|
372
|
-
], [
|
|
373
|
-
"0.10",
|
|
374
|
-
"3.0",
|
|
375
|
-
"9.0"
|
|
376
|
-
])
|
|
377
|
-
});
|
|
378
|
-
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
379
|
-
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
380
|
-
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
381
|
-
/**
|
|
382
|
-
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
383
|
-
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
384
|
-
* @returns An immutable price record or an explicit unpriced reason.
|
|
385
|
-
*/
|
|
386
|
-
function resolveOfficialDeepSeekPrice(input) {
|
|
387
|
-
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
388
|
-
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
389
|
-
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
390
|
-
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
391
|
-
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
392
|
-
const band = priceBandAt(input.at);
|
|
393
|
-
if (band === void 0) return unpriced("invalid price timestamp");
|
|
394
|
-
const model = PRICES[input.modelId];
|
|
395
|
-
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
396
|
-
return {
|
|
397
|
-
kind: "priced",
|
|
398
|
-
record: Object.freeze({
|
|
399
|
-
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
400
|
-
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
401
|
-
provider: "deepseek-official",
|
|
402
|
-
baseUrlClass: "official-public",
|
|
403
|
-
apiRoute: input.apiRoute,
|
|
404
|
-
modelId: input.modelId,
|
|
405
|
-
modelVersion: model.version,
|
|
406
|
-
currency: input.currency,
|
|
407
|
-
unitTokens: 1e6,
|
|
408
|
-
band,
|
|
409
|
-
inputCacheHit,
|
|
410
|
-
inputCacheMiss,
|
|
411
|
-
output,
|
|
412
|
-
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
413
|
-
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
414
|
-
peakRule: PEAK_RULE
|
|
415
|
-
})
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Classify a timestamp under the published Beijing peak schedule.
|
|
420
|
-
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
421
|
-
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
422
|
-
*/
|
|
423
|
-
function priceBandAt(at) {
|
|
424
|
-
if (!Number.isFinite(at.getTime())) return void 0;
|
|
425
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
426
|
-
timeZone: "Asia/Shanghai",
|
|
427
|
-
weekday: "short",
|
|
428
|
-
hour: "2-digit",
|
|
429
|
-
minute: "2-digit",
|
|
430
|
-
second: "2-digit",
|
|
431
|
-
hourCycle: "h23"
|
|
432
|
-
}).formatToParts(at);
|
|
433
|
-
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
434
|
-
const weekday = values.weekday;
|
|
435
|
-
const hour = Number(values.hour);
|
|
436
|
-
const minute = Number(values.minute);
|
|
437
|
-
const second = Number(values.second);
|
|
438
|
-
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
439
|
-
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
440
|
-
const seconds = hour * 3600 + minute * 60 + second;
|
|
441
|
-
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
442
|
-
}
|
|
443
|
-
/**
|
|
444
|
-
* Price one completed request, returning a range when it spans a published band boundary.
|
|
445
|
-
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
446
|
-
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
447
|
-
*/
|
|
448
|
-
function priceOfficialDeepSeekUsage(input) {
|
|
449
|
-
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
450
|
-
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
451
|
-
const start = resolveOfficialDeepSeekPrice({
|
|
452
|
-
...input,
|
|
453
|
-
at: input.startedAt
|
|
454
|
-
});
|
|
455
|
-
if (start.kind === "unpriced") return start;
|
|
456
|
-
const end = resolveOfficialDeepSeekPrice({
|
|
457
|
-
...input,
|
|
458
|
-
at: input.completedAt
|
|
459
|
-
});
|
|
460
|
-
if (end.kind === "unpriced") return end;
|
|
461
|
-
const startAmount = amountFor(start.record, input.usage);
|
|
462
|
-
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
463
|
-
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
464
|
-
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
465
|
-
kind: "exact",
|
|
466
|
-
currency: start.record.currency,
|
|
467
|
-
band: start.record.band,
|
|
468
|
-
...startAmount
|
|
469
|
-
};
|
|
470
|
-
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
471
|
-
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
472
|
-
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
473
|
-
const startFemto = BigInt(startAmount.femtoUnits);
|
|
474
|
-
const endFemto = BigInt(endAmount.femtoUnits);
|
|
475
|
-
return {
|
|
476
|
-
kind: "range",
|
|
477
|
-
currency: start.record.currency,
|
|
478
|
-
bands: [start.record.band, comparisonRecord.band],
|
|
479
|
-
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
480
|
-
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
484
|
-
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
485
|
-
const start = startedAt.getTime();
|
|
486
|
-
const end = completedAt.getTime();
|
|
487
|
-
if (end <= start) return false;
|
|
488
|
-
const dayMs = 864e5;
|
|
489
|
-
if (end - start >= 7 * dayMs) return true;
|
|
490
|
-
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
491
|
-
for (let day = firstDay; day <= end; day += dayMs) {
|
|
492
|
-
const weekday = new Date(day).getUTCDay();
|
|
493
|
-
if (weekday === 0 || weekday === 6) continue;
|
|
494
|
-
for (const hour of [
|
|
495
|
-
1,
|
|
496
|
-
4,
|
|
497
|
-
6,
|
|
498
|
-
10
|
|
499
|
-
]) {
|
|
500
|
-
const boundary = day + hour * 60 * 60 * 1e3;
|
|
501
|
-
if (boundary > start && boundary <= end) return true;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
return false;
|
|
505
|
-
}
|
|
506
|
-
function priceRecordInBand(record, band) {
|
|
507
|
-
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
508
|
-
return Object.freeze({
|
|
509
|
-
...record,
|
|
510
|
-
band,
|
|
511
|
-
inputCacheHit,
|
|
512
|
-
inputCacheMiss,
|
|
513
|
-
output
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
/**
|
|
517
|
-
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
518
|
-
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
519
|
-
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
520
|
-
*/
|
|
521
|
-
function decimalRateNanoUnits(value) {
|
|
522
|
-
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
523
|
-
if (match === null) return void 0;
|
|
524
|
-
const whole = match[1] ?? "0";
|
|
525
|
-
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
526
|
-
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
527
|
-
}
|
|
528
|
-
function amountFor(record, usage) {
|
|
529
|
-
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
530
|
-
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
531
|
-
const output = decimalRateNanoUnits(record.output);
|
|
532
|
-
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
533
|
-
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
534
|
-
return {
|
|
535
|
-
femtoUnits: femtoUnits.toString(),
|
|
536
|
-
decimal: formatFemto(femtoUnits)
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
function formatFemto(value) {
|
|
540
|
-
const digits = value.toString().padStart(16, "0");
|
|
541
|
-
const whole = digits.slice(0, -15);
|
|
542
|
-
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
543
|
-
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
544
|
-
}
|
|
545
|
-
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
546
|
-
return Object.freeze({
|
|
547
|
-
version,
|
|
548
|
-
USD: Object.freeze({
|
|
549
|
-
"off-peak": usdOffPeak,
|
|
550
|
-
peak: usdPeak
|
|
551
|
-
}),
|
|
552
|
-
CNY: Object.freeze({
|
|
553
|
-
"off-peak": cnyOffPeak,
|
|
554
|
-
peak: cnyPeak
|
|
555
|
-
})
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
|
-
function isOfficialModel(value) {
|
|
559
|
-
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
560
|
-
}
|
|
561
|
-
function unpriced(reason) {
|
|
562
|
-
return {
|
|
563
|
-
kind: "unpriced",
|
|
564
|
-
reason
|
|
565
|
-
};
|
|
566
|
-
}
|
|
567
|
-
const advisorStates = /* @__PURE__ */ new WeakMap();
|
|
568
|
-
/**
|
|
569
|
-
* The per-session advisor state, created on first touch.
|
|
570
|
-
* @param session - the session to key the state on (by object identity).
|
|
571
|
-
*/
|
|
572
|
-
function getAdvisorState(session) {
|
|
573
|
-
let state = advisorStates.get(session);
|
|
574
|
-
if (state === void 0) {
|
|
575
|
-
state = {
|
|
576
|
-
todoVersion: void 0,
|
|
577
|
-
summary: void 0,
|
|
578
|
-
lastSummaryTurn: -1,
|
|
579
|
-
watermarkSeq: 0,
|
|
580
|
-
scores: /* @__PURE__ */ new Map(),
|
|
581
|
-
recertified: /* @__PURE__ */ new Map(),
|
|
582
|
-
failures: void 0,
|
|
583
|
-
inFlight: false,
|
|
584
|
-
lastDecay: void 0,
|
|
585
|
-
lastAdvice: void 0
|
|
586
|
-
};
|
|
587
|
-
advisorStates.set(session, state);
|
|
588
|
-
}
|
|
589
|
-
return state;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Insert or refresh one score with LRU semantics: a re-touched seq moves to
|
|
593
|
-
* the newest position, and the oldest entry is evicted once the map exceeds
|
|
594
|
-
* {@link ADVISOR_SCORES_LIMIT}.
|
|
595
|
-
*/
|
|
596
|
-
function recordScore(state, seq, entry) {
|
|
597
|
-
state.scores.delete(seq);
|
|
598
|
-
state.scores.set(seq, entry);
|
|
599
|
-
if (state.scores.size > 64) {
|
|
600
|
-
const oldest = state.scores.keys().next();
|
|
601
|
-
if (oldest.done !== true) state.scores.delete(oldest.value);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
/**
|
|
605
|
-
* Mark one seq as LLM-recertified low relevance (a suggestion for later
|
|
606
|
-
* history-aggressiveness decisions, consumed by nothing in this round).
|
|
607
|
-
* Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
|
|
608
|
-
*/
|
|
609
|
-
function recordRecertified(state, seq, turn) {
|
|
610
|
-
state.recertified.delete(seq);
|
|
611
|
-
state.recertified.set(seq, turn);
|
|
612
|
-
if (state.recertified.size > 64) {
|
|
613
|
-
const oldest = state.recertified.keys().next();
|
|
614
|
-
if (oldest.done !== true) state.recertified.delete(oldest.value);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
/**
|
|
618
|
-
* Drop every cached artifact that depends on the task semantics: a changed
|
|
619
|
-
* todo version invalidates the summary and makes all eligible candidates
|
|
620
|
-
* rescore-worthy (the watermark alone would otherwise hide them).
|
|
621
|
-
*/
|
|
622
|
-
function invalidateOnTaskChange(state, todoVersion) {
|
|
623
|
-
if (state.todoVersion === todoVersion) return false;
|
|
624
|
-
state.todoVersion = todoVersion;
|
|
625
|
-
state.summary = void 0;
|
|
626
|
-
state.lastSummaryTurn = -1;
|
|
627
|
-
return true;
|
|
628
|
-
}
|
|
629
|
-
/**
|
|
630
|
-
* `/ctx-summary off|on` overrides, keyed by session id (string). The command
|
|
631
|
-
* handler only sees `invocation.agent.session.id`, not the pruner's Session
|
|
632
|
-
* object, so these are id-keyed rather than WeakMap'd. Entries are two-char
|
|
633
|
-
* strings per session and cleared whenever the override is lifted.
|
|
634
|
-
*/
|
|
635
|
-
const summaryOverrides = /* @__PURE__ */ new Map();
|
|
636
|
-
/** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
|
|
637
|
-
function getSummaryOverride(sessionId) {
|
|
638
|
-
return summaryOverrides.get(sessionId);
|
|
639
|
-
}
|
|
640
|
-
/** Set or clear (`undefined`) the session's `/ctx-summary` override. */
|
|
641
|
-
function setSummaryOverride(sessionId, value) {
|
|
642
|
-
if (value === void 0) summaryOverrides.delete(sessionId);
|
|
643
|
-
else summaryOverrides.set(sessionId, value);
|
|
644
|
-
}
|
|
645
|
-
/** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
|
|
646
|
-
const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
|
|
647
|
-
/** Record the gate input the pass last evaluated for this session. */
|
|
648
|
-
function observeIntentEnabled(sessionId, enabled) {
|
|
649
|
-
lastObservedIntentEnabled.set(sessionId, enabled);
|
|
650
|
-
}
|
|
651
|
-
/** The settings-side enabled flag last observed for the session, if any. */
|
|
652
|
-
function getObservedIntentEnabled(sessionId) {
|
|
653
|
-
return lastObservedIntentEnabled.get(sessionId);
|
|
654
|
-
}
|
|
655
|
-
const lastIntentFolds = /* @__PURE__ */ new Map();
|
|
656
|
-
/** Record a landed intent fold for the session (newest wins). */
|
|
657
|
-
function recordIntentFold(sessionId, record) {
|
|
658
|
-
lastIntentFolds.set(sessionId, record);
|
|
659
|
-
}
|
|
660
|
-
/** The most recent landed intent fold for the session, if any. */
|
|
661
|
-
function getLastIntentFold(sessionId) {
|
|
662
|
-
return lastIntentFolds.get(sessionId);
|
|
663
|
-
}
|
|
664
|
-
//#endregion
|
|
665
|
-
//#region src/runtime/tokenpilot/intent-gate.ts
|
|
666
|
-
/**
|
|
667
|
-
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
668
|
-
*
|
|
669
|
-
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
670
|
-
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
671
|
-
* the next pressure round. The gate is deliberately conservative — every
|
|
672
|
-
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
673
|
-
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
674
|
-
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
675
|
-
* live in the fold landing path, not here.
|
|
676
|
-
*/
|
|
677
|
-
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
678
|
-
const INTENT_GATE_FLOOR_FRACTION = .45;
|
|
679
|
-
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
680
|
-
const INTENT_GATE_GROWTH_TOKENS = 5e4;
|
|
681
|
-
function isUsableNumber(value) {
|
|
682
|
-
return Number.isFinite(value) && value >= 0;
|
|
683
|
-
}
|
|
684
|
-
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
685
|
-
function evaluateIntentGate(input) {
|
|
686
|
-
const snapshot = (decision, reason) => ({
|
|
687
|
-
...input,
|
|
688
|
-
decision,
|
|
689
|
-
reason
|
|
690
|
-
});
|
|
691
|
-
if (!input.enabled) return snapshot(false, "disabled");
|
|
692
|
-
if (input.override === "off") return snapshot(false, "override-off");
|
|
693
|
-
if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
|
|
694
|
-
if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
|
|
695
|
-
if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
|
|
696
|
-
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
|
|
697
|
-
if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
|
|
698
|
-
return snapshot(true, "passed");
|
|
699
|
-
}
|
|
700
|
-
//#endregion
|
|
701
|
-
//#region src/runtime/monitor.ts
|
|
702
|
-
/**
|
|
703
|
-
* 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
|
|
704
|
-
* 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
|
|
705
|
-
* (默认 80%)——提前一档给出人工干预窗口。
|
|
706
|
-
*/
|
|
707
|
-
const MONITOR_SUGGEST_PCT = .7;
|
|
708
|
-
/**
|
|
709
|
-
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
710
|
-
* injectable so tests seed a private instance instead of the process
|
|
711
|
-
* singleton.
|
|
712
|
-
*/
|
|
713
|
-
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
714
|
-
const scopeKey = sessionId ?? "";
|
|
715
|
-
const override = getSummaryOverride(scopeKey);
|
|
716
|
-
const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
|
|
717
|
-
const contextBlock = observedContext === void 0 ? void 0 : {
|
|
718
|
-
liveTokens: observedContext.liveTokens,
|
|
719
|
-
contextWindow: observedContext.contextWindow,
|
|
720
|
-
pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
|
|
721
|
-
sessionId: observedContext.sessionId
|
|
722
|
-
};
|
|
723
|
-
const suggestion = contextBlock === void 0 || contextBlock.pct === null ? void 0 : {
|
|
724
|
-
suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
|
|
725
|
-
thresholdPct: MONITOR_SUGGEST_PCT,
|
|
726
|
-
occupancyPct: contextBlock.pct
|
|
727
|
-
};
|
|
728
|
-
return {
|
|
729
|
-
...ledger.snapshot(sessionId),
|
|
730
|
-
...contextBlock === void 0 ? {} : { context: contextBlock },
|
|
731
|
-
...suggestion === void 0 ? {} : { suggestion },
|
|
732
|
-
intent: {
|
|
733
|
-
override,
|
|
734
|
-
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
735
|
-
gate: {
|
|
736
|
-
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
737
|
-
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
738
|
-
},
|
|
739
|
-
lastFold: getLastIntentFold(scopeKey)
|
|
740
|
-
},
|
|
741
|
-
sessionScope: sessionId ?? null
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
/** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
|
|
745
|
-
const contextUsageBySession = /* @__PURE__ */ new Map();
|
|
746
|
-
const CONTEXT_USAGE_CAP = 64;
|
|
747
|
-
/**
|
|
748
|
-
* 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
|
|
749
|
-
* contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
|
|
750
|
-
*/
|
|
751
|
-
function observeContextUsage(sessionId, liveTokens, contextWindow) {
|
|
752
|
-
if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
|
|
753
|
-
if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
|
|
754
|
-
const oldest = contextUsageBySession.keys().next().value;
|
|
755
|
-
if (oldest !== void 0) contextUsageBySession.delete(oldest);
|
|
756
|
-
}
|
|
757
|
-
contextUsageBySession.set(sessionId, {
|
|
758
|
-
liveTokens,
|
|
759
|
-
contextWindow,
|
|
760
|
-
at: Date.now(),
|
|
761
|
-
seq: ++observeSeq
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
function getContextUsage(sessionId) {
|
|
765
|
-
const entry = contextUsageBySession.get(sessionId);
|
|
766
|
-
return entry === void 0 ? void 0 : {
|
|
767
|
-
liveTokens: entry.liveTokens,
|
|
768
|
-
contextWindow: entry.contextWindow,
|
|
769
|
-
sessionId
|
|
770
|
-
};
|
|
771
|
-
}
|
|
772
|
-
let observeSeq = 0;
|
|
773
|
-
function latestObservedContextUsage() {
|
|
774
|
-
let latest;
|
|
775
|
-
for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
|
|
776
|
-
sessionId,
|
|
777
|
-
liveTokens: entry.liveTokens,
|
|
778
|
-
contextWindow: entry.contextWindow,
|
|
779
|
-
seq: entry.seq
|
|
780
|
-
};
|
|
781
|
-
return latest;
|
|
782
|
-
}
|
|
783
|
-
function isSessionOverrideAction(value) {
|
|
784
|
-
return value === "on" || value === "off" || value === "clear";
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
788
|
-
* session, `clear` returns it to settings-driven. The resulting override is
|
|
789
|
-
* handed back so the route can echo the post-action truth.
|
|
790
|
-
*/
|
|
791
|
-
function applySessionOverride(sessionId, action) {
|
|
792
|
-
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
793
|
-
return { override: getSummaryOverride(sessionId) };
|
|
794
|
-
}
|
|
795
|
-
/**
|
|
796
|
-
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
797
|
-
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
798
|
-
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
799
|
-
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
800
|
-
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
801
|
-
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
802
|
-
*/
|
|
803
|
-
function estimateSavingsPricing(readService, snapshot) {
|
|
804
|
-
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
805
|
-
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
806
|
-
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
807
|
-
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
808
|
-
if (provider !== "deepseek-official") return void 0;
|
|
809
|
-
const now = /* @__PURE__ */ new Date();
|
|
810
|
-
const startedAt = new Date(snapshot.startedAt);
|
|
811
|
-
const base = {
|
|
812
|
-
provider,
|
|
813
|
-
baseUrlClass: "official-public",
|
|
814
|
-
apiRoute: "chat-completions",
|
|
815
|
-
modelId,
|
|
816
|
-
currency: "USD",
|
|
817
|
-
startedAt,
|
|
818
|
-
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
819
|
-
};
|
|
820
|
-
const actual = priceOfficialDeepSeekUsage({
|
|
821
|
-
...base,
|
|
822
|
-
usage: {
|
|
823
|
-
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
824
|
-
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
825
|
-
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
826
|
-
}
|
|
827
|
-
});
|
|
828
|
-
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
829
|
-
...base,
|
|
830
|
-
usage: {
|
|
831
|
-
cacheReadTokens: 0,
|
|
832
|
-
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
833
|
-
outputTokens: 0
|
|
834
|
-
}
|
|
835
|
-
}) : void 0;
|
|
836
|
-
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
837
|
-
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
838
|
-
return {
|
|
839
|
-
currency: "USD",
|
|
840
|
-
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
841
|
-
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
842
|
-
};
|
|
843
|
-
}
|
|
844
|
-
//#endregion
|
|
845
|
-
//#region src/runtime/types.ts
|
|
846
|
-
/** User-facing mixed strategy profile. */
|
|
847
|
-
const COMPRESSION_PROFILES = [
|
|
848
|
-
"off",
|
|
849
|
-
"native",
|
|
850
|
-
"balanced",
|
|
851
|
-
"cache-strict",
|
|
852
|
-
"savings",
|
|
853
|
-
"adaptive",
|
|
854
|
-
"tokenpilot-inspired",
|
|
855
|
-
"custom"
|
|
856
|
-
];
|
|
857
|
-
//#endregion
|
|
858
|
-
//#region src/runtime/value.ts
|
|
859
|
-
/** Version-neutral immutable-value and closed-union helpers for the plugin runtime. */
|
|
860
|
-
/**
|
|
861
|
-
* Freeze an object graph in place without relying on a Harness utility export.
|
|
862
|
-
* Live AbortSignals remain mutable so request cancellation continues to work.
|
|
863
|
-
* @param value - Value to freeze recursively.
|
|
864
|
-
* @returns The same deeply frozen value.
|
|
865
|
-
*/
|
|
866
|
-
function deepFreeze(value) {
|
|
867
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
868
|
-
const pending = [{
|
|
869
|
-
kind: "visit",
|
|
870
|
-
node: value
|
|
871
|
-
}];
|
|
872
|
-
while (pending.length > 0) {
|
|
873
|
-
const task = pending.pop();
|
|
874
|
-
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
875
|
-
if (task === void 0) continue;
|
|
876
|
-
if (task.kind === "property") {
|
|
877
|
-
pending.push({
|
|
878
|
-
kind: "visit",
|
|
879
|
-
node: task.source[task.key]
|
|
880
|
-
});
|
|
881
|
-
continue;
|
|
882
|
-
}
|
|
883
|
-
const node = task.node;
|
|
884
|
-
if (node === null || typeof node !== "object" || node instanceof AbortSignal || seen.has(node)) continue;
|
|
885
|
-
seen.add(node);
|
|
886
|
-
Object.freeze(node);
|
|
887
|
-
const keys = Object.keys(node);
|
|
888
|
-
for (let index = keys.length - 1; index >= 0; index--) {
|
|
889
|
-
const key = keys[index];
|
|
890
|
-
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
891
|
-
if (key === void 0) continue;
|
|
892
|
-
pending.push({
|
|
893
|
-
kind: "property",
|
|
894
|
-
source: node,
|
|
895
|
-
key
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
return value;
|
|
900
|
-
}
|
|
901
|
-
/**
|
|
902
|
-
* Throw for an impossible member of a closed discriminated union.
|
|
903
|
-
* @param value - Value that escaped its closed union type.
|
|
904
|
-
* @param context - Optional switch-site label.
|
|
905
|
-
* @returns Never returns.
|
|
906
|
-
*/
|
|
907
|
-
function assertNever(value, context) {
|
|
908
|
-
const rendered = JSON.stringify(value) ?? String(value);
|
|
909
|
-
throw new Error(`unreachable variant${context === void 0 ? "" : ` in ${context}`}: ${rendered}`);
|
|
910
|
-
}
|
|
911
|
-
//#endregion
|
|
912
|
-
//#region src/runtime/custom-policy.ts
|
|
913
|
-
/** Strict versioned Custom policy parsing and effective-token resolution. */
|
|
914
|
-
const budgetSchema = z.object({
|
|
915
|
-
enabled: z.boolean().required(),
|
|
916
|
-
trigger: z.number().required(),
|
|
917
|
-
target: z.number().required()
|
|
918
|
-
}).required();
|
|
919
|
-
const legacyHistorySchema = z.object({
|
|
920
|
-
enabled: z.boolean().required(),
|
|
921
|
-
trigger: z.number().required(),
|
|
922
|
-
keepRecentTurns: z.number().step(1).min(0).required(),
|
|
923
|
-
keepRecent: z.number().required(),
|
|
924
|
-
minReclaim: z.number().required()
|
|
925
|
-
}).required();
|
|
926
|
-
const historySchema = z.object({
|
|
927
|
-
enabled: z.boolean().required(),
|
|
928
|
-
trigger: z.number().required(),
|
|
929
|
-
keepRecentToolCalls: z.number().step(1).min(0).required(),
|
|
930
|
-
keepRecentTokens: z.number().required(),
|
|
931
|
-
minReclaim: z.number().required()
|
|
932
|
-
}).required();
|
|
933
|
-
const tailTrimSchema = z.object({
|
|
934
|
-
enabled: z.boolean().required(),
|
|
935
|
-
trigger: z.number().required()
|
|
936
|
-
}).required();
|
|
937
|
-
const customCompressionPolicyV1InputSchema = z.object({
|
|
938
|
-
version: z.const(1).required(),
|
|
939
|
-
unit: z.union(["tokens", "context-percent"]).required(),
|
|
940
|
-
fresh: budgetSchema,
|
|
941
|
-
aggregate: budgetSchema,
|
|
942
|
-
history: legacyHistorySchema,
|
|
943
|
-
prefixPolicy: z.union(["preserve", "pressure-break"]).required()
|
|
944
|
-
}).required();
|
|
945
|
-
const customCompressionPolicyV2InputSchema = z.object({
|
|
946
|
-
version: z.const(2).required(),
|
|
947
|
-
unit: z.union(["tokens", "context-percent"]).required(),
|
|
948
|
-
fresh: budgetSchema,
|
|
949
|
-
aggregate: budgetSchema,
|
|
950
|
-
history: legacyHistorySchema,
|
|
951
|
-
prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
|
|
952
|
-
tailTrim: tailTrimSchema
|
|
953
|
-
}).required();
|
|
954
|
-
const customCompressionPolicyV3InputSchema = z.object({
|
|
955
|
-
version: z.const(3).required(),
|
|
956
|
-
unit: z.union(["tokens", "context-percent"]).required(),
|
|
957
|
-
fresh: budgetSchema,
|
|
958
|
-
aggregate: budgetSchema,
|
|
959
|
-
history: historySchema,
|
|
960
|
-
prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
|
|
961
|
-
tailTrim: tailTrimSchema
|
|
962
|
-
}).required();
|
|
963
|
-
/** Canonical Custom document accepted by Host settings and the runtime resolver. */
|
|
964
|
-
const CustomCompressionPolicySchema = z.transform(z.any().required(), (value) => {
|
|
965
|
-
assertExactPolicyShape(value);
|
|
966
|
-
const canonical = canonicalizeCustomPolicy(value.version === 1 ? customCompressionPolicyV1InputSchema(value) : value.version === 2 ? customCompressionPolicyV2InputSchema(value) : customCompressionPolicyV3InputSchema(value));
|
|
967
|
-
assertCanonicalRelations(canonical);
|
|
968
|
-
return deepFreeze(structuredClone(canonical));
|
|
969
|
-
});
|
|
970
|
-
/** Balanced-equivalent Custom policy stored as one token-canonical document. */
|
|
971
|
-
const DEFAULT_CUSTOM_COMPRESSION_POLICY = deepFreeze({
|
|
972
|
-
version: 3,
|
|
973
|
-
unit: "tokens",
|
|
974
|
-
fresh: {
|
|
975
|
-
enabled: true,
|
|
976
|
-
trigger: 8192,
|
|
977
|
-
target: 3072
|
|
978
|
-
},
|
|
979
|
-
aggregate: {
|
|
980
|
-
enabled: true,
|
|
981
|
-
trigger: 32768,
|
|
982
|
-
target: 12288
|
|
983
|
-
},
|
|
984
|
-
history: {
|
|
985
|
-
enabled: true,
|
|
986
|
-
trigger: 5e5,
|
|
987
|
-
keepRecentToolCalls: 10,
|
|
988
|
-
keepRecentTokens: 64e3,
|
|
989
|
-
minReclaim: 96e3
|
|
990
|
-
},
|
|
991
|
-
prefixPolicy: "pressure-break",
|
|
992
|
-
tailTrim: {
|
|
993
|
-
enabled: false,
|
|
994
|
-
trigger: 7e5
|
|
995
|
-
}
|
|
996
|
-
});
|
|
997
|
-
/**
|
|
998
|
-
* Resolve one validated Custom document to the same token policy used by public presets.
|
|
999
|
-
* @param value - untrusted or typed Custom settings value.
|
|
1000
|
-
* @param options - routed model capacity for context-percent documents.
|
|
1001
|
-
* @returns a detached deeply immutable effective token policy.
|
|
1002
|
-
*/
|
|
1003
|
-
function resolveCustomPolicy(value, options = {}) {
|
|
1004
|
-
const policy = canonicalizeCustomPolicy(CustomCompressionPolicySchema(value));
|
|
1005
|
-
const effective = (name, amount) => {
|
|
1006
|
-
if (policy.unit === "tokens") return amount;
|
|
1007
|
-
const contextWindow = options.contextWindowTokens;
|
|
1008
|
-
if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) throw new Error("Custom context-percent policy requires a resolved positive model context window");
|
|
1009
|
-
const tokens = Math.floor(contextWindow * amount / 100);
|
|
1010
|
-
if (!Number.isSafeInteger(tokens) || amount > 0 && tokens <= 0) throw new Error(`Custom ${name} has no valid effective token value for this model`);
|
|
1011
|
-
return tokens;
|
|
1012
|
-
};
|
|
1013
|
-
const resolved = {
|
|
1014
|
-
profile: "custom",
|
|
1015
|
-
nativeToolResultEnabled: false,
|
|
1016
|
-
freshEnabled: policy.fresh.enabled,
|
|
1017
|
-
aggregateEnabled: policy.aggregate.enabled,
|
|
1018
|
-
historyMode: !policy.history.enabled ? "disabled" : policy.prefixPolicy === "preserve" ? "capacity-pressure" : "routine",
|
|
1019
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1020
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1021
|
-
freshTriggerTokens: effective("Fresh trigger", policy.fresh.trigger),
|
|
1022
|
-
freshTargetTokens: effective("Fresh target", policy.fresh.target),
|
|
1023
|
-
aggregateTriggerTokens: effective("Aggregate trigger", policy.aggregate.trigger),
|
|
1024
|
-
aggregateTargetTokens: effective("Aggregate target", policy.aggregate.target),
|
|
1025
|
-
historyTriggerTokens: effective("History trigger", policy.history.trigger),
|
|
1026
|
-
historyKeepRecentToolCalls: policy.history.keepRecentToolCalls,
|
|
1027
|
-
historyKeepRecentTokens: effective("History recent token tail", policy.history.keepRecentTokens),
|
|
1028
|
-
historyMinReclaimTokens: effective("History min-reclaim", policy.history.minReclaim),
|
|
1029
|
-
tailTrim: {
|
|
1030
|
-
enabled: policy.tailTrim.enabled,
|
|
1031
|
-
triggerTokens: effective("TailTrim trigger", policy.tailTrim.trigger)
|
|
1032
|
-
}
|
|
1033
|
-
};
|
|
1034
|
-
assertEffectiveRelations(resolved);
|
|
1035
|
-
return deepFreeze(resolved);
|
|
1036
|
-
}
|
|
1037
|
-
function canonicalizeCustomPolicy(policy) {
|
|
1038
|
-
if (policy.version === 3) return policy;
|
|
1039
|
-
return {
|
|
1040
|
-
version: 3,
|
|
1041
|
-
unit: policy.unit,
|
|
1042
|
-
fresh: policy.fresh,
|
|
1043
|
-
aggregate: policy.aggregate,
|
|
1044
|
-
history: {
|
|
1045
|
-
enabled: policy.history.enabled,
|
|
1046
|
-
trigger: policy.history.trigger,
|
|
1047
|
-
keepRecentToolCalls: 10,
|
|
1048
|
-
keepRecentTokens: policy.history.keepRecent,
|
|
1049
|
-
minReclaim: policy.history.minReclaim
|
|
1050
|
-
},
|
|
1051
|
-
prefixPolicy: policy.prefixPolicy,
|
|
1052
|
-
tailTrim: policy.version === 1 ? {
|
|
1053
|
-
enabled: false,
|
|
1054
|
-
trigger: 7e5
|
|
1055
|
-
} : policy.tailTrim
|
|
1056
|
-
};
|
|
1057
|
-
}
|
|
1058
|
-
function measuredValues(policy) {
|
|
1059
|
-
return [
|
|
1060
|
-
policy.fresh.trigger,
|
|
1061
|
-
policy.fresh.target,
|
|
1062
|
-
policy.aggregate.trigger,
|
|
1063
|
-
policy.aggregate.target,
|
|
1064
|
-
policy.history.trigger,
|
|
1065
|
-
policy.history.keepRecentTokens,
|
|
1066
|
-
policy.history.minReclaim,
|
|
1067
|
-
policy.tailTrim.trigger
|
|
1068
|
-
];
|
|
1069
|
-
}
|
|
1070
|
-
function validMeasuredValues(policy) {
|
|
1071
|
-
const values = measuredValues(policy);
|
|
1072
|
-
if (![
|
|
1073
|
-
policy.fresh.trigger,
|
|
1074
|
-
policy.fresh.target,
|
|
1075
|
-
policy.aggregate.trigger,
|
|
1076
|
-
policy.aggregate.target,
|
|
1077
|
-
policy.history.trigger,
|
|
1078
|
-
policy.history.minReclaim,
|
|
1079
|
-
policy.tailTrim.trigger
|
|
1080
|
-
].every((value) => value > 0) || policy.history.keepRecentTokens < 0 || !Number.isSafeInteger(policy.history.keepRecentToolCalls) || policy.history.keepRecentToolCalls < 0) return false;
|
|
1081
|
-
return policy.unit === "tokens" ? values.every(Number.isSafeInteger) : values.every((value) => Number.isFinite(value) && value <= 100);
|
|
1082
|
-
}
|
|
1083
|
-
function assertCanonicalRelations(policy) {
|
|
1084
|
-
if (!validMeasuredValues(policy)) throw new TypeError("Custom measured values must use the selected canonical unit");
|
|
1085
|
-
if (policy.fresh.target >= policy.fresh.trigger) throw new TypeError("Custom Fresh target must be below trigger");
|
|
1086
|
-
if (policy.aggregate.target >= policy.aggregate.trigger) throw new TypeError("Custom Aggregate target must be below trigger");
|
|
1087
|
-
if (policy.history.minReclaim > policy.history.trigger) throw new TypeError("Custom History min-reclaim must not exceed its trigger");
|
|
1088
|
-
}
|
|
1089
|
-
function assertExactPolicyShape(value) {
|
|
1090
|
-
if (!isPlainRecord$1(value)) throw new TypeError("Custom must be a plain object");
|
|
1091
|
-
if (value.version !== 1 && value.version !== 2 && value.version !== 3) throw new TypeError("Custom version must be 1, 2, or 3");
|
|
1092
|
-
assertExactKeys(value, value.version === 1 ? [
|
|
1093
|
-
"version",
|
|
1094
|
-
"unit",
|
|
1095
|
-
"fresh",
|
|
1096
|
-
"aggregate",
|
|
1097
|
-
"history",
|
|
1098
|
-
"prefixPolicy"
|
|
1099
|
-
] : [
|
|
1100
|
-
"version",
|
|
1101
|
-
"unit",
|
|
1102
|
-
"fresh",
|
|
1103
|
-
"aggregate",
|
|
1104
|
-
"history",
|
|
1105
|
-
"prefixPolicy",
|
|
1106
|
-
"tailTrim"
|
|
1107
|
-
], "Custom");
|
|
1108
|
-
assertExactKeys(value.fresh, [
|
|
1109
|
-
"enabled",
|
|
1110
|
-
"trigger",
|
|
1111
|
-
"target"
|
|
1112
|
-
], "Custom Fresh");
|
|
1113
|
-
assertExactKeys(value.aggregate, [
|
|
1114
|
-
"enabled",
|
|
1115
|
-
"trigger",
|
|
1116
|
-
"target"
|
|
1117
|
-
], "Custom Aggregate");
|
|
1118
|
-
assertExactKeys(value.history, value.version === 3 ? [
|
|
1119
|
-
"enabled",
|
|
1120
|
-
"trigger",
|
|
1121
|
-
"keepRecentToolCalls",
|
|
1122
|
-
"keepRecentTokens",
|
|
1123
|
-
"minReclaim"
|
|
1124
|
-
] : [
|
|
1125
|
-
"enabled",
|
|
1126
|
-
"trigger",
|
|
1127
|
-
"keepRecentTurns",
|
|
1128
|
-
"keepRecent",
|
|
1129
|
-
"minReclaim"
|
|
1130
|
-
], "Custom History");
|
|
1131
|
-
if (value.version !== 1) assertExactKeys(value.tailTrim, ["enabled", "trigger"], "Custom TailTrim");
|
|
1132
|
-
}
|
|
1133
|
-
function assertExactKeys(value, allowed, label) {
|
|
1134
|
-
if (!isPlainRecord$1(value)) throw new TypeError(`${label} must be a plain object`);
|
|
1135
|
-
const allowedKeys = new Set(allowed);
|
|
1136
|
-
const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
|
|
1137
|
-
if (unknown !== void 0) throw new TypeError(`${label}: unknown key "${unknown}"`);
|
|
1138
|
-
}
|
|
1139
|
-
function isPlainRecord$1(value) {
|
|
1140
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1141
|
-
const prototype = Object.getPrototypeOf(value);
|
|
1142
|
-
return prototype === Object.prototype || prototype === null;
|
|
1143
|
-
}
|
|
1144
|
-
function assertEffectiveRelations(policy) {
|
|
1145
|
-
if (policy.freshTargetTokens >= policy.freshTriggerTokens) throw new Error("Custom effective Fresh target must be below trigger");
|
|
1146
|
-
if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens) throw new Error("Custom effective Aggregate target must be below trigger");
|
|
1147
|
-
if (policy.historyMinReclaimTokens > policy.historyTriggerTokens) throw new Error("Custom effective History min-reclaim must not exceed its trigger");
|
|
1148
|
-
}
|
|
1149
|
-
//#endregion
|
|
1150
|
-
//#region src/runtime/config.ts
|
|
1151
|
-
/** Configuration resolution for the mixed deterministic context-compression selector. */
|
|
1152
|
-
/** Settings namespace shared by the Host service and browser selector. */
|
|
1153
|
-
const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
|
|
1154
|
-
/** Fixed native fallback marker. */
|
|
1155
|
-
const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
|
|
1156
|
-
/**
|
|
1157
|
-
* The one Auto Compact threshold contract shared by the settings UI, the
|
|
1158
|
-
* persisted settings schema, and the runtime resolver. Every integer in the
|
|
1159
|
-
* range is valid and entered directly in the UI.
|
|
1160
|
-
*/
|
|
1161
|
-
const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
|
|
1162
|
-
min: 50,
|
|
1163
|
-
max: 90,
|
|
1164
|
-
step: 1,
|
|
1165
|
-
default: 80
|
|
1166
|
-
});
|
|
1167
|
-
/** Narrow one untrusted value to a valid Auto Compact threshold percent. */
|
|
1168
|
-
function isValidAutoCompactThresholdPercent(value) {
|
|
1169
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max;
|
|
1170
|
-
}
|
|
1171
|
-
const AUTO_COMPACT_DEFAULT = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default });
|
|
1172
|
-
/** Accept JSON-object records while rejecting class instances and exotic prototypes. */
|
|
1173
|
-
function isPlainRecord(value) {
|
|
1174
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1175
|
-
const prototype = Object.getPrototypeOf(value);
|
|
1176
|
-
return prototype === Object.prototype || prototype === null;
|
|
1177
|
-
}
|
|
1178
|
-
/** Reject exotic prototypes anywhere in the JSON-like settings tree. */
|
|
1179
|
-
function assertPlainDataTree(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
1180
|
-
if (value === null || typeof value !== "object") return;
|
|
1181
|
-
if (seen.has(value)) return;
|
|
1182
|
-
seen.add(value);
|
|
1183
|
-
if (Array.isArray(value)) {
|
|
1184
|
-
for (const entry of value) assertPlainDataTree(entry, seen);
|
|
1185
|
-
return;
|
|
1186
|
-
}
|
|
1187
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must contain only plain objects");
|
|
1188
|
-
for (const entry of Object.values(value)) assertPlainDataTree(entry, seen);
|
|
1189
|
-
}
|
|
1190
|
-
/**
|
|
1191
|
-
* Strictly parse the persisted autoCompact section. Schemastery object
|
|
1192
|
-
* defaults silently absorb null, empty, and extra-key sections, so this stays
|
|
1193
|
-
* hand-validated beside the top-level unknown-key check.
|
|
1194
|
-
*/
|
|
1195
|
-
function parseAutoCompactSettings(value) {
|
|
1196
|
-
if (value === void 0) return AUTO_COMPACT_DEFAULT;
|
|
1197
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression autoCompact must be a plain object");
|
|
1198
|
-
const keys = Object.keys(value);
|
|
1199
|
-
if (keys.length !== 1 || keys[0] !== "thresholdPercent") throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join("\", \"")}"`);
|
|
1200
|
-
const thresholdPercent = value.thresholdPercent;
|
|
1201
|
-
if (!isValidAutoCompactThresholdPercent(thresholdPercent)) throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
|
|
1202
|
-
return { thresholdPercent };
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Strictly parse the persisted codeSkeleton section. The gate is orthogonal
|
|
1206
|
-
* to every profile: absent inherits the lossless `false` default, while a
|
|
1207
|
-
* present-but-invalid section is an explicitly invalid document.
|
|
1208
|
-
*/
|
|
1209
|
-
function parseCodeSkeletonSettings(value) {
|
|
1210
|
-
if (value === void 0) return { enabled: false };
|
|
1211
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression codeSkeleton must be a plain object");
|
|
1212
|
-
const keys = Object.keys(value);
|
|
1213
|
-
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
1214
|
-
const enabled = value.enabled;
|
|
1215
|
-
if (typeof enabled !== "boolean") throw new TypeError("Context-compression codeSkeleton.enabled must be a boolean");
|
|
1216
|
-
return { enabled };
|
|
1217
|
-
}
|
|
1218
|
-
/**
|
|
1219
|
-
* Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
|
|
1220
|
-
* section semantics: absent inherits the lossless `false` default, while a
|
|
1221
|
-
* present-but-invalid section is an explicitly invalid document.
|
|
1222
|
-
*/
|
|
1223
|
-
function parseIntentSummarySettings(value) {
|
|
1224
|
-
if (value === void 0) return { enabled: false };
|
|
1225
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
|
|
1226
|
-
const keys = Object.keys(value);
|
|
1227
|
-
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
1228
|
-
const enabled = value.enabled;
|
|
1229
|
-
if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
|
|
1230
|
-
return { enabled };
|
|
1231
|
-
}
|
|
1232
|
-
/**
|
|
1233
|
-
* Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
|
|
1234
|
-
* section semantics: absent inherits the hidden default, while a
|
|
1235
|
-
* present-but-invalid section is an explicitly invalid document.
|
|
1236
|
-
*/
|
|
1237
|
-
function parseMonitorPanelSettings(value) {
|
|
1238
|
-
if (value === void 0) return { enabled: false };
|
|
1239
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression monitorPanel must be a plain object");
|
|
1240
|
-
const keys = Object.keys(value);
|
|
1241
|
-
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
1242
|
-
const enabled = value.enabled;
|
|
1243
|
-
if (typeof enabled !== "boolean") throw new TypeError("Context-compression monitorPanel.enabled must be a boolean");
|
|
1244
|
-
return { enabled };
|
|
1245
|
-
}
|
|
1246
|
-
/**
|
|
1247
|
-
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
1248
|
-
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
1249
|
-
* codeSkeleton section semantics.
|
|
1250
|
-
*/
|
|
1251
|
-
function parsePresetOptionsSettings(value) {
|
|
1252
|
-
if (value === void 0) return void 0;
|
|
1253
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression presetOptions must be a plain object");
|
|
1254
|
-
const allowed = /* @__PURE__ */ new Set([
|
|
1255
|
-
"dedupeToolResults",
|
|
1256
|
-
"summaryLocator",
|
|
1257
|
-
"prefixStabilizer",
|
|
1258
|
-
"readState",
|
|
1259
|
-
"estimatorMode",
|
|
1260
|
-
"estimatorProvider",
|
|
1261
|
-
"estimatorModel",
|
|
1262
|
-
"estimatorBaseUrl",
|
|
1263
|
-
"estimatorApiKey",
|
|
1264
|
-
"estimatorTimeoutMs",
|
|
1265
|
-
"reviewMode",
|
|
1266
|
-
"reviewTimeoutTurns",
|
|
1267
|
-
"cacheHitDiscountAlpha",
|
|
1268
|
-
"reviewHighImpactTokens",
|
|
1269
|
-
"advisorMode",
|
|
1270
|
-
"advisorTimeoutMs",
|
|
1271
|
-
"advisorRefreshTurns",
|
|
1272
|
-
"advisorScoreThreshold",
|
|
1273
|
-
"advisorSampleLimit",
|
|
1274
|
-
"advisorMinTokens"
|
|
1275
|
-
]);
|
|
1276
|
-
const unknown = Object.keys(value).find((key) => !allowed.has(key));
|
|
1277
|
-
if (unknown !== void 0) throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`);
|
|
1278
|
-
for (const key of [
|
|
1279
|
-
"dedupeToolResults",
|
|
1280
|
-
"summaryLocator",
|
|
1281
|
-
"prefixStabilizer",
|
|
1282
|
-
"readState"
|
|
1283
|
-
]) {
|
|
1284
|
-
const entry = value[key];
|
|
1285
|
-
if (entry !== void 0 && typeof entry !== "boolean") throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`);
|
|
1286
|
-
}
|
|
1287
|
-
const estimatorMode = value.estimatorMode;
|
|
1288
|
-
if (estimatorMode !== void 0 && estimatorMode !== "" && estimatorMode !== "host" && estimatorMode !== "direct") throw new TypeError("Context-compression presetOptions.estimatorMode must be \"\", \"host\", or \"direct\"");
|
|
1289
|
-
const advisorMode = value.advisorMode;
|
|
1290
|
-
if (advisorMode !== void 0 && advisorMode !== "" && advisorMode !== "host" && advisorMode !== "direct") throw new TypeError("Context-compression presetOptions.advisorMode must be \"\", \"host\", or \"direct\"");
|
|
1291
|
-
const advisorTimeoutMs = value.advisorTimeoutMs;
|
|
1292
|
-
if (advisorTimeoutMs !== void 0 && (typeof advisorTimeoutMs !== "number" || !Number.isSafeInteger(advisorTimeoutMs) || advisorTimeoutMs < 100 || advisorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000");
|
|
1293
|
-
const advisorRefreshTurns = value.advisorRefreshTurns;
|
|
1294
|
-
if (advisorRefreshTurns !== void 0 && (typeof advisorRefreshTurns !== "number" || !Number.isSafeInteger(advisorRefreshTurns) || advisorRefreshTurns < 1)) throw new TypeError("Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1");
|
|
1295
|
-
const advisorScoreThreshold = value.advisorScoreThreshold;
|
|
1296
|
-
if (advisorScoreThreshold !== void 0 && (typeof advisorScoreThreshold !== "number" || !Number.isFinite(advisorScoreThreshold) || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) throw new TypeError("Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1");
|
|
1297
|
-
const advisorSampleLimit = value.advisorSampleLimit;
|
|
1298
|
-
if (advisorSampleLimit !== void 0 && (typeof advisorSampleLimit !== "number" || !Number.isSafeInteger(advisorSampleLimit) || advisorSampleLimit < 1 || advisorSampleLimit > 64)) throw new TypeError("Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64");
|
|
1299
|
-
const advisorMinTokens = value.advisorMinTokens;
|
|
1300
|
-
if (advisorMinTokens !== void 0 && (typeof advisorMinTokens !== "number" || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) throw new TypeError("Context-compression presetOptions.advisorMinTokens must be a positive integer");
|
|
1301
|
-
const estimatorTimeoutMs = value.estimatorTimeoutMs;
|
|
1302
|
-
if (estimatorTimeoutMs !== void 0 && (typeof estimatorTimeoutMs !== "number" || !Number.isSafeInteger(estimatorTimeoutMs) || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000");
|
|
1303
|
-
for (const key of [
|
|
1304
|
-
"estimatorProvider",
|
|
1305
|
-
"estimatorModel",
|
|
1306
|
-
"estimatorBaseUrl",
|
|
1307
|
-
"estimatorApiKey"
|
|
1308
|
-
]) {
|
|
1309
|
-
const entry = value[key];
|
|
1310
|
-
if (entry !== void 0 && typeof entry !== "string") throw new TypeError(`Context-compression presetOptions.${key} must be a string`);
|
|
1311
|
-
}
|
|
1312
|
-
const result = {};
|
|
1313
|
-
if (value.dedupeToolResults !== void 0) result.dedupeToolResults = value.dedupeToolResults;
|
|
1314
|
-
if (value.summaryLocator !== void 0) result.summaryLocator = value.summaryLocator;
|
|
1315
|
-
if (value.prefixStabilizer !== void 0) result.prefixStabilizer = value.prefixStabilizer;
|
|
1316
|
-
if (value.readState !== void 0) result.readState = value.readState;
|
|
1317
|
-
if (estimatorMode !== void 0) result.estimatorMode = estimatorMode;
|
|
1318
|
-
if (value.estimatorProvider !== void 0) result.estimatorProvider = value.estimatorProvider;
|
|
1319
|
-
if (value.estimatorModel !== void 0) result.estimatorModel = value.estimatorModel;
|
|
1320
|
-
if (value.estimatorBaseUrl !== void 0) result.estimatorBaseUrl = value.estimatorBaseUrl;
|
|
1321
|
-
if (value.estimatorApiKey !== void 0) result.estimatorApiKey = value.estimatorApiKey;
|
|
1322
|
-
if (estimatorTimeoutMs !== void 0) result.estimatorTimeoutMs = estimatorTimeoutMs;
|
|
1323
|
-
if (advisorMode !== void 0) result.advisorMode = advisorMode;
|
|
1324
|
-
if (advisorTimeoutMs !== void 0) result.advisorTimeoutMs = advisorTimeoutMs;
|
|
1325
|
-
if (advisorRefreshTurns !== void 0) result.advisorRefreshTurns = advisorRefreshTurns;
|
|
1326
|
-
if (advisorScoreThreshold !== void 0) result.advisorScoreThreshold = advisorScoreThreshold;
|
|
1327
|
-
if (advisorSampleLimit !== void 0) result.advisorSampleLimit = advisorSampleLimit;
|
|
1328
|
-
if (advisorMinTokens !== void 0) result.advisorMinTokens = advisorMinTokens;
|
|
1329
|
-
return result;
|
|
1330
|
-
}
|
|
1331
|
-
/** Settings schema used by the user-facing profile selector. */
|
|
1332
|
-
const contextCompressionSettingsInputSchema = z.object({
|
|
1333
|
-
profile: z.union([...COMPRESSION_PROFILES]).default("balanced"),
|
|
1334
|
-
custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY)
|
|
1335
|
-
});
|
|
1336
|
-
/**
|
|
1337
|
-
* Reject a section that is PRESENT but not a usable value. Schemastery
|
|
1338
|
-
* `.default(...)` silently substitutes null and undefined, which would turn a
|
|
1339
|
-
* hand-corrupted store into the (lossy) default policy; only genuinely absent
|
|
1340
|
-
* keys may inherit defaults, and that distinction must be made before any
|
|
1341
|
-
* default can fire.
|
|
1342
|
-
*/
|
|
1343
|
-
function assertPresentSection(candidate, key, valid) {
|
|
1344
|
-
if (!Object.hasOwn(candidate, key)) return;
|
|
1345
|
-
if (!valid(candidate[key])) throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`);
|
|
1346
|
-
}
|
|
1347
|
-
const isSupportedProfile = (value) => typeof value === "string" && COMPRESSION_PROFILES.includes(value);
|
|
1348
|
-
const isUsableCustomDocument = (value) => isPlainRecord(value);
|
|
1349
|
-
const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
|
|
1350
|
-
profile: "balanced",
|
|
1351
|
-
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
1352
|
-
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
1353
|
-
codeSkeleton: { enabled: false },
|
|
1354
|
-
intentSummary: { enabled: false },
|
|
1355
|
-
monitorPanel: { enabled: false }
|
|
1356
|
-
};
|
|
1357
|
-
/**
|
|
1358
|
-
* Parse one settings document with the persisted-section semantics: `undefined`
|
|
1359
|
-
* inherits the defaults (an absent section), while `null` is an explicitly
|
|
1360
|
-
* invalid document and must never silently become the default policy.
|
|
1361
|
-
*/
|
|
1362
|
-
function parseContextCompressionSettings(value) {
|
|
1363
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
1364
|
-
const keys = Object.keys(value);
|
|
1365
|
-
if (keys.length === 0 || !keys.includes("profile") || !keys.includes("custom")) throw new TypeError("Context-compression settings document is missing its complete shape");
|
|
1366
|
-
return ContextCompressionSettingsSchema(value);
|
|
1367
|
-
}
|
|
1368
|
-
/** Settings schema used by the user-facing profile selector. */
|
|
1369
|
-
const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value) => {
|
|
1370
|
-
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
1371
|
-
assertPlainDataTree(value);
|
|
1372
|
-
const candidate = structuredClone(value);
|
|
1373
|
-
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
|
|
1374
|
-
if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
|
|
1375
|
-
assertPresentSection(candidate, "profile", isSupportedProfile);
|
|
1376
|
-
assertPresentSection(candidate, "custom", isUsableCustomDocument);
|
|
1377
|
-
const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
|
|
1378
|
-
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
|
|
1379
|
-
const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
|
|
1380
|
-
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
|
|
1381
|
-
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
|
|
1382
|
-
return {
|
|
1383
|
-
...contextCompressionSettingsInputSchema(candidate),
|
|
1384
|
-
autoCompact,
|
|
1385
|
-
codeSkeleton,
|
|
1386
|
-
intentSummary,
|
|
1387
|
-
monitorPanel,
|
|
1388
|
-
...presetOptions === void 0 ? {} : { presetOptions }
|
|
1389
|
-
};
|
|
1390
|
-
}).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
|
|
1391
|
-
/** Low-friction defaults; token budgets live in resolved profile policy. */
|
|
1392
|
-
const DEFAULTS = deepFreeze({
|
|
1393
|
-
profile: "balanced",
|
|
1394
|
-
headChars: 4096,
|
|
1395
|
-
tailChars: 1024
|
|
1396
|
-
});
|
|
1397
|
-
const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
1398
|
-
"profile",
|
|
1399
|
-
"headChars",
|
|
1400
|
-
"tailChars",
|
|
1401
|
-
"nativeTriggerTokens",
|
|
1402
|
-
"nativeTargetTokens",
|
|
1403
|
-
"freshTriggerTokens",
|
|
1404
|
-
"freshTargetTokens",
|
|
1405
|
-
"aggregateTriggerTokens",
|
|
1406
|
-
"aggregateTargetTokens",
|
|
1407
|
-
"historyTriggerTokens",
|
|
1408
|
-
"historyKeepRecentToolCalls",
|
|
1409
|
-
"historyKeepRecentTokens",
|
|
1410
|
-
"historyMinReclaimTokens",
|
|
1411
|
-
"readInputCapChars",
|
|
1412
|
-
"autoCompactThresholdPercent",
|
|
1413
|
-
"presetOptions"
|
|
1414
|
-
]);
|
|
1415
|
-
const LEGACY_GATE_REPLACEMENTS = Object.freeze({
|
|
1416
|
-
thresholdChars: "nativeTriggerTokens",
|
|
1417
|
-
freshThresholdChars: "freshTriggerTokens",
|
|
1418
|
-
freshTargetChars: "freshTargetTokens",
|
|
1419
|
-
freshBatchTriggerChars: "aggregateTriggerTokens",
|
|
1420
|
-
freshBatchTargetChars: "aggregateTargetTokens",
|
|
1421
|
-
historyTriggerChars: "historyTriggerTokens",
|
|
1422
|
-
historyKeepRecentChars: "historyKeepRecentTokens",
|
|
1423
|
-
historyMinReclaimChars: "historyMinReclaimTokens",
|
|
1424
|
-
historyKeepRecentTurns: "historyKeepRecentToolCalls"
|
|
1425
|
-
});
|
|
1426
|
-
/**
|
|
1427
|
-
* Count Unicode code points without splitting surrogate pairs.
|
|
1428
|
-
* @param text - text whose code points are counted.
|
|
1429
|
-
* @returns the number of Unicode code points.
|
|
1430
|
-
*/
|
|
1431
|
-
function codePointLength(text) {
|
|
1432
|
-
let length = 0;
|
|
1433
|
-
for (const _point of text) length++;
|
|
1434
|
-
return length;
|
|
1435
|
-
}
|
|
1436
|
-
/** Express one token-named policy gate on the character basis. */
|
|
1437
|
-
function charsForTokens(tokens) {
|
|
1438
|
-
return tokens * 4;
|
|
1439
|
-
}
|
|
1440
|
-
/** Derive the telemetry-only token figure from a character measurement. */
|
|
1441
|
-
function charsToTokens(chars) {
|
|
1442
|
-
if (!Number.isFinite(chars) || chars <= 0) return 0;
|
|
1443
|
-
return Math.max(1, Math.round(chars / 4));
|
|
1444
|
-
}
|
|
1445
|
-
/**
|
|
1446
|
-
* Test whether a settings value names a supported compression profile.
|
|
1447
|
-
* @param value - untrusted settings value.
|
|
1448
|
-
* @returns whether the value is a supported compression profile.
|
|
1449
|
-
*/
|
|
1450
|
-
function isCompressionProfile(value) {
|
|
1451
|
-
return typeof value === "string" && COMPRESSION_PROFILES.includes(value);
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Resolve and validate plugin configuration.
|
|
1455
|
-
* @param config - optional composition overrides.
|
|
1456
|
-
* @returns a detached, deeply immutable configuration snapshot.
|
|
1457
|
-
*/
|
|
1458
|
-
function resolveConfig(config = {}) {
|
|
1459
|
-
for (const key of Object.keys(config)) {
|
|
1460
|
-
const replacement = LEGACY_GATE_REPLACEMENTS[key];
|
|
1461
|
-
if (replacement !== void 0) throw new Error(`ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; choose "${replacement}" manually in tokens (no character conversion is applied)`);
|
|
1462
|
-
if (!CONFIG_KEYS.has(key)) throw new Error(`ToolResultPruneConfig: unknown key "${key}"`);
|
|
1463
|
-
}
|
|
1464
|
-
const resolved = {
|
|
1465
|
-
profile: config.profile ?? DEFAULTS.profile,
|
|
1466
|
-
headChars: config.headChars ?? DEFAULTS.headChars,
|
|
1467
|
-
tailChars: config.tailChars ?? DEFAULTS.tailChars,
|
|
1468
|
-
...config.nativeTriggerTokens === void 0 ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
|
|
1469
|
-
...config.nativeTargetTokens === void 0 ? {} : { nativeTargetTokens: config.nativeTargetTokens },
|
|
1470
|
-
...config.freshTriggerTokens === void 0 ? {} : { freshTriggerTokens: config.freshTriggerTokens },
|
|
1471
|
-
...config.freshTargetTokens === void 0 ? {} : { freshTargetTokens: config.freshTargetTokens },
|
|
1472
|
-
...config.aggregateTriggerTokens === void 0 ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
|
|
1473
|
-
...config.aggregateTargetTokens === void 0 ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
|
|
1474
|
-
...config.historyTriggerTokens === void 0 ? {} : { historyTriggerTokens: config.historyTriggerTokens },
|
|
1475
|
-
...config.historyKeepRecentToolCalls === void 0 ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
|
|
1476
|
-
...config.historyKeepRecentTokens === void 0 ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
|
|
1477
|
-
...config.historyMinReclaimTokens === void 0 ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
|
|
1478
|
-
...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
|
|
1479
|
-
...config.autoCompactThresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
|
|
1480
|
-
...config.presetOptions === void 0 ? {} : { presetOptions: config.presetOptions }
|
|
1481
|
-
};
|
|
1482
|
-
if (!isCompressionProfile(resolved.profile)) throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`);
|
|
1483
|
-
assertNonNegativeInteger("headChars", resolved.headChars);
|
|
1484
|
-
assertNonNegativeInteger("tailChars", resolved.tailChars);
|
|
1485
|
-
for (const key of [
|
|
1486
|
-
"nativeTriggerTokens",
|
|
1487
|
-
"nativeTargetTokens",
|
|
1488
|
-
"freshTriggerTokens",
|
|
1489
|
-
"freshTargetTokens",
|
|
1490
|
-
"aggregateTriggerTokens",
|
|
1491
|
-
"aggregateTargetTokens",
|
|
1492
|
-
"historyTriggerTokens",
|
|
1493
|
-
"historyMinReclaimTokens",
|
|
1494
|
-
"readInputCapChars"
|
|
1495
|
-
]) {
|
|
1496
|
-
const value = resolved[key];
|
|
1497
|
-
if (value !== void 0) assertPositiveInteger(key, value);
|
|
1498
|
-
}
|
|
1499
|
-
if (resolved.historyKeepRecentToolCalls !== void 0) assertNonNegativeInteger("historyKeepRecentToolCalls", resolved.historyKeepRecentToolCalls);
|
|
1500
|
-
if (resolved.historyKeepRecentTokens !== void 0) assertNonNegativeInteger("historyKeepRecentTokens", resolved.historyKeepRecentTokens);
|
|
1501
|
-
if (resolved.autoCompactThresholdPercent !== void 0 && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
|
|
1502
|
-
assertTargetBelowTrigger("native", resolved.nativeTargetTokens, resolved.nativeTriggerTokens);
|
|
1503
|
-
assertTargetBelowTrigger("fresh", resolved.freshTargetTokens, resolved.freshTriggerTokens);
|
|
1504
|
-
assertTargetBelowTrigger("aggregate", resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens);
|
|
1505
|
-
return deepFreeze(structuredClone(resolved));
|
|
1506
|
-
}
|
|
1507
|
-
/** Per-profile History linkage ratios applied to the Auto Compact watermark. */
|
|
1508
|
-
const AUTO_COMPACT_HISTORY_RATIOS = Object.freeze({
|
|
1509
|
-
balanced: Object.freeze({
|
|
1510
|
-
trigger: .625,
|
|
1511
|
-
minReclaim: .12,
|
|
1512
|
-
keepRecentTokens: .08
|
|
1513
|
-
}),
|
|
1514
|
-
savings: Object.freeze({
|
|
1515
|
-
trigger: .5,
|
|
1516
|
-
minReclaim: .16,
|
|
1517
|
-
keepRecentTokens: .08
|
|
1518
|
-
}),
|
|
1519
|
-
"cache-strict": Object.freeze({
|
|
1520
|
-
trigger: .75,
|
|
1521
|
-
minReclaim: .16,
|
|
1522
|
-
keepRecentTokens: .08
|
|
1523
|
-
}),
|
|
1524
|
-
adaptive: Object.freeze({
|
|
1525
|
-
trigger: .625,
|
|
1526
|
-
minReclaim: .12,
|
|
1527
|
-
keepRecentTokens: .08
|
|
1528
|
-
}),
|
|
1529
|
-
"tokenpilot-inspired": Object.freeze({
|
|
1530
|
-
trigger: .625,
|
|
1531
|
-
minReclaim: .12,
|
|
1532
|
-
keepRecentTokens: .08
|
|
1533
|
-
})
|
|
1534
|
-
});
|
|
1535
|
-
/** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
|
|
1536
|
-
const MICRO_DEADLINE_RATIO = .875;
|
|
1537
|
-
/**
|
|
1538
|
-
* TokenPilot-inspired sub-capability defaults. Every capability is on except
|
|
1539
|
-
* the estimator, which requires an explicit endpoint channel (host or direct)
|
|
1540
|
-
* before any consumer may leave its rule-only fallback.
|
|
1541
|
-
*/
|
|
1542
|
-
const PRESET_OPTION_DEFAULTS = deepFreeze({
|
|
1543
|
-
noNetSavingsGuard: true,
|
|
1544
|
-
skipReductionRecovery: true,
|
|
1545
|
-
dedupeToolResults: true,
|
|
1546
|
-
summaryLocator: true,
|
|
1547
|
-
prefixStabilizer: true,
|
|
1548
|
-
readState: true,
|
|
1549
|
-
estimator: { mode: "" },
|
|
1550
|
-
advisor: {
|
|
1551
|
-
mode: "",
|
|
1552
|
-
timeoutMs: 8e3,
|
|
1553
|
-
refreshTurns: 8,
|
|
1554
|
-
scoreThreshold: .35,
|
|
1555
|
-
sampleLimit: 16,
|
|
1556
|
-
minTokens: 250
|
|
1557
|
-
}
|
|
1558
|
-
});
|
|
1559
|
-
/**
|
|
1560
|
-
* Merge persisted presetOptions overrides over the tokenpilot-inspired
|
|
1561
|
-
* defaults. Persisted booleans are three-state (undefined = inherit); the
|
|
1562
|
-
* estimator channel overrides the default empty mode wholesale.
|
|
1563
|
-
*/
|
|
1564
|
-
function mergePresetOptions(overrides) {
|
|
1565
|
-
if (overrides === void 0) return PRESET_OPTION_DEFAULTS;
|
|
1566
|
-
return deepFreeze({
|
|
1567
|
-
noNetSavingsGuard: true,
|
|
1568
|
-
skipReductionRecovery: true,
|
|
1569
|
-
dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
|
|
1570
|
-
summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
|
|
1571
|
-
prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
|
|
1572
|
-
readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
|
|
1573
|
-
estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
|
|
1574
|
-
advisor: {
|
|
1575
|
-
mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
|
|
1576
|
-
timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
|
|
1577
|
-
refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
|
|
1578
|
-
scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
|
|
1579
|
-
sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
|
|
1580
|
-
minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens
|
|
1581
|
-
}
|
|
1582
|
-
});
|
|
1583
|
-
}
|
|
1584
|
-
/**
|
|
1585
|
-
* Resolve the Auto-Compact-linked History watermarks for one standard profile.
|
|
1586
|
-
*
|
|
1587
|
-
* `A = floor(C × a)` is the Auto Compact token watermark for the routed
|
|
1588
|
-
* context window `C` and the user threshold `a = p / 100`; the History
|
|
1589
|
-
* trigger, minimum reclaim, and recent-token tail scale with `A`, and the
|
|
1590
|
-
* micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
|
|
1591
|
-
* defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
|
|
1592
|
-
* preset numbers exactly. Custom stays manual and Off/Native run no History,
|
|
1593
|
-
* so none of them link.
|
|
1594
|
-
*/
|
|
1595
|
-
function resolveAutoCompactLinkage(profile, options) {
|
|
1596
|
-
const ratios = profile === "custom" ? void 0 : AUTO_COMPACT_HISTORY_RATIOS[profile];
|
|
1597
|
-
const contextWindow = options.contextWindowTokens;
|
|
1598
|
-
const threshold = options.autoCompactThresholdPercent;
|
|
1599
|
-
if (ratios === void 0) return void 0;
|
|
1600
|
-
if (!isValidAutoCompactThresholdPercent(threshold)) return void 0;
|
|
1601
|
-
if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) return void 0;
|
|
1602
|
-
const autoCompactTokens = Math.floor(contextWindow * (threshold / 100));
|
|
1603
|
-
if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return void 0;
|
|
1604
|
-
const linked = {
|
|
1605
|
-
autoCompactTokens,
|
|
1606
|
-
microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
|
|
1607
|
-
historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
|
|
1608
|
-
historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
|
|
1609
|
-
historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens)
|
|
1610
|
-
};
|
|
1611
|
-
for (const value of Object.values(linked)) if (!Number.isSafeInteger(value) || value <= 0) return void 0;
|
|
1612
|
-
return linked;
|
|
1613
|
-
}
|
|
1614
|
-
/**
|
|
1615
|
-
* Resolve one public profile into a complete mixed-strategy policy.
|
|
1616
|
-
* @param config - validated composition configuration.
|
|
1617
|
-
* @param profile - profile frozen for the target Session.
|
|
1618
|
-
* @param custom - versioned Custom document used only by the `custom` profile.
|
|
1619
|
-
* @param options - routed capacity and the frozen Auto Compact threshold used
|
|
1620
|
-
* to resolve context-percent Custom values and standard-profile linkage.
|
|
1621
|
-
* @returns the effective deterministic compression policy.
|
|
1622
|
-
*/
|
|
1623
|
-
function resolvePolicy(config, profile, custom = DEFAULT_CUSTOM_COMPRESSION_POLICY, options = {}) {
|
|
1624
|
-
if (profile === "custom") return resolveCustomPolicy(custom, options);
|
|
1625
|
-
const preset = {
|
|
1626
|
-
off: {
|
|
1627
|
-
nativeToolResultEnabled: false,
|
|
1628
|
-
freshEnabled: false,
|
|
1629
|
-
aggregateEnabled: false,
|
|
1630
|
-
historyMode: "disabled",
|
|
1631
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1632
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1633
|
-
freshTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1634
|
-
freshTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1635
|
-
aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1636
|
-
aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1637
|
-
historyTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1638
|
-
historyKeepRecentToolCalls: 10,
|
|
1639
|
-
historyKeepRecentTokens: 64e3,
|
|
1640
|
-
historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
|
|
1641
|
-
},
|
|
1642
|
-
native: {
|
|
1643
|
-
nativeToolResultEnabled: true,
|
|
1644
|
-
freshEnabled: false,
|
|
1645
|
-
aggregateEnabled: false,
|
|
1646
|
-
historyMode: "disabled",
|
|
1647
|
-
nativeTriggerTokens: 4096,
|
|
1648
|
-
nativeTargetTokens: 2048,
|
|
1649
|
-
freshTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1650
|
-
freshTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1651
|
-
aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1652
|
-
aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1653
|
-
historyTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1654
|
-
historyKeepRecentToolCalls: 10,
|
|
1655
|
-
historyKeepRecentTokens: 64e3,
|
|
1656
|
-
historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
|
|
1657
|
-
},
|
|
1658
|
-
balanced: {
|
|
1659
|
-
nativeToolResultEnabled: false,
|
|
1660
|
-
freshEnabled: true,
|
|
1661
|
-
aggregateEnabled: true,
|
|
1662
|
-
historyMode: "routine",
|
|
1663
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1664
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1665
|
-
freshTriggerTokens: 8192,
|
|
1666
|
-
freshTargetTokens: 3072,
|
|
1667
|
-
aggregateTriggerTokens: 32768,
|
|
1668
|
-
aggregateTargetTokens: 12288,
|
|
1669
|
-
historyTriggerTokens: 5e5,
|
|
1670
|
-
historyKeepRecentToolCalls: 10,
|
|
1671
|
-
historyKeepRecentTokens: 64e3,
|
|
1672
|
-
historyMinReclaimTokens: 96e3
|
|
1673
|
-
},
|
|
1674
|
-
"cache-strict": {
|
|
1675
|
-
nativeToolResultEnabled: false,
|
|
1676
|
-
freshEnabled: true,
|
|
1677
|
-
aggregateEnabled: true,
|
|
1678
|
-
historyMode: "capacity-pressure",
|
|
1679
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1680
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1681
|
-
freshTriggerTokens: 8192,
|
|
1682
|
-
freshTargetTokens: 3072,
|
|
1683
|
-
aggregateTriggerTokens: 32768,
|
|
1684
|
-
aggregateTargetTokens: 12288,
|
|
1685
|
-
historyTriggerTokens: 6e5,
|
|
1686
|
-
historyKeepRecentToolCalls: 10,
|
|
1687
|
-
historyKeepRecentTokens: 64e3,
|
|
1688
|
-
historyMinReclaimTokens: 128e3
|
|
1689
|
-
},
|
|
1690
|
-
savings: {
|
|
1691
|
-
nativeToolResultEnabled: false,
|
|
1692
|
-
freshEnabled: true,
|
|
1693
|
-
aggregateEnabled: true,
|
|
1694
|
-
historyMode: "routine",
|
|
1695
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1696
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1697
|
-
freshTriggerTokens: 4096,
|
|
1698
|
-
freshTargetTokens: 1536,
|
|
1699
|
-
aggregateTriggerTokens: 16384,
|
|
1700
|
-
aggregateTargetTokens: 4096,
|
|
1701
|
-
historyTriggerTokens: 4e5,
|
|
1702
|
-
historyKeepRecentToolCalls: 10,
|
|
1703
|
-
historyKeepRecentTokens: 64e3,
|
|
1704
|
-
historyMinReclaimTokens: 128e3
|
|
1705
|
-
},
|
|
1706
|
-
adaptive: {
|
|
1707
|
-
nativeToolResultEnabled: false,
|
|
1708
|
-
freshEnabled: true,
|
|
1709
|
-
aggregateEnabled: true,
|
|
1710
|
-
historyMode: "adaptive",
|
|
1711
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1712
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1713
|
-
freshTriggerTokens: 8192,
|
|
1714
|
-
freshTargetTokens: 3072,
|
|
1715
|
-
aggregateTriggerTokens: 32768,
|
|
1716
|
-
aggregateTargetTokens: 12288,
|
|
1717
|
-
historyTriggerTokens: 5e5,
|
|
1718
|
-
historyKeepRecentToolCalls: 10,
|
|
1719
|
-
historyKeepRecentTokens: 64e3,
|
|
1720
|
-
historyMinReclaimTokens: 96e3
|
|
1721
|
-
},
|
|
1722
|
-
"tokenpilot-inspired": {
|
|
1723
|
-
nativeToolResultEnabled: false,
|
|
1724
|
-
freshEnabled: true,
|
|
1725
|
-
aggregateEnabled: true,
|
|
1726
|
-
historyMode: "routine",
|
|
1727
|
-
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1728
|
-
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1729
|
-
freshTriggerTokens: 4096,
|
|
1730
|
-
freshTargetTokens: 1536,
|
|
1731
|
-
aggregateTriggerTokens: 32768,
|
|
1732
|
-
aggregateTargetTokens: 12288,
|
|
1733
|
-
historyTriggerTokens: 5e5,
|
|
1734
|
-
historyKeepRecentToolCalls: 10,
|
|
1735
|
-
historyKeepRecentTokens: 64e3,
|
|
1736
|
-
historyMinReclaimTokens: 96e3
|
|
1737
|
-
}
|
|
1738
|
-
}[profile];
|
|
1739
|
-
const linkage = resolveAutoCompactLinkage(profile, options);
|
|
1740
|
-
const policy = {
|
|
1741
|
-
profile,
|
|
1742
|
-
...preset,
|
|
1743
|
-
nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
|
|
1744
|
-
nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
|
|
1745
|
-
freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
|
|
1746
|
-
freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
|
|
1747
|
-
aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
|
|
1748
|
-
aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
|
|
1749
|
-
historyTriggerTokens: config.historyTriggerTokens ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
|
|
1750
|
-
historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
|
|
1751
|
-
historyKeepRecentTokens: config.historyKeepRecentTokens ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
|
|
1752
|
-
historyMinReclaimTokens: config.historyMinReclaimTokens ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
|
|
1753
|
-
...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
|
|
1754
|
-
...linkage === void 0 ? {} : {
|
|
1755
|
-
autoCompactTokens: linkage.autoCompactTokens,
|
|
1756
|
-
microDeadlineTokens: linkage.microDeadlineTokens
|
|
1757
|
-
},
|
|
1758
|
-
...profile === "tokenpilot-inspired" ? { presetOptions: mergePresetOptions(config.presetOptions) } : {}
|
|
1759
|
-
};
|
|
1760
|
-
if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === "native") throw new Error("context compression policy: native target must be below trigger");
|
|
1761
|
-
if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: fresh target must be below trigger");
|
|
1762
|
-
if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: aggregate target must be below trigger");
|
|
1763
|
-
if (policy.readInputCapChars !== void 0 && policy.readInputCapChars <= policy.freshTriggerTokens * 4) throw new Error("context compression policy: read input cap would silence the fresh path");
|
|
1764
|
-
return deepFreeze(policy);
|
|
1765
|
-
}
|
|
1766
|
-
function assertTargetBelowTrigger(label, target, trigger) {
|
|
1767
|
-
if (target === void 0 !== (trigger === void 0)) throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`);
|
|
1768
|
-
if (target !== void 0 && trigger !== void 0 && target >= trigger) throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`);
|
|
1769
|
-
}
|
|
1770
|
-
function assertPositiveInteger(name, value) {
|
|
1771
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`);
|
|
1772
|
-
}
|
|
1773
|
-
function assertNonNegativeInteger(name, value) {
|
|
1774
|
-
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
|
|
1775
|
-
}
|
|
1776
|
-
//#endregion
|
|
1777
|
-
export { getLastIntentFold as A, decimalRateNanoUnits as B, estimateSavingsPricing as C, INTENT_GATE_GROWTH_TOKENS as D, INTENT_GATE_FLOOR_FRACTION as E, recordIntentFold as F, resolveOfficialDeepSeekPrice as H, recordRecertified as I, recordScore as L, getSummaryOverride as M, invalidateOnTaskChange as N, evaluateIntentGate as O, observeIntentEnabled as P, setSummaryOverride as R, buildMonitorSnapshot as S, observeContextUsage as T, getSavingsLedger as U, priceOfficialDeepSeekUsage as V, savingsHash as W, resolveCustomPolicy as _, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as a, COMPRESSION_PROFILES as b, charsToTokens as c, isValidAutoCompactThresholdPercent as d, parseContextCompressionSettings as f, DEFAULT_CUSTOM_COMPRESSION_POLICY as g, CustomCompressionPolicySchema as h, DEFAULTS as i, getObservedIntentEnabled as j, getAdvisorState as k, codePointLength as l, resolvePolicy as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, PRUNE_MARKER as o, resolveConfig as p, ContextCompressionSettingsSchema as r, charsForTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isCompressionProfile as u, assertNever as v, isSessionOverrideAction as w, applySessionOverride as x, deepFreeze as y, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as z };
|