dsh-context-compression-improved 0.9.8 → 0.9.9
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/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/CHANGELOG.md +4 -0
- package/README.md +14 -2
- package/README.zh.md +14 -2
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +16 -0
- package/packages/selector/lib/client.js +396 -117
- package/packages/selector/lib/index.js +829 -10
- package/packages/selector/lib/invariant.js +2 -1
- package/packages/selector/lib/pruner.d.ts +1 -1
- package/packages/selector/lib/pruner.js +77 -983
- package/packages/selector/lib/savings-integral.js +4515 -0
- package/packages/selector/lib/tail-trim.js +2 -90
- package/packages/selector/lib/tool-result.js +150 -0
- package/packages/selector/package.json +8 -4
- package/packages/selector/src/client/index.ts +15 -12
- package/packages/selector/src/client/locales/de.ts +20 -4
- package/packages/selector/src/client/locales/es.ts +20 -4
- package/packages/selector/src/client/locales/fr.ts +20 -4
- package/packages/selector/src/client/locales/it.ts +20 -4
- package/packages/selector/src/client/locales/ja.ts +20 -4
- package/packages/selector/src/client/locales/ko.ts +20 -4
- package/packages/selector/src/client/locales/ru.ts +20 -4
- package/packages/selector/src/client/locales.ts +40 -8
- package/packages/selector/src/client/monitor-fab.ts +80 -10
- package/packages/selector/src/client/savings-card.tsx +159 -40
- package/packages/selector/src/index.ts +236 -1
- package/packages/selector/src/pruner.ts +54 -8
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/monitor.ts +75 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/retrieve.ts +31 -12
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +3 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +122 -13
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +302 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +7 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +83 -1
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +53 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -1
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +327 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +15 -15
- package/pnpm-workspace.yaml +4 -0
- package/scripts/verify-release.mjs +5 -2
- package/vitest.config.ts +8 -0
- package/packages/selector/lib/config.js +0 -1777
- package/packages/selector/lib/host-generation.js +0 -62
|
@@ -0,0 +1,4515 @@
|
|
|
1
|
+
import { n as viewToolResult, s as sessionEvents } from "./tool-result.js";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
import { Tokenizer } from "@huggingface/tokenizers";
|
|
8
|
+
import zlib from "node:zlib";
|
|
9
|
+
import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
|
|
10
|
+
import { mkdir } from "node:fs/promises";
|
|
11
|
+
//#region src/runtime/savings.ts
|
|
12
|
+
/**
|
|
13
|
+
* 节省统计账本(诚实口径)。
|
|
14
|
+
*
|
|
15
|
+
* 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
|
|
16
|
+
* 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
|
|
17
|
+
* tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
|
|
18
|
+
* 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
|
|
19
|
+
* 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
|
|
20
|
+
* 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
|
|
21
|
+
* 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
|
|
22
|
+
* 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
|
|
23
|
+
* 汇总,永不合并成一个数。
|
|
24
|
+
*
|
|
25
|
+
* 存储:本账本是**存量仪表**层(进程内 per-session,环形缓冲 + hash 注册表,
|
|
26
|
+
* 重启归零——重进会话由投影播种重建)。统计口径共三层:
|
|
27
|
+
* 1. 存量仪表(本账本):当前 surface 生效的毛节省/抵消/净额,随内容进出涨落;
|
|
28
|
+
* 2. 持久 claims 流水(stats-sync → stats-db):land/retrieve/usage 事件级幂等
|
|
29
|
+
* 行落库,跨重启保留,作审计与面板累计数据源;
|
|
30
|
+
* 3. 累计积分(savings-integral,fresh 边界按 call 采样存量净额入库):回答
|
|
31
|
+
* "历史上省了多少",随 T15 积分器落地。
|
|
32
|
+
*
|
|
33
|
+
* 存量/流量分离(记账口径三件套):
|
|
34
|
+
* - offset 条目可带 sourceSeq,observeActive 按"召回文本存活面"收敛,离面即停罚;
|
|
35
|
+
* - 同 basis 召回经 foldRecall 折叠进源条目(贡献 a−(b+R),下限 −b,翻负后带
|
|
36
|
+
* negative-effect 标记供分项显示);跨 basis 禁折叠,退化为带 sourceSeq 的
|
|
37
|
+
* 收敛 offset,守住"口径分列永不合并"原则;
|
|
38
|
+
* - 环形缓冲溢出优先淘汰离面/无源条目,replacementSeq 仍在面上的 saving 绝不清。
|
|
39
|
+
*
|
|
40
|
+
* @module dsh-context-compression-improved/runtime/savings
|
|
41
|
+
*/
|
|
42
|
+
const MAX_ENTRIES_PER_SESSION = 800;
|
|
43
|
+
const MAX_REGISTRY = 2048;
|
|
44
|
+
var SavingsLedger = class {
|
|
45
|
+
entries = /* @__PURE__ */ new Map();
|
|
46
|
+
registry = /* @__PURE__ */ new Map();
|
|
47
|
+
seenFullText = /* @__PURE__ */ new Set();
|
|
48
|
+
/** 最近一次 observeActive 传入的存活 seq(驱逐保护判据;缺省 = 保守保护)。 */
|
|
49
|
+
lastLiveSeqs = /* @__PURE__ */ new Map();
|
|
50
|
+
usage = /* @__PURE__ */ new Map();
|
|
51
|
+
startedAt = Date.now();
|
|
52
|
+
/**
|
|
53
|
+
* 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
|
|
54
|
+
* dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
|
|
55
|
+
*/
|
|
56
|
+
recordUsage(sessionId, usage) {
|
|
57
|
+
let total = this.usage.get(sessionId);
|
|
58
|
+
if (total === void 0) {
|
|
59
|
+
total = {
|
|
60
|
+
requests: 0,
|
|
61
|
+
inputTokens: 0,
|
|
62
|
+
outputTokens: 0,
|
|
63
|
+
cacheReadTokens: 0,
|
|
64
|
+
cacheWriteTokens: 0
|
|
65
|
+
};
|
|
66
|
+
this.usage.set(sessionId, total);
|
|
67
|
+
}
|
|
68
|
+
total.requests += 1;
|
|
69
|
+
total.inputTokens += positiveOrZero(usage.inputTokens);
|
|
70
|
+
total.outputTokens += positiveOrZero(usage.outputTokens);
|
|
71
|
+
total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens);
|
|
72
|
+
total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens);
|
|
73
|
+
}
|
|
74
|
+
totalsFor(scope) {
|
|
75
|
+
const sum = {
|
|
76
|
+
requests: 0,
|
|
77
|
+
inputTokens: 0,
|
|
78
|
+
outputTokens: 0,
|
|
79
|
+
cacheReadTokens: 0,
|
|
80
|
+
cacheWriteTokens: 0
|
|
81
|
+
};
|
|
82
|
+
for (const sid of scope) {
|
|
83
|
+
const t = this.usage.get(sid);
|
|
84
|
+
if (t === void 0) continue;
|
|
85
|
+
sum.requests += t.requests;
|
|
86
|
+
sum.inputTokens += t.inputTokens;
|
|
87
|
+
sum.outputTokens += t.outputTokens;
|
|
88
|
+
sum.cacheReadTokens += t.cacheReadTokens;
|
|
89
|
+
sum.cacheWriteTokens += t.cacheWriteTokens;
|
|
90
|
+
}
|
|
91
|
+
return sum;
|
|
92
|
+
}
|
|
93
|
+
/** 单行会话汇总(session/disposed 日志用)。 */
|
|
94
|
+
sessionSummaryLine(sessionId) {
|
|
95
|
+
const snap = this.snapshot(sessionId);
|
|
96
|
+
const hit = snap.usage.cacheHitRate;
|
|
97
|
+
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)}%`}`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。
|
|
101
|
+
*
|
|
102
|
+
* 仪表口径:该条目在替换事件离开当前 surface 前一直计入"当前生效毛节省"
|
|
103
|
+
* (由 {@link observeActive} 每回合收敛),不再一次性永久累加。
|
|
104
|
+
*/
|
|
105
|
+
recordSaving(input) {
|
|
106
|
+
const removed = input.tokensBefore - input.tokensAfter;
|
|
107
|
+
if (!Number.isFinite(removed) || removed <= 0) return;
|
|
108
|
+
this.push(input.sessionId, {
|
|
109
|
+
kind: "saving",
|
|
110
|
+
component: input.component,
|
|
111
|
+
tokens: removed,
|
|
112
|
+
basis: input.basis,
|
|
113
|
+
at: Date.now(),
|
|
114
|
+
sourceSeq: input.sourceSeq,
|
|
115
|
+
foldFloor: -Math.max(0, input.tokensAfter),
|
|
116
|
+
...input.replacementSeq === void 0 ? {} : { replacementSeq: input.replacementSeq }
|
|
117
|
+
});
|
|
118
|
+
if (typeof input.originalText === "string" && input.originalText.length > 0) {
|
|
119
|
+
const hash = savingsHash(input.originalText);
|
|
120
|
+
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
|
|
121
|
+
const oldest = this.registry.keys().next().value;
|
|
122
|
+
if (oldest !== void 0) this.registry.delete(oldest);
|
|
123
|
+
}
|
|
124
|
+
this.registry.set(hash, {
|
|
125
|
+
sessionId: input.sessionId,
|
|
126
|
+
component: input.component,
|
|
127
|
+
claimedTokens: removed,
|
|
128
|
+
basis: input.basis,
|
|
129
|
+
sourceSeq: input.sourceSeq,
|
|
130
|
+
consumed: false
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
|
|
136
|
+
* 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
|
|
137
|
+
* @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
|
|
138
|
+
*/
|
|
139
|
+
noteFullText(input) {
|
|
140
|
+
if (typeof input.text !== "string" || input.text.length === 0) return;
|
|
141
|
+
const seenKey = `${input.sessionId}:${input.seq}`;
|
|
142
|
+
if (this.seenFullText.has(seenKey)) return;
|
|
143
|
+
this.seenFullText.add(seenKey);
|
|
144
|
+
if (this.seenFullText.size > MAX_REGISTRY * 4) {
|
|
145
|
+
this.seenFullText.clear();
|
|
146
|
+
this.seenFullText.add(seenKey);
|
|
147
|
+
}
|
|
148
|
+
const hit = this.registry.get(savingsHash(input.text));
|
|
149
|
+
if (hit === void 0 || hit.sessionId !== input.sessionId) return;
|
|
150
|
+
const { tokens, basis } = input.measure(input.text);
|
|
151
|
+
if (tokens <= 0) return;
|
|
152
|
+
this.push(input.sessionId, {
|
|
153
|
+
kind: "offset",
|
|
154
|
+
component: "full-read",
|
|
155
|
+
tokens,
|
|
156
|
+
basis,
|
|
157
|
+
at: Date.now(),
|
|
158
|
+
sourceSeq: input.seq,
|
|
159
|
+
note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
|
|
163
|
+
recordOffset(input) {
|
|
164
|
+
if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
|
|
165
|
+
this.push(input.sessionId, {
|
|
166
|
+
kind: "offset",
|
|
167
|
+
component: input.component,
|
|
168
|
+
tokens: input.tokens,
|
|
169
|
+
basis: input.basis,
|
|
170
|
+
at: Date.now(),
|
|
171
|
+
...input.sourceSeq === void 0 ? {} : { sourceSeq: input.sourceSeq },
|
|
172
|
+
...input.note === void 0 ? {} : { note: input.note }
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* 召回翻负折叠:把一次召回(实测 R)折进同 (sessionId, sourceSeq, basis) 的源
|
|
177
|
+
* saving 条目:贡献 a−(b+R),下限 −b(多次召回累计不再下探)。翻负后条目带
|
|
178
|
+
* negative-effect 标记,snapshot 分项里以负值呈现,净额与旧行为(毛节省 +(a−b)
|
|
179
|
+
* 叠加流水 −R)等值。
|
|
180
|
+
*
|
|
181
|
+
* 跨 basis 不折叠(口径分列永不合并):退化为带 sourceSeq 的收敛 offset,
|
|
182
|
+
* 下一次 observeActive 即离面停罚。未找到源条目(已离面/投影播种无配对键)同路。
|
|
183
|
+
*
|
|
184
|
+
* @returns 是否折进了源条目(false = 走了退化 offset 流水或无效入参)。
|
|
185
|
+
*/
|
|
186
|
+
foldRecall(sessionId, sourceSeq, recalledTokens, basis, fallback) {
|
|
187
|
+
if (!Number.isFinite(recalledTokens) || recalledTokens <= 0) return false;
|
|
188
|
+
const list = this.entries.get(sessionId);
|
|
189
|
+
if (list !== void 0) for (let i = list.length - 1; i >= 0; i--) {
|
|
190
|
+
const entry = list[i];
|
|
191
|
+
if (entry.kind !== "saving" || entry.sourceSeq !== sourceSeq || entry.basis !== basis) continue;
|
|
192
|
+
entry.tokens = Math.max(entry.tokens - recalledTokens, entry.foldFloor ?? 0);
|
|
193
|
+
if (entry.tokens < 0) entry.negativeEffect = true;
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
this.push(sessionId, {
|
|
197
|
+
kind: "offset",
|
|
198
|
+
component: fallback?.component ?? "retrieve",
|
|
199
|
+
tokens: recalledTokens,
|
|
200
|
+
basis,
|
|
201
|
+
at: Date.now(),
|
|
202
|
+
sourceSeq,
|
|
203
|
+
...fallback?.note === void 0 ? {} : { note: fallback.note }
|
|
204
|
+
});
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
sourceSeqOf(item) {
|
|
208
|
+
return item.sourceSeq;
|
|
209
|
+
}
|
|
210
|
+
push(sessionId, entry) {
|
|
211
|
+
let list = this.entries.get(sessionId);
|
|
212
|
+
if (list === void 0) {
|
|
213
|
+
list = [];
|
|
214
|
+
this.entries.set(sessionId, list);
|
|
215
|
+
}
|
|
216
|
+
list.push(entry);
|
|
217
|
+
if (list.length <= MAX_ENTRIES_PER_SESSION) return;
|
|
218
|
+
const live = this.lastLiveSeqs.get(sessionId);
|
|
219
|
+
while (list.length > MAX_ENTRIES_PER_SESSION) {
|
|
220
|
+
const idx = list.findIndex((candidate) => !isSurfaceProtected(candidate, live));
|
|
221
|
+
if (idx === -1) break;
|
|
222
|
+
list.splice(idx, 1);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* 仪表口径收敛:
|
|
227
|
+
* - 'saving' 条目只在其替换事件仍位于当前 surface 时计为"当前生效毛节省",
|
|
228
|
+
* 离开 surface 即从毛节省中扣除;无 replacementSeq 的保持原样(无法追踪者不收敛)。
|
|
229
|
+
* - 带 sourceSeq 的 'offset' 条目按"召回文本存活面"收敛:sourceSeq 离面即停罚
|
|
230
|
+
* (full-read = 重读事件自身);无 sourceSeq 的 offset 保持原样(永久流水)。
|
|
231
|
+
*/
|
|
232
|
+
observeActive(sessionId, liveSeqs) {
|
|
233
|
+
this.lastLiveSeqs.set(sessionId, liveSeqs);
|
|
234
|
+
const list = this.entries.get(sessionId);
|
|
235
|
+
if (list === void 0) return;
|
|
236
|
+
const kept = list.filter((entry) => {
|
|
237
|
+
if (entry.kind === "saving") return entry.replacementSeq === void 0 || liveSeqs.has(entry.replacementSeq);
|
|
238
|
+
return entry.sourceSeq === void 0 || liveSeqs.has(entry.sourceSeq);
|
|
239
|
+
});
|
|
240
|
+
if (kept.length !== list.length) this.entries.set(sessionId, kept);
|
|
241
|
+
}
|
|
242
|
+
/** 该会话是否已有账本条目(重进会话时用于避免投影与实时叠加)。 */
|
|
243
|
+
hasSession(sessionId) {
|
|
244
|
+
return this.entries.has(sessionId);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* 用会话日志投影播种一个会话的账本(重进/重启会话时调用一次)。写入
|
|
248
|
+
* savings/offsets 条目及其原文配对 registry,后续实时增量(observeActive /
|
|
249
|
+
* noteFullText)在同一条目集合上继续工作。调用方负责只播种一次。
|
|
250
|
+
*/
|
|
251
|
+
seedProjected(sessionId, projection) {
|
|
252
|
+
for (const entry of projection.savings) {
|
|
253
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue;
|
|
254
|
+
this.push(sessionId, {
|
|
255
|
+
kind: "saving",
|
|
256
|
+
component: entry.component,
|
|
257
|
+
tokens: entry.tokens,
|
|
258
|
+
basis: entry.basis,
|
|
259
|
+
at: entry.at,
|
|
260
|
+
replacementSeq: entry.replacementSeq
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
for (const entry of projection.offsets) {
|
|
264
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue;
|
|
265
|
+
this.push(sessionId, {
|
|
266
|
+
kind: "offset",
|
|
267
|
+
component: entry.component,
|
|
268
|
+
tokens: entry.tokens,
|
|
269
|
+
basis: entry.basis,
|
|
270
|
+
at: entry.at,
|
|
271
|
+
...entry.note === void 0 ? {} : { note: entry.note }
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
for (const item of projection.registry) {
|
|
275
|
+
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(item.hash)) {
|
|
276
|
+
const oldest = this.registry.keys().next().value;
|
|
277
|
+
if (oldest !== void 0) this.registry.delete(oldest);
|
|
278
|
+
}
|
|
279
|
+
this.registry.set(item.hash, {
|
|
280
|
+
sessionId,
|
|
281
|
+
component: "projection",
|
|
282
|
+
claimedTokens: item.claimedTokens,
|
|
283
|
+
basis: item.basis,
|
|
284
|
+
sourceSeq: item.sourceSeq,
|
|
285
|
+
consumed: false
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
|
|
290
|
+
snapshot(sessionId) {
|
|
291
|
+
const scope = sessionId === void 0 ? [...this.entries.keys()] : [sessionId];
|
|
292
|
+
const totals = {
|
|
293
|
+
grossExact: 0,
|
|
294
|
+
grossEstimated: 0,
|
|
295
|
+
offsetExact: 0,
|
|
296
|
+
offsetEstimated: 0
|
|
297
|
+
};
|
|
298
|
+
const perComponent = /* @__PURE__ */ new Map();
|
|
299
|
+
const recentOffsets = [];
|
|
300
|
+
for (const sid of scope) for (const entry of this.entries.get(sid) ?? []) {
|
|
301
|
+
const exact = entry.basis === "exact-tokenizer";
|
|
302
|
+
if (entry.kind === "saving" && entry.tokens >= 0) {
|
|
303
|
+
if (exact) totals.grossExact += entry.tokens;
|
|
304
|
+
else totals.grossEstimated += entry.tokens;
|
|
305
|
+
} else if (entry.kind === "saving") {
|
|
306
|
+
if (exact) totals.offsetExact += -entry.tokens;
|
|
307
|
+
else totals.offsetEstimated += -entry.tokens;
|
|
308
|
+
} else {
|
|
309
|
+
if (exact) totals.offsetExact += entry.tokens;
|
|
310
|
+
else totals.offsetEstimated += entry.tokens;
|
|
311
|
+
recentOffsets.push(entry);
|
|
312
|
+
}
|
|
313
|
+
const key = `${entry.kind}:${entry.component}:${entry.basis}`;
|
|
314
|
+
const agg = perComponent.get(key);
|
|
315
|
+
if (agg === void 0) perComponent.set(key, {
|
|
316
|
+
component: entry.component,
|
|
317
|
+
tokens: entry.tokens,
|
|
318
|
+
basis: entry.basis,
|
|
319
|
+
kind: entry.kind
|
|
320
|
+
});
|
|
321
|
+
else agg.tokens += entry.tokens;
|
|
322
|
+
}
|
|
323
|
+
recentOffsets.sort((a, b) => b.at - a.at);
|
|
324
|
+
const usageTotals = this.totalsFor(scope);
|
|
325
|
+
const perSession = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...this.entries.keys(), ...this.usage.keys()])].map((sid) => {
|
|
326
|
+
const s = this.snapshot(sid);
|
|
327
|
+
return {
|
|
328
|
+
sessionId: sid,
|
|
329
|
+
gross: s.gross,
|
|
330
|
+
offsets: s.offsets,
|
|
331
|
+
net: s.net,
|
|
332
|
+
requests: s.usage.requests,
|
|
333
|
+
cacheHitRate: s.usage.cacheHitRate
|
|
334
|
+
};
|
|
335
|
+
}).sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated).slice(0, 8) : [];
|
|
336
|
+
return {
|
|
337
|
+
startedAt: new Date(this.startedAt).toISOString(),
|
|
338
|
+
sessions: sessionId === void 0 ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
|
|
339
|
+
gross: {
|
|
340
|
+
exact: totals.grossExact,
|
|
341
|
+
estimated: totals.grossEstimated
|
|
342
|
+
},
|
|
343
|
+
offsets: {
|
|
344
|
+
exact: totals.offsetExact,
|
|
345
|
+
estimated: totals.offsetEstimated
|
|
346
|
+
},
|
|
347
|
+
net: {
|
|
348
|
+
exact: totals.grossExact - totals.offsetExact,
|
|
349
|
+
estimated: totals.grossEstimated - totals.offsetEstimated
|
|
350
|
+
},
|
|
351
|
+
perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
|
|
352
|
+
recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
|
|
353
|
+
component: e.component,
|
|
354
|
+
tokens: e.tokens,
|
|
355
|
+
basis: e.basis,
|
|
356
|
+
at: new Date(e.at).toISOString(),
|
|
357
|
+
...e.note === void 0 ? {} : { note: e.note }
|
|
358
|
+
})),
|
|
359
|
+
usage: {
|
|
360
|
+
...usageTotals,
|
|
361
|
+
cacheHitRate: cacheHitRateOf(usageTotals)
|
|
362
|
+
},
|
|
363
|
+
perSession
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
/** 测试与停机清理。 */
|
|
367
|
+
clear() {
|
|
368
|
+
this.entries.clear();
|
|
369
|
+
this.registry.clear();
|
|
370
|
+
this.seenFullText.clear();
|
|
371
|
+
this.lastLiveSeqs.clear();
|
|
372
|
+
this.usage.clear();
|
|
373
|
+
this.startedAt = Date.now();
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
function cacheHitRateOf(t) {
|
|
377
|
+
const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens;
|
|
378
|
+
return denom <= 0 ? null : Math.round(t.cacheReadTokens / denom * 1e3) / 1e3;
|
|
379
|
+
}
|
|
380
|
+
/** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
|
|
381
|
+
function savingsHash(text) {
|
|
382
|
+
return createHash("sha256").update(text.replace(/\r\n?/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/(^\s+)|(\s+$)/g, ""), "utf8").digest("hex");
|
|
383
|
+
}
|
|
384
|
+
function positiveOrZero(v) {
|
|
385
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* 驱逐保护判据:'saving' 条目的 replacementSeq 仍在当前面上(或面信息未知时
|
|
389
|
+
* 保守视为在面)则绝不清;其余(离面/无追踪键的 saving、一切 offset)可驱逐。
|
|
390
|
+
*/
|
|
391
|
+
function isSurfaceProtected(entry, live) {
|
|
392
|
+
return entry.kind === "saving" && entry.replacementSeq !== void 0 && (live === void 0 || live.has(entry.replacementSeq));
|
|
393
|
+
}
|
|
394
|
+
const singleton = new SavingsLedger();
|
|
395
|
+
/** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
|
|
396
|
+
function getSavingsLedger() {
|
|
397
|
+
return singleton;
|
|
398
|
+
}
|
|
399
|
+
//#endregion
|
|
400
|
+
//#region src/runtime/deepseek-official-pricing.ts
|
|
401
|
+
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
402
|
+
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
403
|
+
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
404
|
+
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
405
|
+
const PRICES = Object.freeze({
|
|
406
|
+
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
407
|
+
"0.007",
|
|
408
|
+
"0.22",
|
|
409
|
+
"0.66"
|
|
410
|
+
], [
|
|
411
|
+
"0.014",
|
|
412
|
+
"0.44",
|
|
413
|
+
"1.32"
|
|
414
|
+
], [
|
|
415
|
+
"0.05",
|
|
416
|
+
"1.5",
|
|
417
|
+
"4.5"
|
|
418
|
+
], [
|
|
419
|
+
"0.10",
|
|
420
|
+
"3.0",
|
|
421
|
+
"9.0"
|
|
422
|
+
]),
|
|
423
|
+
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
424
|
+
"0.022",
|
|
425
|
+
"0.66",
|
|
426
|
+
"1.98"
|
|
427
|
+
], [
|
|
428
|
+
"0.044",
|
|
429
|
+
"1.32",
|
|
430
|
+
"3.96"
|
|
431
|
+
], [
|
|
432
|
+
"0.15",
|
|
433
|
+
"4.5",
|
|
434
|
+
"13.5"
|
|
435
|
+
], [
|
|
436
|
+
"0.30",
|
|
437
|
+
"9.0",
|
|
438
|
+
"27.0"
|
|
439
|
+
]),
|
|
440
|
+
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
441
|
+
"0.007",
|
|
442
|
+
"0.22",
|
|
443
|
+
"0.66"
|
|
444
|
+
], [
|
|
445
|
+
"0.014",
|
|
446
|
+
"0.44",
|
|
447
|
+
"1.32"
|
|
448
|
+
], [
|
|
449
|
+
"0.05",
|
|
450
|
+
"1.5",
|
|
451
|
+
"4.5"
|
|
452
|
+
], [
|
|
453
|
+
"0.10",
|
|
454
|
+
"3.0",
|
|
455
|
+
"9.0"
|
|
456
|
+
])
|
|
457
|
+
});
|
|
458
|
+
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
459
|
+
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
460
|
+
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
461
|
+
/**
|
|
462
|
+
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
463
|
+
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
464
|
+
* @returns An immutable price record or an explicit unpriced reason.
|
|
465
|
+
*/
|
|
466
|
+
function resolveOfficialDeepSeekPrice(input) {
|
|
467
|
+
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
468
|
+
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
469
|
+
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
470
|
+
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
471
|
+
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
472
|
+
const band = priceBandAt(input.at);
|
|
473
|
+
if (band === void 0) return unpriced("invalid price timestamp");
|
|
474
|
+
const model = PRICES[input.modelId];
|
|
475
|
+
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
476
|
+
return {
|
|
477
|
+
kind: "priced",
|
|
478
|
+
record: Object.freeze({
|
|
479
|
+
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
480
|
+
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
481
|
+
provider: "deepseek-official",
|
|
482
|
+
baseUrlClass: "official-public",
|
|
483
|
+
apiRoute: input.apiRoute,
|
|
484
|
+
modelId: input.modelId,
|
|
485
|
+
modelVersion: model.version,
|
|
486
|
+
currency: input.currency,
|
|
487
|
+
unitTokens: 1e6,
|
|
488
|
+
band,
|
|
489
|
+
inputCacheHit,
|
|
490
|
+
inputCacheMiss,
|
|
491
|
+
output,
|
|
492
|
+
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
493
|
+
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
494
|
+
peakRule: PEAK_RULE
|
|
495
|
+
})
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Classify a timestamp under the published Beijing peak schedule.
|
|
500
|
+
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
501
|
+
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
502
|
+
*/
|
|
503
|
+
function priceBandAt(at) {
|
|
504
|
+
if (!Number.isFinite(at.getTime())) return void 0;
|
|
505
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
506
|
+
timeZone: "Asia/Shanghai",
|
|
507
|
+
weekday: "short",
|
|
508
|
+
hour: "2-digit",
|
|
509
|
+
minute: "2-digit",
|
|
510
|
+
second: "2-digit",
|
|
511
|
+
hourCycle: "h23"
|
|
512
|
+
}).formatToParts(at);
|
|
513
|
+
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
514
|
+
const weekday = values.weekday;
|
|
515
|
+
const hour = Number(values.hour);
|
|
516
|
+
const minute = Number(values.minute);
|
|
517
|
+
const second = Number(values.second);
|
|
518
|
+
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
519
|
+
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
520
|
+
const seconds = hour * 3600 + minute * 60 + second;
|
|
521
|
+
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Price one completed request, returning a range when it spans a published band boundary.
|
|
525
|
+
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
526
|
+
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
527
|
+
*/
|
|
528
|
+
function priceOfficialDeepSeekUsage(input) {
|
|
529
|
+
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
530
|
+
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
531
|
+
const start = resolveOfficialDeepSeekPrice({
|
|
532
|
+
...input,
|
|
533
|
+
at: input.startedAt
|
|
534
|
+
});
|
|
535
|
+
if (start.kind === "unpriced") return start;
|
|
536
|
+
const end = resolveOfficialDeepSeekPrice({
|
|
537
|
+
...input,
|
|
538
|
+
at: input.completedAt
|
|
539
|
+
});
|
|
540
|
+
if (end.kind === "unpriced") return end;
|
|
541
|
+
const startAmount = amountFor(start.record, input.usage);
|
|
542
|
+
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
543
|
+
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
544
|
+
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
545
|
+
kind: "exact",
|
|
546
|
+
currency: start.record.currency,
|
|
547
|
+
band: start.record.band,
|
|
548
|
+
...startAmount
|
|
549
|
+
};
|
|
550
|
+
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
551
|
+
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
552
|
+
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
553
|
+
const startFemto = BigInt(startAmount.femtoUnits);
|
|
554
|
+
const endFemto = BigInt(endAmount.femtoUnits);
|
|
555
|
+
return {
|
|
556
|
+
kind: "range",
|
|
557
|
+
currency: start.record.currency,
|
|
558
|
+
bands: [start.record.band, comparisonRecord.band],
|
|
559
|
+
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
560
|
+
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
564
|
+
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
565
|
+
const start = startedAt.getTime();
|
|
566
|
+
const end = completedAt.getTime();
|
|
567
|
+
if (end <= start) return false;
|
|
568
|
+
const dayMs = 864e5;
|
|
569
|
+
if (end - start >= 7 * dayMs) return true;
|
|
570
|
+
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
571
|
+
for (let day = firstDay; day <= end; day += dayMs) {
|
|
572
|
+
const weekday = new Date(day).getUTCDay();
|
|
573
|
+
if (weekday === 0 || weekday === 6) continue;
|
|
574
|
+
for (const hour of [
|
|
575
|
+
1,
|
|
576
|
+
4,
|
|
577
|
+
6,
|
|
578
|
+
10
|
|
579
|
+
]) {
|
|
580
|
+
const boundary = day + hour * 60 * 60 * 1e3;
|
|
581
|
+
if (boundary > start && boundary <= end) return true;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
function priceRecordInBand(record, band) {
|
|
587
|
+
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
588
|
+
return Object.freeze({
|
|
589
|
+
...record,
|
|
590
|
+
band,
|
|
591
|
+
inputCacheHit,
|
|
592
|
+
inputCacheMiss,
|
|
593
|
+
output
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
598
|
+
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
599
|
+
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
600
|
+
*/
|
|
601
|
+
function decimalRateNanoUnits(value) {
|
|
602
|
+
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
603
|
+
if (match === null) return void 0;
|
|
604
|
+
const whole = match[1] ?? "0";
|
|
605
|
+
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
606
|
+
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
607
|
+
}
|
|
608
|
+
function amountFor(record, usage) {
|
|
609
|
+
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
610
|
+
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
611
|
+
const output = decimalRateNanoUnits(record.output);
|
|
612
|
+
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
613
|
+
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
614
|
+
return {
|
|
615
|
+
femtoUnits: femtoUnits.toString(),
|
|
616
|
+
decimal: formatFemto(femtoUnits)
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
function formatFemto(value) {
|
|
620
|
+
const digits = value.toString().padStart(16, "0");
|
|
621
|
+
const whole = digits.slice(0, -15);
|
|
622
|
+
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
623
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
624
|
+
}
|
|
625
|
+
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
626
|
+
return Object.freeze({
|
|
627
|
+
version,
|
|
628
|
+
USD: Object.freeze({
|
|
629
|
+
"off-peak": usdOffPeak,
|
|
630
|
+
peak: usdPeak
|
|
631
|
+
}),
|
|
632
|
+
CNY: Object.freeze({
|
|
633
|
+
"off-peak": cnyOffPeak,
|
|
634
|
+
peak: cnyPeak
|
|
635
|
+
})
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
function isOfficialModel(value) {
|
|
639
|
+
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
640
|
+
}
|
|
641
|
+
function unpriced(reason) {
|
|
642
|
+
return {
|
|
643
|
+
kind: "unpriced",
|
|
644
|
+
reason
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
const advisorStates = /* @__PURE__ */ new WeakMap();
|
|
648
|
+
/**
|
|
649
|
+
* The per-session advisor state, created on first touch.
|
|
650
|
+
* @param session - the session to key the state on (by object identity).
|
|
651
|
+
*/
|
|
652
|
+
function getAdvisorState(session) {
|
|
653
|
+
let state = advisorStates.get(session);
|
|
654
|
+
if (state === void 0) {
|
|
655
|
+
state = {
|
|
656
|
+
todoVersion: void 0,
|
|
657
|
+
summary: void 0,
|
|
658
|
+
lastSummaryTurn: -1,
|
|
659
|
+
watermarkSeq: 0,
|
|
660
|
+
scores: /* @__PURE__ */ new Map(),
|
|
661
|
+
recertified: /* @__PURE__ */ new Map(),
|
|
662
|
+
failures: void 0,
|
|
663
|
+
inFlight: false,
|
|
664
|
+
lastDecay: void 0,
|
|
665
|
+
lastAdvice: void 0
|
|
666
|
+
};
|
|
667
|
+
advisorStates.set(session, state);
|
|
668
|
+
}
|
|
669
|
+
return state;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Insert or refresh one score with LRU semantics: a re-touched seq moves to
|
|
673
|
+
* the newest position, and the oldest entry is evicted once the map exceeds
|
|
674
|
+
* {@link ADVISOR_SCORES_LIMIT}.
|
|
675
|
+
*/
|
|
676
|
+
function recordScore(state, seq, entry) {
|
|
677
|
+
state.scores.delete(seq);
|
|
678
|
+
state.scores.set(seq, entry);
|
|
679
|
+
if (state.scores.size > 64) {
|
|
680
|
+
const oldest = state.scores.keys().next();
|
|
681
|
+
if (oldest.done !== true) state.scores.delete(oldest.value);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Mark one seq as LLM-recertified low relevance (a suggestion for later
|
|
686
|
+
* history-aggressiveness decisions, consumed by nothing in this round).
|
|
687
|
+
* Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
|
|
688
|
+
*/
|
|
689
|
+
function recordRecertified(state, seq, turn) {
|
|
690
|
+
state.recertified.delete(seq);
|
|
691
|
+
state.recertified.set(seq, turn);
|
|
692
|
+
if (state.recertified.size > 64) {
|
|
693
|
+
const oldest = state.recertified.keys().next();
|
|
694
|
+
if (oldest.done !== true) state.recertified.delete(oldest.value);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Drop every cached artifact that depends on the task semantics: a changed
|
|
699
|
+
* todo version invalidates the summary and makes all eligible candidates
|
|
700
|
+
* rescore-worthy (the watermark alone would otherwise hide them).
|
|
701
|
+
*/
|
|
702
|
+
function invalidateOnTaskChange(state, todoVersion) {
|
|
703
|
+
if (state.todoVersion === todoVersion) return false;
|
|
704
|
+
state.todoVersion = todoVersion;
|
|
705
|
+
state.summary = void 0;
|
|
706
|
+
state.lastSummaryTurn = -1;
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* `/ctx-summary off|on` overrides, keyed by session id (string). The command
|
|
711
|
+
* handler only sees `invocation.agent.session.id`, not the pruner's Session
|
|
712
|
+
* object, so these are id-keyed rather than WeakMap'd. Entries are two-char
|
|
713
|
+
* strings per session and cleared whenever the override is lifted.
|
|
714
|
+
*/
|
|
715
|
+
const summaryOverrides = /* @__PURE__ */ new Map();
|
|
716
|
+
/** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
|
|
717
|
+
function getSummaryOverride(sessionId) {
|
|
718
|
+
return summaryOverrides.get(sessionId);
|
|
719
|
+
}
|
|
720
|
+
/** Set or clear (`undefined`) the session's `/ctx-summary` override. */
|
|
721
|
+
function setSummaryOverride(sessionId, value) {
|
|
722
|
+
if (value === void 0) summaryOverrides.delete(sessionId);
|
|
723
|
+
else summaryOverrides.set(sessionId, value);
|
|
724
|
+
}
|
|
725
|
+
/** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
|
|
726
|
+
const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
|
|
727
|
+
/** Record the gate input the pass last evaluated for this session. */
|
|
728
|
+
function observeIntentEnabled(sessionId, enabled) {
|
|
729
|
+
lastObservedIntentEnabled.set(sessionId, enabled);
|
|
730
|
+
}
|
|
731
|
+
/** The settings-side enabled flag last observed for the session, if any. */
|
|
732
|
+
function getObservedIntentEnabled(sessionId) {
|
|
733
|
+
return lastObservedIntentEnabled.get(sessionId);
|
|
734
|
+
}
|
|
735
|
+
const lastIntentFolds = /* @__PURE__ */ new Map();
|
|
736
|
+
/** Record a landed intent fold for the session (newest wins). */
|
|
737
|
+
function recordIntentFold(sessionId, record) {
|
|
738
|
+
lastIntentFolds.set(sessionId, record);
|
|
739
|
+
}
|
|
740
|
+
/** The most recent landed intent fold for the session, if any. */
|
|
741
|
+
function getLastIntentFold(sessionId) {
|
|
742
|
+
return lastIntentFolds.get(sessionId);
|
|
743
|
+
}
|
|
744
|
+
//#endregion
|
|
745
|
+
//#region src/runtime/tokenpilot/intent-gate.ts
|
|
746
|
+
/**
|
|
747
|
+
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
748
|
+
*
|
|
749
|
+
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
750
|
+
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
751
|
+
* the next pressure round. The gate is deliberately conservative — every
|
|
752
|
+
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
753
|
+
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
754
|
+
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
755
|
+
* live in the fold landing path, not here.
|
|
756
|
+
*/
|
|
757
|
+
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
758
|
+
const INTENT_GATE_FLOOR_FRACTION = .45;
|
|
759
|
+
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
760
|
+
const INTENT_GATE_GROWTH_TOKENS = 5e4;
|
|
761
|
+
function isUsableNumber(value) {
|
|
762
|
+
return Number.isFinite(value) && value >= 0;
|
|
763
|
+
}
|
|
764
|
+
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
765
|
+
function evaluateIntentGate(input) {
|
|
766
|
+
const snapshot = (decision, reason) => ({
|
|
767
|
+
...input,
|
|
768
|
+
decision,
|
|
769
|
+
reason
|
|
770
|
+
});
|
|
771
|
+
if (!input.enabled) return snapshot(false, "disabled");
|
|
772
|
+
if (input.override === "off") return snapshot(false, "override-off");
|
|
773
|
+
if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
|
|
774
|
+
if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
|
|
775
|
+
if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
|
|
776
|
+
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
|
|
777
|
+
if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
|
|
778
|
+
return snapshot(true, "passed");
|
|
779
|
+
}
|
|
780
|
+
//#endregion
|
|
781
|
+
//#region src/runtime/monitor.ts
|
|
782
|
+
/**
|
|
783
|
+
* 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
|
|
784
|
+
* 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
|
|
785
|
+
* (默认 80%)——提前一档给出人工干预窗口。
|
|
786
|
+
*/
|
|
787
|
+
const MONITOR_SUGGEST_PCT = .7;
|
|
788
|
+
/**
|
|
789
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
790
|
+
* injectable so tests seed a private instance instead of the process
|
|
791
|
+
* singleton.
|
|
792
|
+
*/
|
|
793
|
+
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
794
|
+
const scopeKey = sessionId ?? "";
|
|
795
|
+
const override = getSummaryOverride(scopeKey);
|
|
796
|
+
const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
|
|
797
|
+
const contextBlock = observedContext === void 0 ? void 0 : {
|
|
798
|
+
liveTokens: observedContext.liveTokens,
|
|
799
|
+
contextWindow: observedContext.contextWindow,
|
|
800
|
+
pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
|
|
801
|
+
sessionId: observedContext.sessionId
|
|
802
|
+
};
|
|
803
|
+
const suggestion = contextBlock === void 0 || contextBlock.pct === null ? void 0 : {
|
|
804
|
+
suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
|
|
805
|
+
thresholdPct: MONITOR_SUGGEST_PCT,
|
|
806
|
+
occupancyPct: contextBlock.pct
|
|
807
|
+
};
|
|
808
|
+
return {
|
|
809
|
+
...ledger.snapshot(sessionId),
|
|
810
|
+
...contextBlock === void 0 ? {} : { context: contextBlock },
|
|
811
|
+
...suggestion === void 0 ? {} : { suggestion },
|
|
812
|
+
intent: {
|
|
813
|
+
override,
|
|
814
|
+
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
815
|
+
gate: {
|
|
816
|
+
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
817
|
+
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
818
|
+
},
|
|
819
|
+
lastFold: getLastIntentFold(scopeKey)
|
|
820
|
+
},
|
|
821
|
+
sessionScope: sessionId ?? null
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
|
|
825
|
+
const contextUsageBySession = /* @__PURE__ */ new Map();
|
|
826
|
+
const CONTEXT_USAGE_CAP = 64;
|
|
827
|
+
/**
|
|
828
|
+
* 组成按压缩路径去重合并:同路径跨口径(mixed = 精确+估算混合)一行,
|
|
829
|
+
* tokens 降序。重复行是口径拆分的产物,不是两条不同路径。
|
|
830
|
+
*/
|
|
831
|
+
function mergeCompositionByComponent(rows) {
|
|
832
|
+
const byComponent = /* @__PURE__ */ new Map();
|
|
833
|
+
for (const row of rows) {
|
|
834
|
+
const found = byComponent.get(row.component);
|
|
835
|
+
if (found === void 0) byComponent.set(row.component, { ...row });
|
|
836
|
+
else {
|
|
837
|
+
found.tokens += row.tokens;
|
|
838
|
+
found.events += row.events;
|
|
839
|
+
if (found.basis !== row.basis) found.basis = "mixed";
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
return [...byComponent.values()].sort((a, b) => b.tokens - a.tokens);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
|
|
846
|
+
* contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
|
|
847
|
+
*/
|
|
848
|
+
function observeContextUsage(sessionId, liveTokens, contextWindow) {
|
|
849
|
+
if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
|
|
850
|
+
if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
|
|
851
|
+
const oldest = contextUsageBySession.keys().next().value;
|
|
852
|
+
if (oldest !== void 0) contextUsageBySession.delete(oldest);
|
|
853
|
+
}
|
|
854
|
+
contextUsageBySession.set(sessionId, {
|
|
855
|
+
liveTokens,
|
|
856
|
+
contextWindow,
|
|
857
|
+
at: Date.now(),
|
|
858
|
+
seq: ++observeSeq
|
|
859
|
+
});
|
|
860
|
+
}
|
|
861
|
+
function getContextUsage(sessionId) {
|
|
862
|
+
const entry = contextUsageBySession.get(sessionId);
|
|
863
|
+
return entry === void 0 ? void 0 : {
|
|
864
|
+
liveTokens: entry.liveTokens,
|
|
865
|
+
contextWindow: entry.contextWindow,
|
|
866
|
+
sessionId
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
let observeSeq = 0;
|
|
870
|
+
function latestObservedContextUsage() {
|
|
871
|
+
let latest;
|
|
872
|
+
for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
|
|
873
|
+
sessionId,
|
|
874
|
+
liveTokens: entry.liveTokens,
|
|
875
|
+
contextWindow: entry.contextWindow,
|
|
876
|
+
seq: entry.seq
|
|
877
|
+
};
|
|
878
|
+
return latest;
|
|
879
|
+
}
|
|
880
|
+
function isSessionOverrideAction(value) {
|
|
881
|
+
return value === "on" || value === "off" || value === "clear";
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
885
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
886
|
+
* handed back so the route can echo the post-action truth.
|
|
887
|
+
*/
|
|
888
|
+
function applySessionOverride(sessionId, action) {
|
|
889
|
+
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
890
|
+
return { override: getSummaryOverride(sessionId) };
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
894
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
895
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
896
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
897
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
898
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
899
|
+
*/
|
|
900
|
+
function estimateSavingsPricing(readService, snapshot) {
|
|
901
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
902
|
+
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
903
|
+
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
904
|
+
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
905
|
+
if (provider !== "deepseek-official") return void 0;
|
|
906
|
+
const now = /* @__PURE__ */ new Date();
|
|
907
|
+
const startedAt = new Date(snapshot.startedAt);
|
|
908
|
+
const base = {
|
|
909
|
+
provider,
|
|
910
|
+
baseUrlClass: "official-public",
|
|
911
|
+
apiRoute: "chat-completions",
|
|
912
|
+
modelId,
|
|
913
|
+
currency: "USD",
|
|
914
|
+
startedAt,
|
|
915
|
+
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
916
|
+
};
|
|
917
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
918
|
+
...base,
|
|
919
|
+
usage: {
|
|
920
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
921
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
922
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
926
|
+
...base,
|
|
927
|
+
usage: {
|
|
928
|
+
cacheReadTokens: 0,
|
|
929
|
+
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
930
|
+
outputTokens: 0
|
|
931
|
+
}
|
|
932
|
+
}) : void 0;
|
|
933
|
+
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
934
|
+
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
935
|
+
return {
|
|
936
|
+
currency: "USD",
|
|
937
|
+
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
938
|
+
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* 「每次从头开始计算」(用户定标):三值与最后 Δ 全量重导自 DRS 投影替换对——
|
|
943
|
+
* 毛 = Σ(a−b) 仅压缩对(不含回吐);抵消 = Σb 仅召回对;净 = 毛 − 抵消(含回吐,
|
|
944
|
+
* 有召回时净必异于毛)。basis=ds-token 落 exact 臂;chars/4 落 estimated 臂
|
|
945
|
+
* (浮窗 est 标注如实)。同会话同对子,输出确定——单一来源,不再与 claims 残账分裂。
|
|
946
|
+
*/
|
|
947
|
+
function drsTotalsFragment(index) {
|
|
948
|
+
let gross = 0;
|
|
949
|
+
let recall = 0;
|
|
950
|
+
let saving;
|
|
951
|
+
let offset;
|
|
952
|
+
for (const pair of index.pairs) if (pair.kind === "compress") {
|
|
953
|
+
gross += pair.aTokens - pair.bTokens;
|
|
954
|
+
if (saving === void 0 || pair.seq > saving.seq) saving = {
|
|
955
|
+
tokens: pair.aTokens - pair.bTokens,
|
|
956
|
+
seq: pair.seq
|
|
957
|
+
};
|
|
958
|
+
} else {
|
|
959
|
+
recall += pair.bTokens;
|
|
960
|
+
if (offset === void 0 || pair.seq > offset.seq) offset = {
|
|
961
|
+
tokens: pair.bTokens,
|
|
962
|
+
seq: pair.seq
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
const exact = index.basis === "ds-token";
|
|
966
|
+
const arm = (value) => exact ? {
|
|
967
|
+
exact: value,
|
|
968
|
+
estimated: 0
|
|
969
|
+
} : {
|
|
970
|
+
exact: 0,
|
|
971
|
+
estimated: value
|
|
972
|
+
};
|
|
973
|
+
const lastDelta = saving === void 0 && offset === void 0 ? void 0 : {
|
|
974
|
+
...saving === void 0 ? {} : { saving },
|
|
975
|
+
...offset === void 0 ? {} : { offset }
|
|
976
|
+
};
|
|
977
|
+
return {
|
|
978
|
+
sessionTotals: {
|
|
979
|
+
gross: arm(gross),
|
|
980
|
+
offsets: arm(recall),
|
|
981
|
+
net: arm(gross - recall)
|
|
982
|
+
},
|
|
983
|
+
...lastDelta === void 0 ? {} : { lastDelta }
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
//#endregion
|
|
987
|
+
//#region src/deepseek-v4-tokenizer.ts
|
|
988
|
+
/** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
|
|
989
|
+
const TOKENIZER_ID = "deepseek-ai/DeepSeek-V4-Pro";
|
|
990
|
+
const TOKENIZER_REVISION = "0e1a0e5e52aea73055f50fef6f2423db370265b6";
|
|
991
|
+
const TOKENIZER_SHA256 = "8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf";
|
|
992
|
+
const CONFIG_SHA256 = "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547";
|
|
993
|
+
const VISION_TOKENIZER_ID = "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp";
|
|
994
|
+
const VISION_TOKENIZER_REVISION = "6821d6ad3681a4b137b066b76094fa82ebd0a380";
|
|
995
|
+
const VISION_TOKENIZER_SHA256 = "c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b";
|
|
996
|
+
const VISION_CONFIG_SHA256 = "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547";
|
|
997
|
+
/** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
|
|
998
|
+
const DEEPSEEK_V4_TOKENIZER_ARTIFACT = Object.freeze({
|
|
999
|
+
repository: TOKENIZER_ID,
|
|
1000
|
+
revision: TOKENIZER_REVISION,
|
|
1001
|
+
license: "MIT",
|
|
1002
|
+
tokenizerSha256: TOKENIZER_SHA256,
|
|
1003
|
+
tokenizerConfigSha256: CONFIG_SHA256,
|
|
1004
|
+
modelIds: Object.freeze(["deepseek-v4-flash", "deepseek-v4-pro"])
|
|
1005
|
+
});
|
|
1006
|
+
/**
|
|
1007
|
+
* Auditable origin and compatibility mapping for the bundled V4 Flash Vision
|
|
1008
|
+
* tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
|
|
1009
|
+
* the `<|deepseek_image|>` special token), so the vision model must never be
|
|
1010
|
+
* mapped onto the V4 Pro tokenizer as an alias.
|
|
1011
|
+
*/
|
|
1012
|
+
const DEEPSEEK_VISION_TOKENIZER_ARTIFACT = Object.freeze({
|
|
1013
|
+
repository: VISION_TOKENIZER_ID,
|
|
1014
|
+
revision: VISION_TOKENIZER_REVISION,
|
|
1015
|
+
license: "MIT",
|
|
1016
|
+
tokenizerSha256: VISION_TOKENIZER_SHA256,
|
|
1017
|
+
tokenizerConfigSha256: VISION_CONFIG_SHA256,
|
|
1018
|
+
modelIds: Object.freeze(["deepseek-v4-flash-vision-exp"])
|
|
1019
|
+
});
|
|
1020
|
+
/**
|
|
1021
|
+
* Every bundled artifact is registered with independent asset roots, integrity
|
|
1022
|
+
* manifests, and cache entries: one corrupted artifact must never disable the
|
|
1023
|
+
* tokenizer serving the other model family.
|
|
1024
|
+
*/
|
|
1025
|
+
const ARTIFACTS = Object.freeze([Object.freeze({
|
|
1026
|
+
origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
1027
|
+
assetRoot: new URL("../assets/deepseek-v4/", import.meta.url),
|
|
1028
|
+
integrity: Object.freeze({
|
|
1029
|
+
tokenizer: Object.freeze({
|
|
1030
|
+
bytes: 6367146,
|
|
1031
|
+
sha256: TOKENIZER_SHA256
|
|
1032
|
+
}),
|
|
1033
|
+
config: Object.freeze({
|
|
1034
|
+
bytes: 801,
|
|
1035
|
+
sha256: CONFIG_SHA256
|
|
1036
|
+
})
|
|
1037
|
+
})
|
|
1038
|
+
}), Object.freeze({
|
|
1039
|
+
origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
|
|
1040
|
+
assetRoot: new URL("../assets/deepseek-v4-vision-exp/", import.meta.url),
|
|
1041
|
+
integrity: Object.freeze({
|
|
1042
|
+
tokenizer: Object.freeze({
|
|
1043
|
+
bytes: 6367257,
|
|
1044
|
+
sha256: VISION_TOKENIZER_SHA256
|
|
1045
|
+
}),
|
|
1046
|
+
config: Object.freeze({
|
|
1047
|
+
bytes: 801,
|
|
1048
|
+
sha256: VISION_CONFIG_SHA256
|
|
1049
|
+
})
|
|
1050
|
+
})
|
|
1051
|
+
})]);
|
|
1052
|
+
const registryCache = /* @__PURE__ */ new Map();
|
|
1053
|
+
function artifactForModel(modelId) {
|
|
1054
|
+
return ARTIFACTS.find((artifact) => artifact.origin.modelIds.includes(modelId));
|
|
1055
|
+
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Resolve the shared offline tokenizer for one compatible API model.
|
|
1058
|
+
* Unknown models and a cached asset/runtime failure return `undefined`; callers
|
|
1059
|
+
* must report unavailable instead of manufacturing a character estimate.
|
|
1060
|
+
* @param modelId - exact DeepSeek API wire model id.
|
|
1061
|
+
* @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
|
|
1062
|
+
*/
|
|
1063
|
+
function deepSeekV4TokenizerForModel(modelId) {
|
|
1064
|
+
const artifact = artifactForModel(modelId);
|
|
1065
|
+
if (artifact === void 0) return void 0;
|
|
1066
|
+
const cached = registryCache.get(artifact.origin);
|
|
1067
|
+
if (cached !== void 0) return cached.tokenizer;
|
|
1068
|
+
let entry;
|
|
1069
|
+
try {
|
|
1070
|
+
entry = { tokenizer: createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin) };
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
entry = { failure: error instanceof Error ? error.message : String(error) };
|
|
1073
|
+
}
|
|
1074
|
+
registryCache.set(artifact.origin, entry);
|
|
1075
|
+
return entry.tokenizer;
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Build a tokenizer from one local asset directory after byte/hash validation.
|
|
1079
|
+
* This provider-private seam exists so tests can prove every failure branch
|
|
1080
|
+
* without mutating the committed artifact.
|
|
1081
|
+
* @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
|
|
1082
|
+
* @param integrity - expected byte length and SHA-256 for both files.
|
|
1083
|
+
* @param origin - auditable identity recorded on every returned count.
|
|
1084
|
+
* @returns a synchronous exact text counter.
|
|
1085
|
+
* @internal
|
|
1086
|
+
*/
|
|
1087
|
+
function createDeepSeekV4TokenizerFromAssets(assetRoot, integrity, origin = DEEPSEEK_V4_TOKENIZER_ARTIFACT) {
|
|
1088
|
+
const tokenizerJson = readVerifiedJson(assetRoot, "tokenizer.json", integrity.tokenizer);
|
|
1089
|
+
const tokenizerConfig = readVerifiedJson(assetRoot, "tokenizer_config.json", integrity.config);
|
|
1090
|
+
const runtime = new Tokenizer(tokenizerJson, tokenizerConfig);
|
|
1091
|
+
return Object.freeze({ countText(text) {
|
|
1092
|
+
const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length;
|
|
1093
|
+
return Object.freeze({
|
|
1094
|
+
kind: "exact-tokenizer",
|
|
1095
|
+
tokens,
|
|
1096
|
+
tokenizerId: origin.repository,
|
|
1097
|
+
tokenizerRevision: origin.revision
|
|
1098
|
+
});
|
|
1099
|
+
} });
|
|
1100
|
+
}
|
|
1101
|
+
function readVerifiedJson(assetRoot, name, descriptor) {
|
|
1102
|
+
const bytes = readFileSync(new URL(name, assetRoot));
|
|
1103
|
+
if (bytes.byteLength !== descriptor.bytes) throw new Error(`DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`);
|
|
1104
|
+
if (createHash("sha256").update(bytes).digest("hex") !== descriptor.sha256) throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`);
|
|
1105
|
+
const parsed = JSON.parse(bytes.toString("utf8"));
|
|
1106
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`);
|
|
1107
|
+
return parsed;
|
|
1108
|
+
}
|
|
1109
|
+
//#endregion
|
|
1110
|
+
//#region src/runtime/session-file-decode.ts
|
|
1111
|
+
/**
|
|
1112
|
+
* 会话日志文件的只读解码叶子模块(回填后端 B 的格式底座,T19)。
|
|
1113
|
+
*
|
|
1114
|
+
* **零内部依赖**:只 import `node:*` 内置模块,不引用本插件任何其他 runtime 模块,
|
|
1115
|
+
* 供 `stats-backfill.ts`(后端 B)与测试直接消费;断代风险被隔离在本文件内。
|
|
1116
|
+
*
|
|
1117
|
+
* 移植自 dsh-session-steward 的 `host/health/generation.ts` + `decode.ts`
|
|
1118
|
+
* (代次文件名契约 + zstd 多帧/撕裂尾帧/打包行/provenance 解码链),
|
|
1119
|
+
* 并按本仓 D7 静态门做纪律适配:
|
|
1120
|
+
* - 源码(含注释)不得出现「session+裸点+jsonl」的连续字面量,也不得以任何
|
|
1121
|
+
* 大小写/驼峰形态写出宿主的格式版本常量名(检查器扫 src/lib/dist 三类命中,
|
|
1122
|
+
* 本注释自身就是最后一个命中点,所以只能用描述式写法);
|
|
1123
|
+
* 历史代文件名一律拼接构造(与 SS 生产代码同技巧),正则内转义点不触发。
|
|
1124
|
+
* - **header 代次未知 → fail-soft**:本模块只解码不裁决,提供
|
|
1125
|
+
* `classifySessionHeader`;调用方(回填)据此跳过该会话 + 一次性 warn,
|
|
1126
|
+
* 绝不整体抛。
|
|
1127
|
+
*
|
|
1128
|
+
* 只读纪律:本模块绝不写会话文件(SS 红线先例)。
|
|
1129
|
+
*/
|
|
1130
|
+
/**
|
|
1131
|
+
* 规范日志名的语法(不含压缩后缀),与宿主 session-format 的 filename 检查器
|
|
1132
|
+
* 逐字一致:代次 0 不带版本号,后续代次必须是小写数字且无前导零;
|
|
1133
|
+
* `.v0`、`.v01`、`.V1`、`session.v1.backup` 变体都不识别为规范代次。
|
|
1134
|
+
*/
|
|
1135
|
+
const CANONICAL_LOG_BASENAME = /^session(?:\.v([1-9][0-9]*))?\.jsonl$/u;
|
|
1136
|
+
/**
|
|
1137
|
+
* 迁移暂存名的语法(宿主发布路径的暂存形状 `session.migration.<hex>.jsonl[.zstd].tmp`,
|
|
1138
|
+
* token 位数是宿主内部细节,这里只固定形状,宿主换 token 长度时不失明)。
|
|
1139
|
+
*/
|
|
1140
|
+
const MIGRATION_STAGING_NAME = /^session\.migration\.[0-9a-f]+\.jsonl(?:\.zstd)?\.tmp$/u;
|
|
1141
|
+
function compressionSuffix(compression) {
|
|
1142
|
+
return compression === "zstd" ? ".zstd" : "";
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* 把一个规范日志名解析回代次;与宿主同语义:非规范名(临时、大写、前导零、
|
|
1146
|
+
* `.v0`、别的压缩后缀)一律返回 undefined,**不猜**。
|
|
1147
|
+
* @param filename - 会话目录里的一个文件名。
|
|
1148
|
+
* @param compression - 该目录使用的物理编码(缺省 zstd)。
|
|
1149
|
+
* @returns 其格式代次,或名字不构成规范代次时的 undefined。
|
|
1150
|
+
*/
|
|
1151
|
+
function parseGenerationLogFilename(filename, compression = "zstd") {
|
|
1152
|
+
const suffix = compressionSuffix(compression);
|
|
1153
|
+
if (!filename.endsWith(suffix)) return void 0;
|
|
1154
|
+
const match = CANONICAL_LOG_BASENAME.exec(filename.slice(0, filename.length - suffix.length));
|
|
1155
|
+
if (match === null) return void 0;
|
|
1156
|
+
if (match[1] === void 0) return 0;
|
|
1157
|
+
const version = Number(match[1]);
|
|
1158
|
+
return Number.isSafeInteger(version) ? version : void 0;
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* 两种压缩编码都试一遍,判定该名字是不是某代的规范产物。
|
|
1162
|
+
* 发现路径不假设部署的压缩配置(配置在 profile 侧,插件读不到),按名字本身分类。
|
|
1163
|
+
* @param filename - 会话目录里的一个文件名。
|
|
1164
|
+
* @returns 代次与编码,或该名字不是规范代次时的 undefined。
|
|
1165
|
+
*/
|
|
1166
|
+
function classifyGenerationFilename(filename) {
|
|
1167
|
+
const zstd = parseGenerationLogFilename(filename, "zstd");
|
|
1168
|
+
if (zstd !== void 0) return {
|
|
1169
|
+
version: zstd,
|
|
1170
|
+
compression: "zstd"
|
|
1171
|
+
};
|
|
1172
|
+
const none = parseGenerationLogFilename(filename, "none");
|
|
1173
|
+
if (none !== void 0) return {
|
|
1174
|
+
version: none,
|
|
1175
|
+
compression: "none"
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* 该文件名是否是迁移暂存(当前代的发布源)。
|
|
1180
|
+
* @param filename - 会话目录里的一个文件名。
|
|
1181
|
+
* @returns 是否形如 `session.migration.<token>.jsonl[.zstd].tmp`。
|
|
1182
|
+
*/
|
|
1183
|
+
function isMigrationStagingFilename(filename) {
|
|
1184
|
+
return MIGRATION_STAGING_NAME.test(filename);
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* 读取一个会话目录的代次事实(只读,不碰任何文件内容)。
|
|
1188
|
+
* 目录在枚举与读取之间消失(宿主正在删会话)时如实返回「没有产物」,不抛。
|
|
1189
|
+
* @param dir - 会话目录的绝对路径。
|
|
1190
|
+
* @returns 规范产物(按代次升序)、当前代、历史代与暂存残留。
|
|
1191
|
+
*/
|
|
1192
|
+
function readSessionGenerations(dir) {
|
|
1193
|
+
const canonical = [];
|
|
1194
|
+
const staging = [];
|
|
1195
|
+
let entries;
|
|
1196
|
+
try {
|
|
1197
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
1198
|
+
} catch {
|
|
1199
|
+
return {
|
|
1200
|
+
canonical: [],
|
|
1201
|
+
staging: [],
|
|
1202
|
+
legacyOnly: false
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
for (const entry of entries) {
|
|
1206
|
+
if (!entry.isFile()) continue;
|
|
1207
|
+
const path = join(dir, entry.name);
|
|
1208
|
+
let bytes;
|
|
1209
|
+
let mtimeMs;
|
|
1210
|
+
try {
|
|
1211
|
+
const stat = statSync(path);
|
|
1212
|
+
bytes = stat.size;
|
|
1213
|
+
mtimeMs = stat.mtimeMs;
|
|
1214
|
+
} catch {
|
|
1215
|
+
continue;
|
|
1216
|
+
}
|
|
1217
|
+
const artifact = {
|
|
1218
|
+
name: entry.name,
|
|
1219
|
+
path,
|
|
1220
|
+
bytes,
|
|
1221
|
+
mtimeMs
|
|
1222
|
+
};
|
|
1223
|
+
const generation = classifyGenerationFilename(entry.name);
|
|
1224
|
+
if (generation !== void 0) {
|
|
1225
|
+
canonical.push({
|
|
1226
|
+
...artifact,
|
|
1227
|
+
version: generation.version,
|
|
1228
|
+
compression: generation.compression
|
|
1229
|
+
});
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
if (isMigrationStagingFilename(entry.name)) staging.push(artifact);
|
|
1233
|
+
}
|
|
1234
|
+
canonical.sort((left, right) => left.version - right.version || left.mtimeMs - right.mtimeMs);
|
|
1235
|
+
staging.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
1236
|
+
const current = canonical.at(-1);
|
|
1237
|
+
const legacy = canonical.find((artifact) => artifact.version === 0);
|
|
1238
|
+
return {
|
|
1239
|
+
canonical,
|
|
1240
|
+
staging,
|
|
1241
|
+
...current === void 0 ? {} : { current },
|
|
1242
|
+
...legacy === void 0 ? {} : { legacy },
|
|
1243
|
+
legacyOnly: canonical.length > 0 && current?.version === 0
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
/** zstd 帧魔数(0xFD2FB528 的小端读取值)。 */
|
|
1247
|
+
const ZSTD_MAGIC = 4247762216;
|
|
1248
|
+
/** 打包行类型(读路径必须解包)。 */
|
|
1249
|
+
const PACKED_ROWS = /* @__PURE__ */ new Set([
|
|
1250
|
+
"text-chunks",
|
|
1251
|
+
"reasoning-chunks",
|
|
1252
|
+
"tool-call-chunks"
|
|
1253
|
+
]);
|
|
1254
|
+
/** 扫描拼接的 zstd 多帧;返回完整帧范围与撕裂尾帧起点。 */
|
|
1255
|
+
function scanZstdFrames(buffer) {
|
|
1256
|
+
const frames = [];
|
|
1257
|
+
let offset = 0;
|
|
1258
|
+
while (offset < buffer.length) {
|
|
1259
|
+
const start = offset;
|
|
1260
|
+
if (buffer.length - offset < 4) return {
|
|
1261
|
+
frames,
|
|
1262
|
+
tornStart: start
|
|
1263
|
+
};
|
|
1264
|
+
if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) return {
|
|
1265
|
+
frames,
|
|
1266
|
+
tornStart: start
|
|
1267
|
+
};
|
|
1268
|
+
offset += 4;
|
|
1269
|
+
if (offset === buffer.length) return {
|
|
1270
|
+
frames,
|
|
1271
|
+
tornStart: start
|
|
1272
|
+
};
|
|
1273
|
+
const descriptor = buffer.readUInt8(offset);
|
|
1274
|
+
offset += 1;
|
|
1275
|
+
if ((descriptor & 24) !== 0) return {
|
|
1276
|
+
frames,
|
|
1277
|
+
tornStart: start
|
|
1278
|
+
};
|
|
1279
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
1280
|
+
const singleSegment = (descriptor & 32) !== 0;
|
|
1281
|
+
const checksum = (descriptor & 4) !== 0;
|
|
1282
|
+
const dictionaryFlag = descriptor & 3;
|
|
1283
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
1284
|
+
const contentSizeBytes = contentSizeFlag === 0 ? singleSegment ? 1 : 0 : 1 << contentSizeFlag;
|
|
1285
|
+
const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
1286
|
+
if (buffer.length - offset < remainingHeaderBytes) return {
|
|
1287
|
+
frames,
|
|
1288
|
+
tornStart: start
|
|
1289
|
+
};
|
|
1290
|
+
offset += remainingHeaderBytes;
|
|
1291
|
+
for (;;) {
|
|
1292
|
+
if (buffer.length - offset < 3) return {
|
|
1293
|
+
frames,
|
|
1294
|
+
tornStart: start
|
|
1295
|
+
};
|
|
1296
|
+
const blockHeader = buffer.readUIntLE(offset, 3);
|
|
1297
|
+
offset += 3;
|
|
1298
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
1299
|
+
const blockType = blockHeader >>> 1 & 3;
|
|
1300
|
+
const blockSize = blockHeader >>> 3;
|
|
1301
|
+
if (blockType === 3) return {
|
|
1302
|
+
frames,
|
|
1303
|
+
tornStart: start
|
|
1304
|
+
};
|
|
1305
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
1306
|
+
if (buffer.length - offset < payloadBytes) return {
|
|
1307
|
+
frames,
|
|
1308
|
+
tornStart: start
|
|
1309
|
+
};
|
|
1310
|
+
offset += payloadBytes;
|
|
1311
|
+
if (lastBlock) break;
|
|
1312
|
+
}
|
|
1313
|
+
if (checksum) {
|
|
1314
|
+
if (buffer.length - offset < 4) return {
|
|
1315
|
+
frames,
|
|
1316
|
+
tornStart: start
|
|
1317
|
+
};
|
|
1318
|
+
offset += 4;
|
|
1319
|
+
}
|
|
1320
|
+
frames.push({
|
|
1321
|
+
start,
|
|
1322
|
+
end: offset
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
return { frames };
|
|
1326
|
+
}
|
|
1327
|
+
/** 存储形态的 provenance(`[[start,end],…]` 区间编码或直接 seq 数组)展开为递增 seq 列表。 */
|
|
1328
|
+
function decodeSeqRangesStorage(value, currentSeq) {
|
|
1329
|
+
if (!Array.isArray(value)) throw new Error("sourceEventSeqs must be an array when present");
|
|
1330
|
+
const out = [];
|
|
1331
|
+
for (const entry of value) {
|
|
1332
|
+
if (typeof entry === "number") {
|
|
1333
|
+
out.push(entry);
|
|
1334
|
+
continue;
|
|
1335
|
+
}
|
|
1336
|
+
if (Array.isArray(entry) && entry.length === 2) {
|
|
1337
|
+
const [start, end] = entry;
|
|
1338
|
+
if (typeof start !== "number" || typeof end !== "number" || end < start) throw new Error("sourceEventSeqs range is malformed");
|
|
1339
|
+
for (let seq = start; seq <= end; seq += 1) out.push(seq);
|
|
1340
|
+
continue;
|
|
1341
|
+
}
|
|
1342
|
+
throw new Error("sourceEventSeqs entry is neither a seq nor a [start,end] range");
|
|
1343
|
+
}
|
|
1344
|
+
for (const seq of out) if (!Number.isSafeInteger(seq) || seq < 0 || seq >= currentSeq) throw new Error(`sourceEventSeqs must reference earlier events: ${seq} >= ${currentSeq}`);
|
|
1345
|
+
return out;
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* 按需软加载宿主的官方解码器;不可用(未安装/版本不符)时返回 undefined。
|
|
1349
|
+
* 插件不 value-import 官方包,这里只做运行时可选加载。
|
|
1350
|
+
*/
|
|
1351
|
+
async function loadOfficialDecoders() {
|
|
1352
|
+
try {
|
|
1353
|
+
const mod = await import(
|
|
1354
|
+
/* @vite-ignore */
|
|
1355
|
+
"@deepseek-ai/dsh-session"
|
|
1356
|
+
);
|
|
1357
|
+
if (typeof mod.decodeStorageRecord !== "function" || typeof mod.decodeSeqRanges !== "function") return void 0;
|
|
1358
|
+
return {
|
|
1359
|
+
decodeStorageRecord: mod.decodeStorageRecord,
|
|
1360
|
+
decodeSeqRanges: mod.decodeSeqRanges
|
|
1361
|
+
};
|
|
1362
|
+
} catch {
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
/** 本地等价实现:把一行存储记录解包为事件(打包行展开为 assistant/chunk)。 */
|
|
1367
|
+
function decodeRecordLocal(value) {
|
|
1368
|
+
if (typeof value !== "object" || value === null) return [value];
|
|
1369
|
+
const record = value;
|
|
1370
|
+
const type = record["type"];
|
|
1371
|
+
if (typeof type !== "string" || !PACKED_ROWS.has(type)) {
|
|
1372
|
+
const seq = record["seq"];
|
|
1373
|
+
if (typeof seq === "number" && (!Number.isSafeInteger(seq) || seq < 0)) throw new Error(`session event seq ${String(seq)} is not a non-negative safe integer`);
|
|
1374
|
+
return [record];
|
|
1375
|
+
}
|
|
1376
|
+
const data = record["data"];
|
|
1377
|
+
if (data === void 0) throw new Error(`malformed ${type} storage row: data must be an object`);
|
|
1378
|
+
const members = type === "tool-call-chunks" ? data["args"] : data["texts"];
|
|
1379
|
+
if (!Array.isArray(members) || members.length === 0 || members.some((entry) => typeof entry !== "string")) throw new Error(`malformed ${type} storage row: payload must be a non-empty string array`);
|
|
1380
|
+
const dt = data["dt"];
|
|
1381
|
+
if (!Array.isArray(dt) || dt.some((gap) => !Number.isSafeInteger(gap))) throw new Error(`malformed ${type} storage row: dt must be an array of safe integers`);
|
|
1382
|
+
if (dt.length !== members.length - 1) throw new Error(`malformed ${type} storage row: dt length ${dt.length} does not match ${members.length} members`);
|
|
1383
|
+
const seq0 = record["seq0"];
|
|
1384
|
+
const time0 = record["time0"];
|
|
1385
|
+
if (typeof seq0 !== "number" || typeof time0 !== "number") throw new Error(`malformed ${type} storage row: seq0/time0 must be numbers`);
|
|
1386
|
+
const turn = data["turn"];
|
|
1387
|
+
const step = data["step"];
|
|
1388
|
+
const index = data["index"];
|
|
1389
|
+
const out = [];
|
|
1390
|
+
let time = time0;
|
|
1391
|
+
for (let k = 0; k < members.length; k += 1) {
|
|
1392
|
+
if (k > 0) time += dt[k - 1];
|
|
1393
|
+
let chunk;
|
|
1394
|
+
if (type === "text-chunks") chunk = {
|
|
1395
|
+
type: "text-delta",
|
|
1396
|
+
index,
|
|
1397
|
+
text: members[k]
|
|
1398
|
+
};
|
|
1399
|
+
else if (type === "reasoning-chunks") chunk = {
|
|
1400
|
+
type: "reasoning-delta",
|
|
1401
|
+
index,
|
|
1402
|
+
text: members[k]
|
|
1403
|
+
};
|
|
1404
|
+
else chunk = {
|
|
1405
|
+
type: "tool-call-delta",
|
|
1406
|
+
index,
|
|
1407
|
+
id: typeof data["id"] === "string" ? data["id"] : "",
|
|
1408
|
+
...typeof data["name"] === "string" ? { name: data["name"] } : {},
|
|
1409
|
+
argumentsDelta: members[k]
|
|
1410
|
+
};
|
|
1411
|
+
out.push({
|
|
1412
|
+
type: "assistant/chunk",
|
|
1413
|
+
seq: seq0 + k,
|
|
1414
|
+
time,
|
|
1415
|
+
data: {
|
|
1416
|
+
turn,
|
|
1417
|
+
step,
|
|
1418
|
+
chunk
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
return out;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* 解码一个会话日志(zstd 帧扫描 + 撕裂尾帧抢救 + 解包 + seq 连续性)。
|
|
1426
|
+
* @param bytes - 文件内容(调用方读取,便于测试注入与 mtime/size 只读断言)。
|
|
1427
|
+
* @param decoders - 可选官方解码器(缺省用本地等价实现;差异记入 decoder 字段,禁止静默回退)。
|
|
1428
|
+
* @returns 事件、统计与问题清单。
|
|
1429
|
+
*/
|
|
1430
|
+
function decodeSessionLogBytes(bytes, decoders) {
|
|
1431
|
+
const { frames, tornStart } = scanZstdFrames(bytes);
|
|
1432
|
+
const parts = [];
|
|
1433
|
+
const frameIssues = [];
|
|
1434
|
+
for (const frame of frames) try {
|
|
1435
|
+
parts.push(zlib.zstdDecompressSync(bytes.subarray(frame.start, frame.end)));
|
|
1436
|
+
} catch (err) {
|
|
1437
|
+
frameIssues.push(`frame@${frame.start}: ${String(err instanceof Error ? err.message : err)}`);
|
|
1438
|
+
}
|
|
1439
|
+
let recoveredFromTorn = 0;
|
|
1440
|
+
if (tornStart !== void 0) try {
|
|
1441
|
+
const recovered = zlib.zstdDecompressSync(bytes.subarray(tornStart), { finishFlush: zlib.constants.ZSTD_e_flush });
|
|
1442
|
+
recoveredFromTorn = recovered.length;
|
|
1443
|
+
parts.push(recovered);
|
|
1444
|
+
} catch {}
|
|
1445
|
+
const lines = (() => {
|
|
1446
|
+
const payload = Buffer.concat(parts);
|
|
1447
|
+
if (payload.length === 0 && frames.length === 0 && bytes.length > 0) return bytes.toString("utf8");
|
|
1448
|
+
return payload.toString("utf8");
|
|
1449
|
+
})().split("\n").filter((line) => line.trim() !== "");
|
|
1450
|
+
const issues = frameIssues.map((why, index) => ({
|
|
1451
|
+
line: index + 1,
|
|
1452
|
+
why
|
|
1453
|
+
}));
|
|
1454
|
+
const decodeRecord = decoders?.decodeStorageRecord ?? decodeRecordLocal;
|
|
1455
|
+
const events = [];
|
|
1456
|
+
for (let index = 1; index < lines.length; index += 1) {
|
|
1457
|
+
const line = lines[index];
|
|
1458
|
+
let decoded;
|
|
1459
|
+
try {
|
|
1460
|
+
const parsed = JSON.parse(line);
|
|
1461
|
+
decoded = decodeRecord(parsed["sourceEventSeqs"] === void 0 ? parsed : {
|
|
1462
|
+
...parsed,
|
|
1463
|
+
sourceEventSeqs: decoders?.decodeSeqRanges !== void 0 && typeof parsed["seq"] === "number" ? decoders.decodeSeqRanges(parsed["sourceEventSeqs"], parsed["seq"]) : decodeSeqRangesStorage(parsed["sourceEventSeqs"], Number(parsed["seq"] ?? 0))
|
|
1464
|
+
});
|
|
1465
|
+
} catch (err) {
|
|
1466
|
+
issues.push({
|
|
1467
|
+
line: index + 1,
|
|
1468
|
+
why: `decode failed: ${String(err instanceof Error ? err.message : err)}`
|
|
1469
|
+
});
|
|
1470
|
+
break;
|
|
1471
|
+
}
|
|
1472
|
+
const rowStart = events.length;
|
|
1473
|
+
let gapped = false;
|
|
1474
|
+
for (const event of decoded) {
|
|
1475
|
+
if (event.seq !== events.length) {
|
|
1476
|
+
issues.push({
|
|
1477
|
+
line: index + 1,
|
|
1478
|
+
why: `seq gap (expected ${events.length}, got ${event.seq})`
|
|
1479
|
+
});
|
|
1480
|
+
events.length = rowStart;
|
|
1481
|
+
gapped = true;
|
|
1482
|
+
break;
|
|
1483
|
+
}
|
|
1484
|
+
events.push(event);
|
|
1485
|
+
}
|
|
1486
|
+
if (gapped) break;
|
|
1487
|
+
}
|
|
1488
|
+
const openStep = findOpenStep(events);
|
|
1489
|
+
let header;
|
|
1490
|
+
const headerLine = lines[0];
|
|
1491
|
+
if (headerLine !== void 0) try {
|
|
1492
|
+
const parsed = JSON.parse(headerLine);
|
|
1493
|
+
if (typeof parsed === "object" && parsed !== null) header = parsed;
|
|
1494
|
+
} catch {}
|
|
1495
|
+
return {
|
|
1496
|
+
events,
|
|
1497
|
+
frames: frames.length,
|
|
1498
|
+
...tornStart === void 0 ? {} : { tornStart },
|
|
1499
|
+
recoveredFromTorn,
|
|
1500
|
+
issues,
|
|
1501
|
+
decoder: decoders === void 0 ? "local" : "official",
|
|
1502
|
+
...openStep === void 0 ? {} : { openStep },
|
|
1503
|
+
...header === void 0 ? {} : { header }
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
/** 尾部未收尾的 open step(有 step/start 无对应 step/end)。 */
|
|
1507
|
+
function findOpenStep(events) {
|
|
1508
|
+
let open;
|
|
1509
|
+
for (const event of events) {
|
|
1510
|
+
const data = event.data;
|
|
1511
|
+
if (event.type === "step/start" && typeof data?.turn === "number" && typeof data?.step === "number") {
|
|
1512
|
+
open = {
|
|
1513
|
+
turn: data.turn,
|
|
1514
|
+
step: data.step
|
|
1515
|
+
};
|
|
1516
|
+
continue;
|
|
1517
|
+
}
|
|
1518
|
+
if (event.type === "step/end") open = void 0;
|
|
1519
|
+
}
|
|
1520
|
+
return open;
|
|
1521
|
+
}
|
|
1522
|
+
/** 本插件已实证认得的格式代次集合(v3/v4 线;其余一律按未知处理)。 */
|
|
1523
|
+
const KNOWN_SESSION_FORMAT_GENERATIONS = /* @__PURE__ */ new Set([3, 4]);
|
|
1524
|
+
/**
|
|
1525
|
+
* 从解码结果的 header 判定格式代次是否可回填。
|
|
1526
|
+
*
|
|
1527
|
+
* 本模块只分类不告警——「跳过该会话 + 恰一条 warn」的裁决属于调用方
|
|
1528
|
+
* (stats-backfill)的责任面,保证叶子模块无副作用。
|
|
1529
|
+
* @param header - decodeSessionLog 结果里的 header(首行不是 JSON 时 undefined)。
|
|
1530
|
+
* @param known - 已知代次集合(缺省 {@link KNOWN_SESSION_FORMAT_GENERATIONS})。
|
|
1531
|
+
*/
|
|
1532
|
+
function classifySessionHeader(header, known = KNOWN_SESSION_FORMAT_GENERATIONS) {
|
|
1533
|
+
if (header === void 0) return { state: "missing-header" };
|
|
1534
|
+
if (header["type"] !== "session") return { state: "not-session" };
|
|
1535
|
+
const version = header["version"];
|
|
1536
|
+
if (typeof version === "number" && known.has(version)) return {
|
|
1537
|
+
state: "known",
|
|
1538
|
+
version
|
|
1539
|
+
};
|
|
1540
|
+
return {
|
|
1541
|
+
state: "unknown-version",
|
|
1542
|
+
version
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
//#endregion
|
|
1546
|
+
//#region src/runtime/token-count.ts
|
|
1547
|
+
/** Build an explicit unavailable result without inventing an estimate. */
|
|
1548
|
+
function unavailableTokenCount(reason) {
|
|
1549
|
+
if (reason.length === 0) throw new TypeError("unavailable token count requires a reason");
|
|
1550
|
+
return Object.freeze({
|
|
1551
|
+
kind: "unavailable",
|
|
1552
|
+
reason
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
/** Sum independent canonical fields only when every count has one identity. */
|
|
1556
|
+
function countExactCanonicalTextFields(fields, counter, subject) {
|
|
1557
|
+
if (subject.length === 0) throw new TypeError("canonical text field count requires a subject");
|
|
1558
|
+
const values = fields.length === 0 ? [""] : fields;
|
|
1559
|
+
let identity;
|
|
1560
|
+
let tokens = 0;
|
|
1561
|
+
for (const value of values) {
|
|
1562
|
+
const count = counter(value);
|
|
1563
|
+
if (count.kind !== "exact-tokenizer") return unavailableTokenCount(`${subject}: ${count.kind === "unavailable" ? count.reason : "canonical content requires an exact tokenizer count"}`);
|
|
1564
|
+
if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
|
|
1565
|
+
identity ??= count;
|
|
1566
|
+
tokens += count.tokens;
|
|
1567
|
+
if (!Number.isSafeInteger(tokens) || tokens < 0) return unavailableTokenCount(`${subject}: token sum is outside the safe integer range`);
|
|
1568
|
+
}
|
|
1569
|
+
if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
|
|
1570
|
+
return Object.freeze({
|
|
1571
|
+
...identity,
|
|
1572
|
+
tokens
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
//#endregion
|
|
1576
|
+
//#region src/runtime/deepseek-v4-vision-tokens.ts
|
|
1577
|
+
/**
|
|
1578
|
+
* Exact DeepSeek V4 Flash Vision image-token arithmetic.
|
|
1579
|
+
*
|
|
1580
|
+
* Every rule in this module is a line-by-line port of the official
|
|
1581
|
+
* `inference/image_processor.py` published by
|
|
1582
|
+
* `deepseek-ai/DeepSeek-V4-Flash-Vision-Exp` at the pinned immutable revision
|
|
1583
|
+
* recorded below. The golden fixtures in `tests/fixtures/vision-golden.json`
|
|
1584
|
+
* are generated by executing that official implementation, so any change here
|
|
1585
|
+
* must keep the Node counts byte-identical to the reference output.
|
|
1586
|
+
*
|
|
1587
|
+
* These arithmetic results back intrinsic-grid estimates, never exact counts
|
|
1588
|
+
* of the final request. The official expansion
|
|
1589
|
+
* depends on the absolute serialized prompt position (system prompt,
|
|
1590
|
+
* chat-template framing, adapter image handles) and on the adapter's final
|
|
1591
|
+
* request-image projection — including per-route pixel-budget or image-detail
|
|
1592
|
+
* overrides and byte-cap reprojection — none of which is published through a
|
|
1593
|
+
* public API, and a projected image can count FEWER tokens than its intrinsic
|
|
1594
|
+
* grid suggests. The measurement layer therefore labels image-bearing nodes
|
|
1595
|
+
* as estimates and keeps them outside exact rewrite proofs; the 640,000-pixel
|
|
1596
|
+
* budget below documents the adapter default rather than establishing
|
|
1597
|
+
* exactness.
|
|
1598
|
+
*/
|
|
1599
|
+
/** Official projection parameters pinned from the model repository config. */
|
|
1600
|
+
const DEEPSEEK_VISION_PROJECTION = Object.freeze({
|
|
1601
|
+
sourceRepository: "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp",
|
|
1602
|
+
sourceRevision: "6821d6ad3681a4b137b066b76094fa82ebd0a380",
|
|
1603
|
+
/** `vision_patch_size` from the official config. */
|
|
1604
|
+
visionPatchSize: 14,
|
|
1605
|
+
/** `vision_downsample_ratio` from the official config. */
|
|
1606
|
+
visionDownsampleRatio: 3,
|
|
1607
|
+
/** `vision_max_n_token`: post-preprocessing cap per image, not a fixed value. */
|
|
1608
|
+
visionMaxNTokens: 384,
|
|
1609
|
+
/** `vision_min_pixels`: tiny images are upscaled before patching. */
|
|
1610
|
+
visionMinPixels: 147456,
|
|
1611
|
+
/** `vision_max_wh_ratio`: wider-than-ratio images are width-clamped. */
|
|
1612
|
+
visionMaxWhRatio: 8,
|
|
1613
|
+
/**
|
|
1614
|
+
* Default per-image pixel budget used by the DeepSeek adapter's normal
|
|
1615
|
+
* attachment projection (`DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET` in
|
|
1616
|
+
* `@deepseek-ai/dsh-llm-deepseek`). Route overrides remain unobservable to
|
|
1617
|
+
* this estimator.
|
|
1618
|
+
*/
|
|
1619
|
+
requestImagePixelBudget: 64e4
|
|
1620
|
+
});
|
|
1621
|
+
/** Stable identity for the deliberately approximate image-token counter. */
|
|
1622
|
+
const DEEPSEEK_VISION_IMAGE_ESTIMATOR = Object.freeze({
|
|
1623
|
+
id: `${DEEPSEEK_VISION_PROJECTION.sourceRepository}/image-token-estimate`,
|
|
1624
|
+
revision: `${DEEPSEEK_VISION_PROJECTION.sourceRevision}:v1`
|
|
1625
|
+
});
|
|
1626
|
+
/** Official `COMPRESS_PAD_TO` alignment constant from image_processor.py. */
|
|
1627
|
+
const COMPRESS_PAD_TO = 4;
|
|
1628
|
+
/**
|
|
1629
|
+
* Estimate one image without claiming an exact serialized position or final
|
|
1630
|
+
* adapter projection. Valid intrinsic dimensions use the midpoint of the four
|
|
1631
|
+
* possible alignment residues. Invalid or unsafe metadata uses the documented
|
|
1632
|
+
* fixed fallback. In both cases the official per-image budget is retained as
|
|
1633
|
+
* a conservative upper bound.
|
|
1634
|
+
*/
|
|
1635
|
+
function estimateDeepSeekVisionImageTokens(width, height) {
|
|
1636
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0 || !Number.isSafeInteger(width * height)) return Object.freeze({
|
|
1637
|
+
tokens: 256,
|
|
1638
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
1639
|
+
source: "default"
|
|
1640
|
+
});
|
|
1641
|
+
try {
|
|
1642
|
+
const grid = deepSeekVisionImageGrid(width, height);
|
|
1643
|
+
const counts = [
|
|
1644
|
+
0,
|
|
1645
|
+
1,
|
|
1646
|
+
2,
|
|
1647
|
+
3
|
|
1648
|
+
].map((position) => deepSeekVisionImageBlockTokens(grid.nLlmH, grid.nLlmW, position));
|
|
1649
|
+
const paddingMinimumTokens = Math.min(...counts);
|
|
1650
|
+
const paddingMaximumTokens = Math.max(...counts);
|
|
1651
|
+
return Object.freeze({
|
|
1652
|
+
tokens: Math.round((paddingMinimumTokens + paddingMaximumTokens) / 2),
|
|
1653
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
1654
|
+
source: "intrinsic-grid",
|
|
1655
|
+
paddingMinimumTokens,
|
|
1656
|
+
paddingMaximumTokens
|
|
1657
|
+
});
|
|
1658
|
+
} catch {
|
|
1659
|
+
return Object.freeze({
|
|
1660
|
+
tokens: 256,
|
|
1661
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
1662
|
+
source: "default"
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* Resolve the aligner grid for one image's intrinsic dimensions.
|
|
1668
|
+
*
|
|
1669
|
+
* Port of the arithmetic path of the official `load_image`: aspect-ratio
|
|
1670
|
+
* clamp, minimum-pixel upscale, patch-grid ceiling, and the `safe_resize`
|
|
1671
|
+
* budget loop.
|
|
1672
|
+
*/
|
|
1673
|
+
function deepSeekVisionImageGrid(width, height) {
|
|
1674
|
+
const { visionPatchSize: patch, visionMaxWhRatio, visionMinPixels } = DEEPSEEK_VISION_PROJECTION;
|
|
1675
|
+
let effectiveWidth = width;
|
|
1676
|
+
let effectiveHeight = height;
|
|
1677
|
+
if (visionMaxWhRatio !== void 0 && effectiveWidth > effectiveHeight * visionMaxWhRatio) effectiveWidth = effectiveHeight * visionMaxWhRatio;
|
|
1678
|
+
if (effectiveWidth * effectiveHeight > 0 && effectiveWidth * effectiveHeight < visionMinPixels) {
|
|
1679
|
+
const ratio = (visionMinPixels / (effectiveWidth * effectiveHeight)) ** .5;
|
|
1680
|
+
effectiveWidth = Math.trunc(effectiveWidth * ratio);
|
|
1681
|
+
effectiveHeight = Math.trunc(effectiveHeight * ratio);
|
|
1682
|
+
}
|
|
1683
|
+
const bestWidth = Math.ceil(effectiveWidth / patch) * patch;
|
|
1684
|
+
const bestHeight = Math.ceil(effectiveHeight / patch) * patch;
|
|
1685
|
+
const resolved = safeResize(effectiveHeight, effectiveWidth, bestHeight, bestWidth);
|
|
1686
|
+
return Object.freeze({ ...resolved });
|
|
1687
|
+
}
|
|
1688
|
+
/**
|
|
1689
|
+
* Token count of one expanded image block, port of `build_image_block` length.
|
|
1690
|
+
* @internal exported for direct golden-fixture comparison.
|
|
1691
|
+
*/
|
|
1692
|
+
function deepSeekVisionImageBlockTokens(nLlmH, nLlmW, startTokenPos) {
|
|
1693
|
+
const compressPad = 3 - startTokenPos % COMPRESS_PAD_TO;
|
|
1694
|
+
const rows = nLlmH + nLlmH % 2;
|
|
1695
|
+
const rowLen = nLlmW + 1;
|
|
1696
|
+
const padLast = Math.floor(rows / 2) * rowLen % 2 * 2;
|
|
1697
|
+
return compressPad + 1 + rows * rowLen + padLast + 1;
|
|
1698
|
+
}
|
|
1699
|
+
/** Port of the official `grid_tokens` N-layout occupancy check. */
|
|
1700
|
+
function gridTokens(bestHeight, bestWidth) {
|
|
1701
|
+
const { visionPatchSize: patch, visionDownsampleRatio: downsample } = DEEPSEEK_VISION_PROJECTION;
|
|
1702
|
+
const nLlmH = Math.ceil(Math.floor(bestHeight / patch) / downsample);
|
|
1703
|
+
const nLlmW = Math.ceil(Math.floor(bestWidth / patch) / downsample);
|
|
1704
|
+
let numTokens = nLlmH * (nLlmW + 1) + 2;
|
|
1705
|
+
if (nLlmH % 2 === 1) numTokens += nLlmW + 1;
|
|
1706
|
+
numTokens += Math.floor((nLlmH + 1) / 2) * (nLlmW + 1) % 2 * 2;
|
|
1707
|
+
return {
|
|
1708
|
+
nLlmH,
|
|
1709
|
+
nLlmW,
|
|
1710
|
+
numTokens
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
/** Port of the official `solve_resize_ratio` budget solver. */
|
|
1714
|
+
function solveResizeRatio(height, width, maxNTokens) {
|
|
1715
|
+
const { visionPatchSize: patch, visionDownsampleRatio: downsample } = DEEPSEEK_VISION_PROJECTION;
|
|
1716
|
+
const ratio = height / width;
|
|
1717
|
+
const maxWFloat = Math.sqrt((maxNTokens - 2) / ratio + .25) - .5;
|
|
1718
|
+
const maxHFloat = maxWFloat * ratio;
|
|
1719
|
+
let bestWidth;
|
|
1720
|
+
let bestHeight;
|
|
1721
|
+
if (maxWFloat < 1) {
|
|
1722
|
+
const maxW = 1;
|
|
1723
|
+
let maxH = Math.floor((maxNTokens - 2) / 2);
|
|
1724
|
+
if (maxH % 2 === 1) maxH -= 1;
|
|
1725
|
+
bestWidth = maxW * patch * downsample;
|
|
1726
|
+
bestHeight = maxH * patch * downsample;
|
|
1727
|
+
} else if (maxHFloat < 2) {
|
|
1728
|
+
const maxH = 2;
|
|
1729
|
+
const maxW = Math.floor((maxNTokens - 2) / maxH) - 1;
|
|
1730
|
+
if (maxW <= 1) throw new Error("DeepSeek vision resize solver produced an invalid width");
|
|
1731
|
+
bestWidth = maxW * patch * downsample;
|
|
1732
|
+
bestHeight = maxH * patch * downsample;
|
|
1733
|
+
} else {
|
|
1734
|
+
const maxW = Math.floor(maxWFloat);
|
|
1735
|
+
let maxH = Math.floor(maxHFloat);
|
|
1736
|
+
if (maxH % 2 === 1) maxH -= 1;
|
|
1737
|
+
const beta = Math.min(maxW * patch * downsample / width, maxH * patch * downsample / height);
|
|
1738
|
+
bestWidth = Math.floor(width * beta / patch) * patch;
|
|
1739
|
+
bestHeight = Math.floor(height * beta / patch) * patch;
|
|
1740
|
+
}
|
|
1741
|
+
const grid = gridTokens(bestHeight, bestWidth);
|
|
1742
|
+
return {
|
|
1743
|
+
nLlmH: grid.nLlmH,
|
|
1744
|
+
nLlmW: grid.nLlmW,
|
|
1745
|
+
bestHeight,
|
|
1746
|
+
bestWidth
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
/** Port of the official `safe_resize` loop with the compress-pad budget. */
|
|
1750
|
+
function safeResize(height, width, initialBestHeight, initialBestWidth) {
|
|
1751
|
+
const { visionMaxNTokens } = DEEPSEEK_VISION_PROJECTION;
|
|
1752
|
+
let budget = visionMaxNTokens - 3;
|
|
1753
|
+
let grid = gridTokens(initialBestHeight, initialBestWidth);
|
|
1754
|
+
let bestHeight = initialBestHeight;
|
|
1755
|
+
let bestWidth = initialBestWidth;
|
|
1756
|
+
while (grid.numTokens > budget) {
|
|
1757
|
+
const solved = solveResizeRatio(height, width, budget);
|
|
1758
|
+
grid = gridTokens(solved.bestHeight, solved.bestWidth);
|
|
1759
|
+
bestHeight = solved.bestHeight;
|
|
1760
|
+
bestWidth = solved.bestWidth;
|
|
1761
|
+
budget -= 1;
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
nLlmH: grid.nLlmH,
|
|
1765
|
+
nLlmW: grid.nLlmW,
|
|
1766
|
+
bestHeight,
|
|
1767
|
+
bestWidth
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
//#endregion
|
|
1771
|
+
//#region src/runtime/types.ts
|
|
1772
|
+
/** User-facing mixed strategy profile. */
|
|
1773
|
+
const COMPRESSION_PROFILES = [
|
|
1774
|
+
"off",
|
|
1775
|
+
"native",
|
|
1776
|
+
"balanced",
|
|
1777
|
+
"cache-strict",
|
|
1778
|
+
"savings",
|
|
1779
|
+
"adaptive",
|
|
1780
|
+
"tokenpilot-inspired",
|
|
1781
|
+
"custom"
|
|
1782
|
+
];
|
|
1783
|
+
//#endregion
|
|
1784
|
+
//#region src/runtime/value.ts
|
|
1785
|
+
/** Version-neutral immutable-value and closed-union helpers for the plugin runtime. */
|
|
1786
|
+
/**
|
|
1787
|
+
* Freeze an object graph in place without relying on a Harness utility export.
|
|
1788
|
+
* Live AbortSignals remain mutable so request cancellation continues to work.
|
|
1789
|
+
* @param value - Value to freeze recursively.
|
|
1790
|
+
* @returns The same deeply frozen value.
|
|
1791
|
+
*/
|
|
1792
|
+
function deepFreeze(value) {
|
|
1793
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
1794
|
+
const pending = [{
|
|
1795
|
+
kind: "visit",
|
|
1796
|
+
node: value
|
|
1797
|
+
}];
|
|
1798
|
+
while (pending.length > 0) {
|
|
1799
|
+
const task = pending.pop();
|
|
1800
|
+
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
1801
|
+
if (task === void 0) continue;
|
|
1802
|
+
if (task.kind === "property") {
|
|
1803
|
+
pending.push({
|
|
1804
|
+
kind: "visit",
|
|
1805
|
+
node: task.source[task.key]
|
|
1806
|
+
});
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
const node = task.node;
|
|
1810
|
+
if (node === null || typeof node !== "object" || node instanceof AbortSignal || seen.has(node)) continue;
|
|
1811
|
+
seen.add(node);
|
|
1812
|
+
Object.freeze(node);
|
|
1813
|
+
const keys = Object.keys(node);
|
|
1814
|
+
for (let index = keys.length - 1; index >= 0; index--) {
|
|
1815
|
+
const key = keys[index];
|
|
1816
|
+
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
1817
|
+
if (key === void 0) continue;
|
|
1818
|
+
pending.push({
|
|
1819
|
+
kind: "property",
|
|
1820
|
+
source: node,
|
|
1821
|
+
key
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
return value;
|
|
1826
|
+
}
|
|
1827
|
+
/**
|
|
1828
|
+
* Throw for an impossible member of a closed discriminated union.
|
|
1829
|
+
* @param value - Value that escaped its closed union type.
|
|
1830
|
+
* @param context - Optional switch-site label.
|
|
1831
|
+
* @returns Never returns.
|
|
1832
|
+
*/
|
|
1833
|
+
function assertNever(value, context) {
|
|
1834
|
+
const rendered = JSON.stringify(value) ?? String(value);
|
|
1835
|
+
throw new Error(`unreachable variant${context === void 0 ? "" : ` in ${context}`}: ${rendered}`);
|
|
1836
|
+
}
|
|
1837
|
+
//#endregion
|
|
1838
|
+
//#region src/runtime/custom-policy.ts
|
|
1839
|
+
/** Strict versioned Custom policy parsing and effective-token resolution. */
|
|
1840
|
+
const budgetSchema = z.object({
|
|
1841
|
+
enabled: z.boolean().required(),
|
|
1842
|
+
trigger: z.number().required(),
|
|
1843
|
+
target: z.number().required()
|
|
1844
|
+
}).required();
|
|
1845
|
+
const legacyHistorySchema = z.object({
|
|
1846
|
+
enabled: z.boolean().required(),
|
|
1847
|
+
trigger: z.number().required(),
|
|
1848
|
+
keepRecentTurns: z.number().step(1).min(0).required(),
|
|
1849
|
+
keepRecent: z.number().required(),
|
|
1850
|
+
minReclaim: z.number().required()
|
|
1851
|
+
}).required();
|
|
1852
|
+
const historySchema = z.object({
|
|
1853
|
+
enabled: z.boolean().required(),
|
|
1854
|
+
trigger: z.number().required(),
|
|
1855
|
+
keepRecentToolCalls: z.number().step(1).min(0).required(),
|
|
1856
|
+
keepRecentTokens: z.number().required(),
|
|
1857
|
+
minReclaim: z.number().required()
|
|
1858
|
+
}).required();
|
|
1859
|
+
const tailTrimSchema = z.object({
|
|
1860
|
+
enabled: z.boolean().required(),
|
|
1861
|
+
trigger: z.number().required()
|
|
1862
|
+
}).required();
|
|
1863
|
+
const customCompressionPolicyV1InputSchema = z.object({
|
|
1864
|
+
version: z.const(1).required(),
|
|
1865
|
+
unit: z.union(["tokens", "context-percent"]).required(),
|
|
1866
|
+
fresh: budgetSchema,
|
|
1867
|
+
aggregate: budgetSchema,
|
|
1868
|
+
history: legacyHistorySchema,
|
|
1869
|
+
prefixPolicy: z.union(["preserve", "pressure-break"]).required()
|
|
1870
|
+
}).required();
|
|
1871
|
+
const customCompressionPolicyV2InputSchema = z.object({
|
|
1872
|
+
version: z.const(2).required(),
|
|
1873
|
+
unit: z.union(["tokens", "context-percent"]).required(),
|
|
1874
|
+
fresh: budgetSchema,
|
|
1875
|
+
aggregate: budgetSchema,
|
|
1876
|
+
history: legacyHistorySchema,
|
|
1877
|
+
prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
|
|
1878
|
+
tailTrim: tailTrimSchema
|
|
1879
|
+
}).required();
|
|
1880
|
+
const customCompressionPolicyV3InputSchema = z.object({
|
|
1881
|
+
version: z.const(3).required(),
|
|
1882
|
+
unit: z.union(["tokens", "context-percent"]).required(),
|
|
1883
|
+
fresh: budgetSchema,
|
|
1884
|
+
aggregate: budgetSchema,
|
|
1885
|
+
history: historySchema,
|
|
1886
|
+
prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
|
|
1887
|
+
tailTrim: tailTrimSchema
|
|
1888
|
+
}).required();
|
|
1889
|
+
/** Canonical Custom document accepted by Host settings and the runtime resolver. */
|
|
1890
|
+
const CustomCompressionPolicySchema = z.transform(z.any().required(), (value) => {
|
|
1891
|
+
assertExactPolicyShape(value);
|
|
1892
|
+
const canonical = canonicalizeCustomPolicy(value.version === 1 ? customCompressionPolicyV1InputSchema(value) : value.version === 2 ? customCompressionPolicyV2InputSchema(value) : customCompressionPolicyV3InputSchema(value));
|
|
1893
|
+
assertCanonicalRelations(canonical);
|
|
1894
|
+
return deepFreeze(structuredClone(canonical));
|
|
1895
|
+
});
|
|
1896
|
+
/** Balanced-equivalent Custom policy stored as one token-canonical document. */
|
|
1897
|
+
const DEFAULT_CUSTOM_COMPRESSION_POLICY = deepFreeze({
|
|
1898
|
+
version: 3,
|
|
1899
|
+
unit: "tokens",
|
|
1900
|
+
fresh: {
|
|
1901
|
+
enabled: true,
|
|
1902
|
+
trigger: 8192,
|
|
1903
|
+
target: 3072
|
|
1904
|
+
},
|
|
1905
|
+
aggregate: {
|
|
1906
|
+
enabled: true,
|
|
1907
|
+
trigger: 32768,
|
|
1908
|
+
target: 12288
|
|
1909
|
+
},
|
|
1910
|
+
history: {
|
|
1911
|
+
enabled: true,
|
|
1912
|
+
trigger: 5e5,
|
|
1913
|
+
keepRecentToolCalls: 10,
|
|
1914
|
+
keepRecentTokens: 64e3,
|
|
1915
|
+
minReclaim: 96e3
|
|
1916
|
+
},
|
|
1917
|
+
prefixPolicy: "pressure-break",
|
|
1918
|
+
tailTrim: {
|
|
1919
|
+
enabled: false,
|
|
1920
|
+
trigger: 7e5
|
|
1921
|
+
}
|
|
1922
|
+
});
|
|
1923
|
+
/**
|
|
1924
|
+
* Resolve one validated Custom document to the same token policy used by public presets.
|
|
1925
|
+
* @param value - untrusted or typed Custom settings value.
|
|
1926
|
+
* @param options - routed model capacity for context-percent documents.
|
|
1927
|
+
* @returns a detached deeply immutable effective token policy.
|
|
1928
|
+
*/
|
|
1929
|
+
function resolveCustomPolicy(value, options = {}) {
|
|
1930
|
+
const policy = canonicalizeCustomPolicy(CustomCompressionPolicySchema(value));
|
|
1931
|
+
const effective = (name, amount) => {
|
|
1932
|
+
if (policy.unit === "tokens") return amount;
|
|
1933
|
+
const contextWindow = options.contextWindowTokens;
|
|
1934
|
+
if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) throw new Error("Custom context-percent policy requires a resolved positive model context window");
|
|
1935
|
+
const tokens = Math.floor(contextWindow * amount / 100);
|
|
1936
|
+
if (!Number.isSafeInteger(tokens) || amount > 0 && tokens <= 0) throw new Error(`Custom ${name} has no valid effective token value for this model`);
|
|
1937
|
+
return tokens;
|
|
1938
|
+
};
|
|
1939
|
+
const resolved = {
|
|
1940
|
+
profile: "custom",
|
|
1941
|
+
nativeToolResultEnabled: false,
|
|
1942
|
+
freshEnabled: policy.fresh.enabled,
|
|
1943
|
+
aggregateEnabled: policy.aggregate.enabled,
|
|
1944
|
+
historyMode: !policy.history.enabled ? "disabled" : policy.prefixPolicy === "preserve" ? "capacity-pressure" : "routine",
|
|
1945
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
1946
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
1947
|
+
freshTriggerTokens: effective("Fresh trigger", policy.fresh.trigger),
|
|
1948
|
+
freshTargetTokens: effective("Fresh target", policy.fresh.target),
|
|
1949
|
+
aggregateTriggerTokens: effective("Aggregate trigger", policy.aggregate.trigger),
|
|
1950
|
+
aggregateTargetTokens: effective("Aggregate target", policy.aggregate.target),
|
|
1951
|
+
historyTriggerTokens: effective("History trigger", policy.history.trigger),
|
|
1952
|
+
historyKeepRecentToolCalls: policy.history.keepRecentToolCalls,
|
|
1953
|
+
historyKeepRecentTokens: effective("History recent token tail", policy.history.keepRecentTokens),
|
|
1954
|
+
historyMinReclaimTokens: effective("History min-reclaim", policy.history.minReclaim),
|
|
1955
|
+
tailTrim: {
|
|
1956
|
+
enabled: policy.tailTrim.enabled,
|
|
1957
|
+
triggerTokens: effective("TailTrim trigger", policy.tailTrim.trigger)
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
assertEffectiveRelations(resolved);
|
|
1961
|
+
return deepFreeze(resolved);
|
|
1962
|
+
}
|
|
1963
|
+
function canonicalizeCustomPolicy(policy) {
|
|
1964
|
+
if (policy.version === 3) return policy;
|
|
1965
|
+
return {
|
|
1966
|
+
version: 3,
|
|
1967
|
+
unit: policy.unit,
|
|
1968
|
+
fresh: policy.fresh,
|
|
1969
|
+
aggregate: policy.aggregate,
|
|
1970
|
+
history: {
|
|
1971
|
+
enabled: policy.history.enabled,
|
|
1972
|
+
trigger: policy.history.trigger,
|
|
1973
|
+
keepRecentToolCalls: 10,
|
|
1974
|
+
keepRecentTokens: policy.history.keepRecent,
|
|
1975
|
+
minReclaim: policy.history.minReclaim
|
|
1976
|
+
},
|
|
1977
|
+
prefixPolicy: policy.prefixPolicy,
|
|
1978
|
+
tailTrim: policy.version === 1 ? {
|
|
1979
|
+
enabled: false,
|
|
1980
|
+
trigger: 7e5
|
|
1981
|
+
} : policy.tailTrim
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
function measuredValues(policy) {
|
|
1985
|
+
return [
|
|
1986
|
+
policy.fresh.trigger,
|
|
1987
|
+
policy.fresh.target,
|
|
1988
|
+
policy.aggregate.trigger,
|
|
1989
|
+
policy.aggregate.target,
|
|
1990
|
+
policy.history.trigger,
|
|
1991
|
+
policy.history.keepRecentTokens,
|
|
1992
|
+
policy.history.minReclaim,
|
|
1993
|
+
policy.tailTrim.trigger
|
|
1994
|
+
];
|
|
1995
|
+
}
|
|
1996
|
+
function validMeasuredValues(policy) {
|
|
1997
|
+
const values = measuredValues(policy);
|
|
1998
|
+
if (![
|
|
1999
|
+
policy.fresh.trigger,
|
|
2000
|
+
policy.fresh.target,
|
|
2001
|
+
policy.aggregate.trigger,
|
|
2002
|
+
policy.aggregate.target,
|
|
2003
|
+
policy.history.trigger,
|
|
2004
|
+
policy.history.minReclaim,
|
|
2005
|
+
policy.tailTrim.trigger
|
|
2006
|
+
].every((value) => value > 0) || policy.history.keepRecentTokens < 0 || !Number.isSafeInteger(policy.history.keepRecentToolCalls) || policy.history.keepRecentToolCalls < 0) return false;
|
|
2007
|
+
return policy.unit === "tokens" ? values.every(Number.isSafeInteger) : values.every((value) => Number.isFinite(value) && value <= 100);
|
|
2008
|
+
}
|
|
2009
|
+
function assertCanonicalRelations(policy) {
|
|
2010
|
+
if (!validMeasuredValues(policy)) throw new TypeError("Custom measured values must use the selected canonical unit");
|
|
2011
|
+
if (policy.fresh.target >= policy.fresh.trigger) throw new TypeError("Custom Fresh target must be below trigger");
|
|
2012
|
+
if (policy.aggregate.target >= policy.aggregate.trigger) throw new TypeError("Custom Aggregate target must be below trigger");
|
|
2013
|
+
if (policy.history.minReclaim > policy.history.trigger) throw new TypeError("Custom History min-reclaim must not exceed its trigger");
|
|
2014
|
+
}
|
|
2015
|
+
function assertExactPolicyShape(value) {
|
|
2016
|
+
if (!isPlainRecord$1(value)) throw new TypeError("Custom must be a plain object");
|
|
2017
|
+
if (value.version !== 1 && value.version !== 2 && value.version !== 3) throw new TypeError("Custom version must be 1, 2, or 3");
|
|
2018
|
+
assertExactKeys(value, value.version === 1 ? [
|
|
2019
|
+
"version",
|
|
2020
|
+
"unit",
|
|
2021
|
+
"fresh",
|
|
2022
|
+
"aggregate",
|
|
2023
|
+
"history",
|
|
2024
|
+
"prefixPolicy"
|
|
2025
|
+
] : [
|
|
2026
|
+
"version",
|
|
2027
|
+
"unit",
|
|
2028
|
+
"fresh",
|
|
2029
|
+
"aggregate",
|
|
2030
|
+
"history",
|
|
2031
|
+
"prefixPolicy",
|
|
2032
|
+
"tailTrim"
|
|
2033
|
+
], "Custom");
|
|
2034
|
+
assertExactKeys(value.fresh, [
|
|
2035
|
+
"enabled",
|
|
2036
|
+
"trigger",
|
|
2037
|
+
"target"
|
|
2038
|
+
], "Custom Fresh");
|
|
2039
|
+
assertExactKeys(value.aggregate, [
|
|
2040
|
+
"enabled",
|
|
2041
|
+
"trigger",
|
|
2042
|
+
"target"
|
|
2043
|
+
], "Custom Aggregate");
|
|
2044
|
+
assertExactKeys(value.history, value.version === 3 ? [
|
|
2045
|
+
"enabled",
|
|
2046
|
+
"trigger",
|
|
2047
|
+
"keepRecentToolCalls",
|
|
2048
|
+
"keepRecentTokens",
|
|
2049
|
+
"minReclaim"
|
|
2050
|
+
] : [
|
|
2051
|
+
"enabled",
|
|
2052
|
+
"trigger",
|
|
2053
|
+
"keepRecentTurns",
|
|
2054
|
+
"keepRecent",
|
|
2055
|
+
"minReclaim"
|
|
2056
|
+
], "Custom History");
|
|
2057
|
+
if (value.version !== 1) assertExactKeys(value.tailTrim, ["enabled", "trigger"], "Custom TailTrim");
|
|
2058
|
+
}
|
|
2059
|
+
function assertExactKeys(value, allowed, label) {
|
|
2060
|
+
if (!isPlainRecord$1(value)) throw new TypeError(`${label} must be a plain object`);
|
|
2061
|
+
const allowedKeys = new Set(allowed);
|
|
2062
|
+
const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
|
|
2063
|
+
if (unknown !== void 0) throw new TypeError(`${label}: unknown key "${unknown}"`);
|
|
2064
|
+
}
|
|
2065
|
+
function isPlainRecord$1(value) {
|
|
2066
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2067
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2068
|
+
return prototype === Object.prototype || prototype === null;
|
|
2069
|
+
}
|
|
2070
|
+
function assertEffectiveRelations(policy) {
|
|
2071
|
+
if (policy.freshTargetTokens >= policy.freshTriggerTokens) throw new Error("Custom effective Fresh target must be below trigger");
|
|
2072
|
+
if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens) throw new Error("Custom effective Aggregate target must be below trigger");
|
|
2073
|
+
if (policy.historyMinReclaimTokens > policy.historyTriggerTokens) throw new Error("Custom effective History min-reclaim must not exceed its trigger");
|
|
2074
|
+
}
|
|
2075
|
+
//#endregion
|
|
2076
|
+
//#region src/runtime/config.ts
|
|
2077
|
+
/** Configuration resolution for the mixed deterministic context-compression selector. */
|
|
2078
|
+
/** Settings namespace shared by the Host service and browser selector. */
|
|
2079
|
+
const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
|
|
2080
|
+
/** Fixed native fallback marker. */
|
|
2081
|
+
const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
|
|
2082
|
+
/**
|
|
2083
|
+
* The one Auto Compact threshold contract shared by the settings UI, the
|
|
2084
|
+
* persisted settings schema, and the runtime resolver. Every integer in the
|
|
2085
|
+
* range is valid and entered directly in the UI.
|
|
2086
|
+
*/
|
|
2087
|
+
const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
|
|
2088
|
+
min: 50,
|
|
2089
|
+
max: 90,
|
|
2090
|
+
step: 1,
|
|
2091
|
+
default: 80
|
|
2092
|
+
});
|
|
2093
|
+
/** Narrow one untrusted value to a valid Auto Compact threshold percent. */
|
|
2094
|
+
function isValidAutoCompactThresholdPercent(value) {
|
|
2095
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max;
|
|
2096
|
+
}
|
|
2097
|
+
const AUTO_COMPACT_DEFAULT = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default });
|
|
2098
|
+
/** Accept JSON-object records while rejecting class instances and exotic prototypes. */
|
|
2099
|
+
function isPlainRecord(value) {
|
|
2100
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2101
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2102
|
+
return prototype === Object.prototype || prototype === null;
|
|
2103
|
+
}
|
|
2104
|
+
/** Reject exotic prototypes anywhere in the JSON-like settings tree. */
|
|
2105
|
+
function assertPlainDataTree(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
2106
|
+
if (value === null || typeof value !== "object") return;
|
|
2107
|
+
if (seen.has(value)) return;
|
|
2108
|
+
seen.add(value);
|
|
2109
|
+
if (Array.isArray(value)) {
|
|
2110
|
+
for (const entry of value) assertPlainDataTree(entry, seen);
|
|
2111
|
+
return;
|
|
2112
|
+
}
|
|
2113
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must contain only plain objects");
|
|
2114
|
+
for (const entry of Object.values(value)) assertPlainDataTree(entry, seen);
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* Strictly parse the persisted autoCompact section. Schemastery object
|
|
2118
|
+
* defaults silently absorb null, empty, and extra-key sections, so this stays
|
|
2119
|
+
* hand-validated beside the top-level unknown-key check.
|
|
2120
|
+
*/
|
|
2121
|
+
function parseAutoCompactSettings(value) {
|
|
2122
|
+
if (value === void 0) return AUTO_COMPACT_DEFAULT;
|
|
2123
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression autoCompact must be a plain object");
|
|
2124
|
+
const keys = Object.keys(value);
|
|
2125
|
+
if (keys.length !== 1 || keys[0] !== "thresholdPercent") throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join("\", \"")}"`);
|
|
2126
|
+
const thresholdPercent = value.thresholdPercent;
|
|
2127
|
+
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)}`);
|
|
2128
|
+
return { thresholdPercent };
|
|
2129
|
+
}
|
|
2130
|
+
/**
|
|
2131
|
+
* Strictly parse the persisted codeSkeleton section. The gate is orthogonal
|
|
2132
|
+
* to every profile: absent inherits the lossless `false` default, while a
|
|
2133
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
2134
|
+
*/
|
|
2135
|
+
function parseCodeSkeletonSettings(value) {
|
|
2136
|
+
if (value === void 0) return { enabled: false };
|
|
2137
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression codeSkeleton must be a plain object");
|
|
2138
|
+
const keys = Object.keys(value);
|
|
2139
|
+
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
2140
|
+
const enabled = value.enabled;
|
|
2141
|
+
if (typeof enabled !== "boolean") throw new TypeError("Context-compression codeSkeleton.enabled must be a boolean");
|
|
2142
|
+
return { enabled };
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
|
|
2146
|
+
* section semantics: absent inherits the lossless `false` default, while a
|
|
2147
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
2148
|
+
*/
|
|
2149
|
+
function parseIntentSummarySettings(value) {
|
|
2150
|
+
if (value === void 0) return { enabled: false };
|
|
2151
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
|
|
2152
|
+
const keys = Object.keys(value);
|
|
2153
|
+
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
2154
|
+
const enabled = value.enabled;
|
|
2155
|
+
if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
|
|
2156
|
+
return { enabled };
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
|
|
2160
|
+
* section semantics: absent inherits the hidden default, while a
|
|
2161
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
2162
|
+
*/
|
|
2163
|
+
function parseMonitorPanelSettings(value) {
|
|
2164
|
+
if (value === void 0) return { enabled: false };
|
|
2165
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression monitorPanel must be a plain object");
|
|
2166
|
+
const keys = Object.keys(value);
|
|
2167
|
+
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
2168
|
+
const enabled = value.enabled;
|
|
2169
|
+
if (typeof enabled !== "boolean") throw new TypeError("Context-compression monitorPanel.enabled must be a boolean");
|
|
2170
|
+
return { enabled };
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
2174
|
+
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
2175
|
+
* codeSkeleton section semantics.
|
|
2176
|
+
*/
|
|
2177
|
+
function parsePresetOptionsSettings(value) {
|
|
2178
|
+
if (value === void 0) return void 0;
|
|
2179
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression presetOptions must be a plain object");
|
|
2180
|
+
const allowed = /* @__PURE__ */ new Set([
|
|
2181
|
+
"dedupeToolResults",
|
|
2182
|
+
"summaryLocator",
|
|
2183
|
+
"prefixStabilizer",
|
|
2184
|
+
"readState",
|
|
2185
|
+
"estimatorMode",
|
|
2186
|
+
"estimatorProvider",
|
|
2187
|
+
"estimatorModel",
|
|
2188
|
+
"estimatorBaseUrl",
|
|
2189
|
+
"estimatorApiKey",
|
|
2190
|
+
"estimatorTimeoutMs",
|
|
2191
|
+
"reviewMode",
|
|
2192
|
+
"reviewTimeoutTurns",
|
|
2193
|
+
"cacheHitDiscountAlpha",
|
|
2194
|
+
"reviewHighImpactTokens",
|
|
2195
|
+
"advisorMode",
|
|
2196
|
+
"advisorTimeoutMs",
|
|
2197
|
+
"advisorRefreshTurns",
|
|
2198
|
+
"advisorScoreThreshold",
|
|
2199
|
+
"advisorSampleLimit",
|
|
2200
|
+
"advisorMinTokens"
|
|
2201
|
+
]);
|
|
2202
|
+
const unknown = Object.keys(value).find((key) => !allowed.has(key));
|
|
2203
|
+
if (unknown !== void 0) throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`);
|
|
2204
|
+
for (const key of [
|
|
2205
|
+
"dedupeToolResults",
|
|
2206
|
+
"summaryLocator",
|
|
2207
|
+
"prefixStabilizer",
|
|
2208
|
+
"readState"
|
|
2209
|
+
]) {
|
|
2210
|
+
const entry = value[key];
|
|
2211
|
+
if (entry !== void 0 && typeof entry !== "boolean") throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`);
|
|
2212
|
+
}
|
|
2213
|
+
const estimatorMode = value.estimatorMode;
|
|
2214
|
+
if (estimatorMode !== void 0 && estimatorMode !== "" && estimatorMode !== "host" && estimatorMode !== "direct") throw new TypeError("Context-compression presetOptions.estimatorMode must be \"\", \"host\", or \"direct\"");
|
|
2215
|
+
const advisorMode = value.advisorMode;
|
|
2216
|
+
if (advisorMode !== void 0 && advisorMode !== "" && advisorMode !== "host" && advisorMode !== "direct") throw new TypeError("Context-compression presetOptions.advisorMode must be \"\", \"host\", or \"direct\"");
|
|
2217
|
+
const advisorTimeoutMs = value.advisorTimeoutMs;
|
|
2218
|
+
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");
|
|
2219
|
+
const advisorRefreshTurns = value.advisorRefreshTurns;
|
|
2220
|
+
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");
|
|
2221
|
+
const advisorScoreThreshold = value.advisorScoreThreshold;
|
|
2222
|
+
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");
|
|
2223
|
+
const advisorSampleLimit = value.advisorSampleLimit;
|
|
2224
|
+
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");
|
|
2225
|
+
const advisorMinTokens = value.advisorMinTokens;
|
|
2226
|
+
if (advisorMinTokens !== void 0 && (typeof advisorMinTokens !== "number" || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) throw new TypeError("Context-compression presetOptions.advisorMinTokens must be a positive integer");
|
|
2227
|
+
const estimatorTimeoutMs = value.estimatorTimeoutMs;
|
|
2228
|
+
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");
|
|
2229
|
+
for (const key of [
|
|
2230
|
+
"estimatorProvider",
|
|
2231
|
+
"estimatorModel",
|
|
2232
|
+
"estimatorBaseUrl",
|
|
2233
|
+
"estimatorApiKey"
|
|
2234
|
+
]) {
|
|
2235
|
+
const entry = value[key];
|
|
2236
|
+
if (entry !== void 0 && typeof entry !== "string") throw new TypeError(`Context-compression presetOptions.${key} must be a string`);
|
|
2237
|
+
}
|
|
2238
|
+
const result = {};
|
|
2239
|
+
if (value.dedupeToolResults !== void 0) result.dedupeToolResults = value.dedupeToolResults;
|
|
2240
|
+
if (value.summaryLocator !== void 0) result.summaryLocator = value.summaryLocator;
|
|
2241
|
+
if (value.prefixStabilizer !== void 0) result.prefixStabilizer = value.prefixStabilizer;
|
|
2242
|
+
if (value.readState !== void 0) result.readState = value.readState;
|
|
2243
|
+
if (estimatorMode !== void 0) result.estimatorMode = estimatorMode;
|
|
2244
|
+
if (value.estimatorProvider !== void 0) result.estimatorProvider = value.estimatorProvider;
|
|
2245
|
+
if (value.estimatorModel !== void 0) result.estimatorModel = value.estimatorModel;
|
|
2246
|
+
if (value.estimatorBaseUrl !== void 0) result.estimatorBaseUrl = value.estimatorBaseUrl;
|
|
2247
|
+
if (value.estimatorApiKey !== void 0) result.estimatorApiKey = value.estimatorApiKey;
|
|
2248
|
+
if (estimatorTimeoutMs !== void 0) result.estimatorTimeoutMs = estimatorTimeoutMs;
|
|
2249
|
+
if (advisorMode !== void 0) result.advisorMode = advisorMode;
|
|
2250
|
+
if (advisorTimeoutMs !== void 0) result.advisorTimeoutMs = advisorTimeoutMs;
|
|
2251
|
+
if (advisorRefreshTurns !== void 0) result.advisorRefreshTurns = advisorRefreshTurns;
|
|
2252
|
+
if (advisorScoreThreshold !== void 0) result.advisorScoreThreshold = advisorScoreThreshold;
|
|
2253
|
+
if (advisorSampleLimit !== void 0) result.advisorSampleLimit = advisorSampleLimit;
|
|
2254
|
+
if (advisorMinTokens !== void 0) result.advisorMinTokens = advisorMinTokens;
|
|
2255
|
+
return result;
|
|
2256
|
+
}
|
|
2257
|
+
/** Settings schema used by the user-facing profile selector. */
|
|
2258
|
+
const contextCompressionSettingsInputSchema = z.object({
|
|
2259
|
+
profile: z.union([...COMPRESSION_PROFILES]).default("balanced"),
|
|
2260
|
+
custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY)
|
|
2261
|
+
});
|
|
2262
|
+
/**
|
|
2263
|
+
* Reject a section that is PRESENT but not a usable value. Schemastery
|
|
2264
|
+
* `.default(...)` silently substitutes null and undefined, which would turn a
|
|
2265
|
+
* hand-corrupted store into the (lossy) default policy; only genuinely absent
|
|
2266
|
+
* keys may inherit defaults, and that distinction must be made before any
|
|
2267
|
+
* default can fire.
|
|
2268
|
+
*/
|
|
2269
|
+
function assertPresentSection(candidate, key, valid) {
|
|
2270
|
+
if (!Object.hasOwn(candidate, key)) return;
|
|
2271
|
+
if (!valid(candidate[key])) throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`);
|
|
2272
|
+
}
|
|
2273
|
+
const isSupportedProfile = (value) => typeof value === "string" && COMPRESSION_PROFILES.includes(value);
|
|
2274
|
+
const isUsableCustomDocument = (value) => isPlainRecord(value);
|
|
2275
|
+
const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
|
|
2276
|
+
profile: "balanced",
|
|
2277
|
+
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
2278
|
+
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
2279
|
+
codeSkeleton: { enabled: false },
|
|
2280
|
+
intentSummary: { enabled: false },
|
|
2281
|
+
monitorPanel: { enabled: false }
|
|
2282
|
+
};
|
|
2283
|
+
/**
|
|
2284
|
+
* Parse one settings document with the persisted-section semantics: `undefined`
|
|
2285
|
+
* inherits the defaults (an absent section), while `null` is an explicitly
|
|
2286
|
+
* invalid document and must never silently become the default policy.
|
|
2287
|
+
*/
|
|
2288
|
+
function parseContextCompressionSettings(value) {
|
|
2289
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
2290
|
+
const keys = Object.keys(value);
|
|
2291
|
+
if (keys.length === 0 || !keys.includes("profile") || !keys.includes("custom")) throw new TypeError("Context-compression settings document is missing its complete shape");
|
|
2292
|
+
return ContextCompressionSettingsSchema(value);
|
|
2293
|
+
}
|
|
2294
|
+
/** Settings schema used by the user-facing profile selector. */
|
|
2295
|
+
const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value) => {
|
|
2296
|
+
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
2297
|
+
assertPlainDataTree(value);
|
|
2298
|
+
const candidate = structuredClone(value);
|
|
2299
|
+
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
|
|
2300
|
+
if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
|
|
2301
|
+
assertPresentSection(candidate, "profile", isSupportedProfile);
|
|
2302
|
+
assertPresentSection(candidate, "custom", isUsableCustomDocument);
|
|
2303
|
+
const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
|
|
2304
|
+
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
|
|
2305
|
+
const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
|
|
2306
|
+
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
|
|
2307
|
+
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
|
|
2308
|
+
return {
|
|
2309
|
+
...contextCompressionSettingsInputSchema(candidate),
|
|
2310
|
+
autoCompact,
|
|
2311
|
+
codeSkeleton,
|
|
2312
|
+
intentSummary,
|
|
2313
|
+
monitorPanel,
|
|
2314
|
+
...presetOptions === void 0 ? {} : { presetOptions }
|
|
2315
|
+
};
|
|
2316
|
+
}).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
|
|
2317
|
+
/** Low-friction defaults; token budgets live in resolved profile policy. */
|
|
2318
|
+
const DEFAULTS = deepFreeze({
|
|
2319
|
+
profile: "balanced",
|
|
2320
|
+
headChars: 4096,
|
|
2321
|
+
tailChars: 1024
|
|
2322
|
+
});
|
|
2323
|
+
const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
2324
|
+
"profile",
|
|
2325
|
+
"headChars",
|
|
2326
|
+
"tailChars",
|
|
2327
|
+
"nativeTriggerTokens",
|
|
2328
|
+
"nativeTargetTokens",
|
|
2329
|
+
"freshTriggerTokens",
|
|
2330
|
+
"freshTargetTokens",
|
|
2331
|
+
"aggregateTriggerTokens",
|
|
2332
|
+
"aggregateTargetTokens",
|
|
2333
|
+
"historyTriggerTokens",
|
|
2334
|
+
"historyKeepRecentToolCalls",
|
|
2335
|
+
"historyKeepRecentTokens",
|
|
2336
|
+
"historyMinReclaimTokens",
|
|
2337
|
+
"readInputCapChars",
|
|
2338
|
+
"autoCompactThresholdPercent",
|
|
2339
|
+
"presetOptions"
|
|
2340
|
+
]);
|
|
2341
|
+
const LEGACY_GATE_REPLACEMENTS = Object.freeze({
|
|
2342
|
+
thresholdChars: "nativeTriggerTokens",
|
|
2343
|
+
freshThresholdChars: "freshTriggerTokens",
|
|
2344
|
+
freshTargetChars: "freshTargetTokens",
|
|
2345
|
+
freshBatchTriggerChars: "aggregateTriggerTokens",
|
|
2346
|
+
freshBatchTargetChars: "aggregateTargetTokens",
|
|
2347
|
+
historyTriggerChars: "historyTriggerTokens",
|
|
2348
|
+
historyKeepRecentChars: "historyKeepRecentTokens",
|
|
2349
|
+
historyMinReclaimChars: "historyMinReclaimTokens",
|
|
2350
|
+
historyKeepRecentTurns: "historyKeepRecentToolCalls"
|
|
2351
|
+
});
|
|
2352
|
+
/**
|
|
2353
|
+
* Count Unicode code points without splitting surrogate pairs.
|
|
2354
|
+
* @param text - text whose code points are counted.
|
|
2355
|
+
* @returns the number of Unicode code points.
|
|
2356
|
+
*/
|
|
2357
|
+
function codePointLength(text) {
|
|
2358
|
+
let length = 0;
|
|
2359
|
+
for (const _point of text) length++;
|
|
2360
|
+
return length;
|
|
2361
|
+
}
|
|
2362
|
+
/** Express one token-named policy gate on the character basis. */
|
|
2363
|
+
function charsForTokens(tokens) {
|
|
2364
|
+
return tokens * 4;
|
|
2365
|
+
}
|
|
2366
|
+
/** Derive the telemetry-only token figure from a character measurement. */
|
|
2367
|
+
function charsToTokens(chars) {
|
|
2368
|
+
if (!Number.isFinite(chars) || chars <= 0) return 0;
|
|
2369
|
+
return Math.max(1, Math.round(chars / 4));
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Test whether a settings value names a supported compression profile.
|
|
2373
|
+
* @param value - untrusted settings value.
|
|
2374
|
+
* @returns whether the value is a supported compression profile.
|
|
2375
|
+
*/
|
|
2376
|
+
function isCompressionProfile(value) {
|
|
2377
|
+
return typeof value === "string" && COMPRESSION_PROFILES.includes(value);
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Resolve and validate plugin configuration.
|
|
2381
|
+
* @param config - optional composition overrides.
|
|
2382
|
+
* @returns a detached, deeply immutable configuration snapshot.
|
|
2383
|
+
*/
|
|
2384
|
+
function resolveConfig(config = {}) {
|
|
2385
|
+
for (const key of Object.keys(config)) {
|
|
2386
|
+
const replacement = LEGACY_GATE_REPLACEMENTS[key];
|
|
2387
|
+
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)`);
|
|
2388
|
+
if (!CONFIG_KEYS.has(key)) throw new Error(`ToolResultPruneConfig: unknown key "${key}"`);
|
|
2389
|
+
}
|
|
2390
|
+
const resolved = {
|
|
2391
|
+
profile: config.profile ?? DEFAULTS.profile,
|
|
2392
|
+
headChars: config.headChars ?? DEFAULTS.headChars,
|
|
2393
|
+
tailChars: config.tailChars ?? DEFAULTS.tailChars,
|
|
2394
|
+
...config.nativeTriggerTokens === void 0 ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
|
|
2395
|
+
...config.nativeTargetTokens === void 0 ? {} : { nativeTargetTokens: config.nativeTargetTokens },
|
|
2396
|
+
...config.freshTriggerTokens === void 0 ? {} : { freshTriggerTokens: config.freshTriggerTokens },
|
|
2397
|
+
...config.freshTargetTokens === void 0 ? {} : { freshTargetTokens: config.freshTargetTokens },
|
|
2398
|
+
...config.aggregateTriggerTokens === void 0 ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
|
|
2399
|
+
...config.aggregateTargetTokens === void 0 ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
|
|
2400
|
+
...config.historyTriggerTokens === void 0 ? {} : { historyTriggerTokens: config.historyTriggerTokens },
|
|
2401
|
+
...config.historyKeepRecentToolCalls === void 0 ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
|
|
2402
|
+
...config.historyKeepRecentTokens === void 0 ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
|
|
2403
|
+
...config.historyMinReclaimTokens === void 0 ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
|
|
2404
|
+
...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
|
|
2405
|
+
...config.autoCompactThresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
|
|
2406
|
+
...config.presetOptions === void 0 ? {} : { presetOptions: config.presetOptions }
|
|
2407
|
+
};
|
|
2408
|
+
if (!isCompressionProfile(resolved.profile)) throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`);
|
|
2409
|
+
assertNonNegativeInteger("headChars", resolved.headChars);
|
|
2410
|
+
assertNonNegativeInteger("tailChars", resolved.tailChars);
|
|
2411
|
+
for (const key of [
|
|
2412
|
+
"nativeTriggerTokens",
|
|
2413
|
+
"nativeTargetTokens",
|
|
2414
|
+
"freshTriggerTokens",
|
|
2415
|
+
"freshTargetTokens",
|
|
2416
|
+
"aggregateTriggerTokens",
|
|
2417
|
+
"aggregateTargetTokens",
|
|
2418
|
+
"historyTriggerTokens",
|
|
2419
|
+
"historyMinReclaimTokens",
|
|
2420
|
+
"readInputCapChars"
|
|
2421
|
+
]) {
|
|
2422
|
+
const value = resolved[key];
|
|
2423
|
+
if (value !== void 0) assertPositiveInteger(key, value);
|
|
2424
|
+
}
|
|
2425
|
+
if (resolved.historyKeepRecentToolCalls !== void 0) assertNonNegativeInteger("historyKeepRecentToolCalls", resolved.historyKeepRecentToolCalls);
|
|
2426
|
+
if (resolved.historyKeepRecentTokens !== void 0) assertNonNegativeInteger("historyKeepRecentTokens", resolved.historyKeepRecentTokens);
|
|
2427
|
+
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)}`);
|
|
2428
|
+
assertTargetBelowTrigger("native", resolved.nativeTargetTokens, resolved.nativeTriggerTokens);
|
|
2429
|
+
assertTargetBelowTrigger("fresh", resolved.freshTargetTokens, resolved.freshTriggerTokens);
|
|
2430
|
+
assertTargetBelowTrigger("aggregate", resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens);
|
|
2431
|
+
return deepFreeze(structuredClone(resolved));
|
|
2432
|
+
}
|
|
2433
|
+
/** Per-profile History linkage ratios applied to the Auto Compact watermark. */
|
|
2434
|
+
const AUTO_COMPACT_HISTORY_RATIOS = Object.freeze({
|
|
2435
|
+
balanced: Object.freeze({
|
|
2436
|
+
trigger: .625,
|
|
2437
|
+
minReclaim: .12,
|
|
2438
|
+
keepRecentTokens: .08
|
|
2439
|
+
}),
|
|
2440
|
+
savings: Object.freeze({
|
|
2441
|
+
trigger: .5,
|
|
2442
|
+
minReclaim: .16,
|
|
2443
|
+
keepRecentTokens: .08
|
|
2444
|
+
}),
|
|
2445
|
+
"cache-strict": Object.freeze({
|
|
2446
|
+
trigger: .75,
|
|
2447
|
+
minReclaim: .16,
|
|
2448
|
+
keepRecentTokens: .08
|
|
2449
|
+
}),
|
|
2450
|
+
adaptive: Object.freeze({
|
|
2451
|
+
trigger: .625,
|
|
2452
|
+
minReclaim: .12,
|
|
2453
|
+
keepRecentTokens: .08
|
|
2454
|
+
}),
|
|
2455
|
+
"tokenpilot-inspired": Object.freeze({
|
|
2456
|
+
trigger: .625,
|
|
2457
|
+
minReclaim: .12,
|
|
2458
|
+
keepRecentTokens: .08
|
|
2459
|
+
})
|
|
2460
|
+
});
|
|
2461
|
+
/** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
|
|
2462
|
+
const MICRO_DEADLINE_RATIO = .875;
|
|
2463
|
+
/**
|
|
2464
|
+
* TokenPilot-inspired sub-capability defaults. Every capability is on except
|
|
2465
|
+
* the estimator, which requires an explicit endpoint channel (host or direct)
|
|
2466
|
+
* before any consumer may leave its rule-only fallback.
|
|
2467
|
+
*/
|
|
2468
|
+
const PRESET_OPTION_DEFAULTS = deepFreeze({
|
|
2469
|
+
noNetSavingsGuard: true,
|
|
2470
|
+
skipReductionRecovery: true,
|
|
2471
|
+
dedupeToolResults: true,
|
|
2472
|
+
summaryLocator: true,
|
|
2473
|
+
prefixStabilizer: true,
|
|
2474
|
+
readState: true,
|
|
2475
|
+
estimator: { mode: "" },
|
|
2476
|
+
advisor: {
|
|
2477
|
+
mode: "",
|
|
2478
|
+
timeoutMs: 8e3,
|
|
2479
|
+
refreshTurns: 8,
|
|
2480
|
+
scoreThreshold: .35,
|
|
2481
|
+
sampleLimit: 16,
|
|
2482
|
+
minTokens: 250
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
/**
|
|
2486
|
+
* Merge persisted presetOptions overrides over the tokenpilot-inspired
|
|
2487
|
+
* defaults. Persisted booleans are three-state (undefined = inherit); the
|
|
2488
|
+
* estimator channel overrides the default empty mode wholesale.
|
|
2489
|
+
*/
|
|
2490
|
+
function mergePresetOptions(overrides) {
|
|
2491
|
+
if (overrides === void 0) return PRESET_OPTION_DEFAULTS;
|
|
2492
|
+
return deepFreeze({
|
|
2493
|
+
noNetSavingsGuard: true,
|
|
2494
|
+
skipReductionRecovery: true,
|
|
2495
|
+
dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
|
|
2496
|
+
summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
|
|
2497
|
+
prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
|
|
2498
|
+
readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
|
|
2499
|
+
estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
|
|
2500
|
+
advisor: {
|
|
2501
|
+
mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
|
|
2502
|
+
timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
|
|
2503
|
+
refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
|
|
2504
|
+
scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
|
|
2505
|
+
sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
|
|
2506
|
+
minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens
|
|
2507
|
+
}
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
/**
|
|
2511
|
+
* Resolve the Auto-Compact-linked History watermarks for one standard profile.
|
|
2512
|
+
*
|
|
2513
|
+
* `A = floor(C × a)` is the Auto Compact token watermark for the routed
|
|
2514
|
+
* context window `C` and the user threshold `a = p / 100`; the History
|
|
2515
|
+
* trigger, minimum reclaim, and recent-token tail scale with `A`, and the
|
|
2516
|
+
* micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
|
|
2517
|
+
* defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
|
|
2518
|
+
* preset numbers exactly. Custom stays manual and Off/Native run no History,
|
|
2519
|
+
* so none of them link.
|
|
2520
|
+
*/
|
|
2521
|
+
function resolveAutoCompactLinkage(profile, options) {
|
|
2522
|
+
const ratios = profile === "custom" ? void 0 : AUTO_COMPACT_HISTORY_RATIOS[profile];
|
|
2523
|
+
const contextWindow = options.contextWindowTokens;
|
|
2524
|
+
const threshold = options.autoCompactThresholdPercent;
|
|
2525
|
+
if (ratios === void 0) return void 0;
|
|
2526
|
+
if (!isValidAutoCompactThresholdPercent(threshold)) return void 0;
|
|
2527
|
+
if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) return void 0;
|
|
2528
|
+
const autoCompactTokens = Math.floor(contextWindow * (threshold / 100));
|
|
2529
|
+
if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return void 0;
|
|
2530
|
+
const linked = {
|
|
2531
|
+
autoCompactTokens,
|
|
2532
|
+
microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
|
|
2533
|
+
historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
|
|
2534
|
+
historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
|
|
2535
|
+
historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens)
|
|
2536
|
+
};
|
|
2537
|
+
for (const value of Object.values(linked)) if (!Number.isSafeInteger(value) || value <= 0) return void 0;
|
|
2538
|
+
return linked;
|
|
2539
|
+
}
|
|
2540
|
+
/**
|
|
2541
|
+
* Resolve one public profile into a complete mixed-strategy policy.
|
|
2542
|
+
* @param config - validated composition configuration.
|
|
2543
|
+
* @param profile - profile frozen for the target Session.
|
|
2544
|
+
* @param custom - versioned Custom document used only by the `custom` profile.
|
|
2545
|
+
* @param options - routed capacity and the frozen Auto Compact threshold used
|
|
2546
|
+
* to resolve context-percent Custom values and standard-profile linkage.
|
|
2547
|
+
* @returns the effective deterministic compression policy.
|
|
2548
|
+
*/
|
|
2549
|
+
function resolvePolicy(config, profile, custom = DEFAULT_CUSTOM_COMPRESSION_POLICY, options = {}) {
|
|
2550
|
+
if (profile === "custom") return resolveCustomPolicy(custom, options);
|
|
2551
|
+
const preset = {
|
|
2552
|
+
off: {
|
|
2553
|
+
nativeToolResultEnabled: false,
|
|
2554
|
+
freshEnabled: false,
|
|
2555
|
+
aggregateEnabled: false,
|
|
2556
|
+
historyMode: "disabled",
|
|
2557
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2558
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2559
|
+
freshTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2560
|
+
freshTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2561
|
+
aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2562
|
+
aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2563
|
+
historyTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2564
|
+
historyKeepRecentToolCalls: 10,
|
|
2565
|
+
historyKeepRecentTokens: 64e3,
|
|
2566
|
+
historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
|
|
2567
|
+
},
|
|
2568
|
+
native: {
|
|
2569
|
+
nativeToolResultEnabled: true,
|
|
2570
|
+
freshEnabled: false,
|
|
2571
|
+
aggregateEnabled: false,
|
|
2572
|
+
historyMode: "disabled",
|
|
2573
|
+
nativeTriggerTokens: 4096,
|
|
2574
|
+
nativeTargetTokens: 2048,
|
|
2575
|
+
freshTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2576
|
+
freshTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2577
|
+
aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2578
|
+
aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2579
|
+
historyTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2580
|
+
historyKeepRecentToolCalls: 10,
|
|
2581
|
+
historyKeepRecentTokens: 64e3,
|
|
2582
|
+
historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
|
|
2583
|
+
},
|
|
2584
|
+
balanced: {
|
|
2585
|
+
nativeToolResultEnabled: false,
|
|
2586
|
+
freshEnabled: true,
|
|
2587
|
+
aggregateEnabled: true,
|
|
2588
|
+
historyMode: "routine",
|
|
2589
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2590
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2591
|
+
freshTriggerTokens: 8192,
|
|
2592
|
+
freshTargetTokens: 3072,
|
|
2593
|
+
aggregateTriggerTokens: 32768,
|
|
2594
|
+
aggregateTargetTokens: 12288,
|
|
2595
|
+
historyTriggerTokens: 5e5,
|
|
2596
|
+
historyKeepRecentToolCalls: 10,
|
|
2597
|
+
historyKeepRecentTokens: 64e3,
|
|
2598
|
+
historyMinReclaimTokens: 96e3
|
|
2599
|
+
},
|
|
2600
|
+
"cache-strict": {
|
|
2601
|
+
nativeToolResultEnabled: false,
|
|
2602
|
+
freshEnabled: true,
|
|
2603
|
+
aggregateEnabled: true,
|
|
2604
|
+
historyMode: "capacity-pressure",
|
|
2605
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2606
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2607
|
+
freshTriggerTokens: 8192,
|
|
2608
|
+
freshTargetTokens: 3072,
|
|
2609
|
+
aggregateTriggerTokens: 32768,
|
|
2610
|
+
aggregateTargetTokens: 12288,
|
|
2611
|
+
historyTriggerTokens: 6e5,
|
|
2612
|
+
historyKeepRecentToolCalls: 10,
|
|
2613
|
+
historyKeepRecentTokens: 64e3,
|
|
2614
|
+
historyMinReclaimTokens: 128e3
|
|
2615
|
+
},
|
|
2616
|
+
savings: {
|
|
2617
|
+
nativeToolResultEnabled: false,
|
|
2618
|
+
freshEnabled: true,
|
|
2619
|
+
aggregateEnabled: true,
|
|
2620
|
+
historyMode: "routine",
|
|
2621
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2622
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2623
|
+
freshTriggerTokens: 4096,
|
|
2624
|
+
freshTargetTokens: 1536,
|
|
2625
|
+
aggregateTriggerTokens: 16384,
|
|
2626
|
+
aggregateTargetTokens: 4096,
|
|
2627
|
+
historyTriggerTokens: 4e5,
|
|
2628
|
+
historyKeepRecentToolCalls: 10,
|
|
2629
|
+
historyKeepRecentTokens: 64e3,
|
|
2630
|
+
historyMinReclaimTokens: 128e3
|
|
2631
|
+
},
|
|
2632
|
+
adaptive: {
|
|
2633
|
+
nativeToolResultEnabled: false,
|
|
2634
|
+
freshEnabled: true,
|
|
2635
|
+
aggregateEnabled: true,
|
|
2636
|
+
historyMode: "adaptive",
|
|
2637
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2638
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2639
|
+
freshTriggerTokens: 8192,
|
|
2640
|
+
freshTargetTokens: 3072,
|
|
2641
|
+
aggregateTriggerTokens: 32768,
|
|
2642
|
+
aggregateTargetTokens: 12288,
|
|
2643
|
+
historyTriggerTokens: 5e5,
|
|
2644
|
+
historyKeepRecentToolCalls: 10,
|
|
2645
|
+
historyKeepRecentTokens: 64e3,
|
|
2646
|
+
historyMinReclaimTokens: 96e3
|
|
2647
|
+
},
|
|
2648
|
+
"tokenpilot-inspired": {
|
|
2649
|
+
nativeToolResultEnabled: false,
|
|
2650
|
+
freshEnabled: true,
|
|
2651
|
+
aggregateEnabled: true,
|
|
2652
|
+
historyMode: "routine",
|
|
2653
|
+
nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
|
|
2654
|
+
nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
2655
|
+
freshTriggerTokens: 4096,
|
|
2656
|
+
freshTargetTokens: 1536,
|
|
2657
|
+
aggregateTriggerTokens: 32768,
|
|
2658
|
+
aggregateTargetTokens: 12288,
|
|
2659
|
+
historyTriggerTokens: 5e5,
|
|
2660
|
+
historyKeepRecentToolCalls: 10,
|
|
2661
|
+
historyKeepRecentTokens: 64e3,
|
|
2662
|
+
historyMinReclaimTokens: 96e3
|
|
2663
|
+
}
|
|
2664
|
+
}[profile];
|
|
2665
|
+
const linkage = resolveAutoCompactLinkage(profile, options);
|
|
2666
|
+
const policy = {
|
|
2667
|
+
profile,
|
|
2668
|
+
...preset,
|
|
2669
|
+
nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
|
|
2670
|
+
nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
|
|
2671
|
+
freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
|
|
2672
|
+
freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
|
|
2673
|
+
aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
|
|
2674
|
+
aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
|
|
2675
|
+
historyTriggerTokens: config.historyTriggerTokens ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
|
|
2676
|
+
historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
|
|
2677
|
+
historyKeepRecentTokens: config.historyKeepRecentTokens ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
|
|
2678
|
+
historyMinReclaimTokens: config.historyMinReclaimTokens ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
|
|
2679
|
+
...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
|
|
2680
|
+
...linkage === void 0 ? {} : {
|
|
2681
|
+
autoCompactTokens: linkage.autoCompactTokens,
|
|
2682
|
+
microDeadlineTokens: linkage.microDeadlineTokens
|
|
2683
|
+
},
|
|
2684
|
+
...profile === "tokenpilot-inspired" ? { presetOptions: mergePresetOptions(config.presetOptions) } : {}
|
|
2685
|
+
};
|
|
2686
|
+
if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === "native") throw new Error("context compression policy: native target must be below trigger");
|
|
2687
|
+
if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: fresh target must be below trigger");
|
|
2688
|
+
if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: aggregate target must be below trigger");
|
|
2689
|
+
if (policy.readInputCapChars !== void 0 && policy.readInputCapChars <= policy.freshTriggerTokens * 4) throw new Error("context compression policy: read input cap would silence the fresh path");
|
|
2690
|
+
return deepFreeze(policy);
|
|
2691
|
+
}
|
|
2692
|
+
function assertTargetBelowTrigger(label, target, trigger) {
|
|
2693
|
+
if (target === void 0 !== (trigger === void 0)) throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`);
|
|
2694
|
+
if (target !== void 0 && trigger !== void 0 && target >= trigger) throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`);
|
|
2695
|
+
}
|
|
2696
|
+
function assertPositiveInteger(name, value) {
|
|
2697
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`);
|
|
2698
|
+
}
|
|
2699
|
+
function assertNonNegativeInteger(name, value) {
|
|
2700
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
|
|
2701
|
+
}
|
|
2702
|
+
/** Count the lines present in the original but absent from the replacement. */
|
|
2703
|
+
function countOmittedLines(original, replacement) {
|
|
2704
|
+
const omitted = original.split("\n").length - replacement.split("\n").length;
|
|
2705
|
+
return omitted > 0 ? omitted : void 0;
|
|
2706
|
+
}
|
|
2707
|
+
/** Routed-context utilization required before capacity-pressure History may age sent history. */
|
|
2708
|
+
const CAPACITY_PRESSURE_RATIO = .7;
|
|
2709
|
+
//#endregion
|
|
2710
|
+
//#region src/pruner/content.ts
|
|
2711
|
+
function onlyTextBlock(blocks) {
|
|
2712
|
+
return blocks.length === 1 && blocks[0]?.type === "text" ? blocks[0] : null;
|
|
2713
|
+
}
|
|
2714
|
+
function onlyTextBlocks(blocks) {
|
|
2715
|
+
return blocks.every((block) => block.type === "text") ? blocks : null;
|
|
2716
|
+
}
|
|
2717
|
+
function countToolContent(blocks, view) {
|
|
2718
|
+
const text = onlyTextBlocks(blocks);
|
|
2719
|
+
if (text === null) return unavailableCount("tool result contains unsupported rich content");
|
|
2720
|
+
return countExactCanonicalTextFields(text.map((block) => block.text), (candidate) => view.countCanonicalText(candidate), "tool result replacement");
|
|
2721
|
+
}
|
|
2722
|
+
function sameProviderMeasurementKey(left, right) {
|
|
2723
|
+
return left.provider === right.provider && left.baseUrlClass === right.baseUrlClass && left.apiRoute === right.apiRoute && left.modelId === right.modelId && left.requestTemplateRevision === right.requestTemplateRevision && left.tokenizerRevision === right.tokenizerRevision && left.modality === right.modality;
|
|
2724
|
+
}
|
|
2725
|
+
function unavailableCount(reason) {
|
|
2726
|
+
return Object.freeze({
|
|
2727
|
+
kind: "unavailable",
|
|
2728
|
+
reason
|
|
2729
|
+
});
|
|
2730
|
+
}
|
|
2731
|
+
function recoveryMarker(sourceRef, label, startLine) {
|
|
2732
|
+
return `\n\n[... ${label}; source=${sourceRef}; ${startLine === void 0 ? "use context_compression_retrieve with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)" : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`} ...]\n\n`;
|
|
2733
|
+
}
|
|
2734
|
+
/**
|
|
2735
|
+
* Measure text content in Unicode code points; non-text blocks cost zero.
|
|
2736
|
+
* @param blocks - tool-result content to measure.
|
|
2737
|
+
* @returns total Unicode code points across text blocks.
|
|
2738
|
+
*/
|
|
2739
|
+
function measureContent(blocks) {
|
|
2740
|
+
let chars = 0;
|
|
2741
|
+
for (const block of blocks) if (block.type === "text") chars += codePointLength(block.text);
|
|
2742
|
+
return chars;
|
|
2743
|
+
}
|
|
2744
|
+
function pressureCost(blocks) {
|
|
2745
|
+
let cost = 0;
|
|
2746
|
+
for (const block of blocks) switch (block.type) {
|
|
2747
|
+
case "text":
|
|
2748
|
+
case "reasoning":
|
|
2749
|
+
cost += codePointLength(block.text);
|
|
2750
|
+
break;
|
|
2751
|
+
case "tool-call":
|
|
2752
|
+
cost += 256 + codePointLength(block.name) + codePointLength(block.arguments);
|
|
2753
|
+
break;
|
|
2754
|
+
default: {
|
|
2755
|
+
const serialized = JSON.stringify(block);
|
|
2756
|
+
cost += Math.max(256, codePointLength(serialized));
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
return cost;
|
|
2760
|
+
}
|
|
2761
|
+
function nativePruneContent(blocks, thresholdChars, headChars, tailChars, marker = PRUNE_MARKER) {
|
|
2762
|
+
const totalChars = measureContent(blocks);
|
|
2763
|
+
if (totalChars <= thresholdChars) return null;
|
|
2764
|
+
const markerChars = codePointLength(typeof marker === "function" ? marker(1) : marker);
|
|
2765
|
+
const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars));
|
|
2766
|
+
const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead));
|
|
2767
|
+
const removedStart = safeHead;
|
|
2768
|
+
const removedEnd = totalChars - safeTail;
|
|
2769
|
+
const pruned = [];
|
|
2770
|
+
let consumed = 0;
|
|
2771
|
+
let markerInserted = false;
|
|
2772
|
+
let newlinesBefore = 0;
|
|
2773
|
+
for (const block of blocks) {
|
|
2774
|
+
if (block.type !== "text") {
|
|
2775
|
+
pruned.push(block);
|
|
2776
|
+
newlinesBefore += 1;
|
|
2777
|
+
continue;
|
|
2778
|
+
}
|
|
2779
|
+
const points = Array.from(block.text);
|
|
2780
|
+
const blockStart = consumed;
|
|
2781
|
+
const blockEnd = blockStart + points.length;
|
|
2782
|
+
const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart));
|
|
2783
|
+
const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart));
|
|
2784
|
+
const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart;
|
|
2785
|
+
const headText = points.slice(0, headEnd).join("");
|
|
2786
|
+
const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted ? marker : "";
|
|
2787
|
+
if (insertion !== "") markerInserted = true;
|
|
2788
|
+
const text = points.slice(0, headEnd).join("") + insertion + points.slice(tailStart).join("");
|
|
2789
|
+
if (text !== "") pruned.push({
|
|
2790
|
+
...block,
|
|
2791
|
+
text
|
|
2792
|
+
});
|
|
2793
|
+
newlinesBefore += block.text.split("\n").length - 1 + 1;
|
|
2794
|
+
consumed = blockEnd;
|
|
2795
|
+
}
|
|
2796
|
+
if (!markerInserted) return null;
|
|
2797
|
+
const charsAfter = measureContent(pruned);
|
|
2798
|
+
return charsAfter <= thresholdChars && charsAfter < totalChars ? pruned : null;
|
|
2799
|
+
}
|
|
2800
|
+
function summarize(entries) {
|
|
2801
|
+
return {
|
|
2802
|
+
pruned: entries,
|
|
2803
|
+
charsRemoved: entries.reduce((sum, entry) => sum + entry.charsBefore - entry.charsAfter, 0),
|
|
2804
|
+
tokensRemoved: entries.reduce((sum, entry) => sum + entry.tokensBefore - entry.tokensAfter, 0)
|
|
2805
|
+
};
|
|
2806
|
+
}
|
|
2807
|
+
function emptyResult() {
|
|
2808
|
+
return {
|
|
2809
|
+
pruned: [],
|
|
2810
|
+
charsRemoved: 0,
|
|
2811
|
+
tokensRemoved: 0
|
|
2812
|
+
};
|
|
2813
|
+
}
|
|
2814
|
+
//#endregion
|
|
2815
|
+
//#region src/runtime/measurement.ts
|
|
2816
|
+
const dshSessionSoft = dshSessionNamespace;
|
|
2817
|
+
const deriveEventMessage = dshSessionSoft.deriveEventMessage ?? dshSessionSoft.default?.deriveEventMessage ?? (() => null);
|
|
2818
|
+
/**
|
|
2819
|
+
* Character pressure of one model-visible content array, measured on the same
|
|
2820
|
+
* level `SnapshotCandidate.characterPressure` uses: a tool/result message is
|
|
2821
|
+
* measured by its inner tool-result content, never by the wrapper block, so the
|
|
2822
|
+
* node-level and candidate-level figures stay directly comparable.
|
|
2823
|
+
* @param content - the node's model-visible content blocks.
|
|
2824
|
+
* @returns character pressure in Unicode code points, plus rich-block costs.
|
|
2825
|
+
*/
|
|
2826
|
+
function nodeCharacterPressure(content) {
|
|
2827
|
+
return pressureCost(content);
|
|
2828
|
+
}
|
|
2829
|
+
const VISION_MODEL_ID = DEEPSEEK_VISION_TOKENIZER_ARTIFACT.modelIds[0];
|
|
2830
|
+
/**
|
|
2831
|
+
* Capture one route-bound view without calling patched Harness methods.
|
|
2832
|
+
* Official `measure()` remains authoritative for request pressure; the bundled
|
|
2833
|
+
* tokenizer supplies exact canonical content counts used by safe rewrites.
|
|
2834
|
+
*/
|
|
2835
|
+
function measureForCompaction(ctx, session) {
|
|
2836
|
+
const header = session.requestHeader();
|
|
2837
|
+
const measurement = ctx.tokenMeter.measure(session, header);
|
|
2838
|
+
const target = header?.config;
|
|
2839
|
+
const counter = bindCounter(target?.provider, target?.model);
|
|
2840
|
+
const events = sessionEvents(session);
|
|
2841
|
+
const eventsBySeq = new Map(events.map((event) => [Number(event.seq), event]));
|
|
2842
|
+
const measuredNodes = measurement.nodes.map((node) => {
|
|
2843
|
+
const event = eventsBySeq.get(Number(node.seq));
|
|
2844
|
+
if (event === void 0) return {
|
|
2845
|
+
seq: node.seq,
|
|
2846
|
+
count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`),
|
|
2847
|
+
characterPressure: 0
|
|
2848
|
+
};
|
|
2849
|
+
const message = deriveEventMessage(event);
|
|
2850
|
+
if (message === null) return {
|
|
2851
|
+
seq: node.seq,
|
|
2852
|
+
count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`),
|
|
2853
|
+
characterPressure: 0
|
|
2854
|
+
};
|
|
2855
|
+
const count = countCanonicalContent(message.content, counter, `surface node ${String(node.seq)}`);
|
|
2856
|
+
const intrinsicImageBlockEstimate = count.kind === "tokenizer-estimate" ? intrinsicImageDiagnostic(message.content, target) : void 0;
|
|
2857
|
+
return {
|
|
2858
|
+
seq: node.seq,
|
|
2859
|
+
count,
|
|
2860
|
+
characterPressure: nodeCharacterPressure(message.content),
|
|
2861
|
+
...intrinsicImageBlockEstimate === void 0 ? {} : { intrinsicImageBlockEstimate }
|
|
2862
|
+
};
|
|
2863
|
+
});
|
|
2864
|
+
const currentSurface = countSurfaceCounts(measuredNodes.map((node) => node.count), "current surface");
|
|
2865
|
+
const currentSurfaceChars = measuredNodes.reduce((sum, node) => sum + node.characterPressure, 0);
|
|
2866
|
+
const intrinsicImageBlockEstimateTokens = measuredNodes.reduce((sum, node) => sum + (node.intrinsicImageBlockEstimate?.paddingMinimumTokens ?? 0), 0);
|
|
2867
|
+
return Object.freeze({
|
|
2868
|
+
...measurement,
|
|
2869
|
+
...target === void 0 ? {} : {
|
|
2870
|
+
providerRoute: target.provider,
|
|
2871
|
+
modelId: target.model
|
|
2872
|
+
},
|
|
2873
|
+
measuredNodes: Object.freeze(measuredNodes),
|
|
2874
|
+
currentSurface,
|
|
2875
|
+
currentSurfaceChars,
|
|
2876
|
+
intrinsicImageBlockEstimateTokens,
|
|
2877
|
+
countCanonicalText: counter.countText
|
|
2878
|
+
});
|
|
2879
|
+
}
|
|
2880
|
+
/** Request-level usage exposed by official TokenMeter, without invented route attribution. */
|
|
2881
|
+
function officialRequestUsage(view) {
|
|
2882
|
+
return view.baseline.kind === "usage" ? view.baseline.usage : void 0;
|
|
2883
|
+
}
|
|
2884
|
+
/**
|
|
2885
|
+
* Count one canonical content walk in canonical field order.
|
|
2886
|
+
*
|
|
2887
|
+
* Text, reasoning, tool-call names/arguments, and nested text tool results are
|
|
2888
|
+
* counted exactly with one tokenizer identity. Image blocks produce a bounded
|
|
2889
|
+
* estimate because the absolute prompt position and the adapter's final
|
|
2890
|
+
* projection are not publicly observable. A mixed text/image node is therefore
|
|
2891
|
+
* an estimate and never qualifies for an exact rewrite proof.
|
|
2892
|
+
*/
|
|
2893
|
+
function countCanonicalContent(blocks, counter, subject) {
|
|
2894
|
+
let identity;
|
|
2895
|
+
let estimateIdentity;
|
|
2896
|
+
let tokens = 0;
|
|
2897
|
+
let upperBoundTokens = 0;
|
|
2898
|
+
let firstRefusal;
|
|
2899
|
+
const absorb = (count) => {
|
|
2900
|
+
if (count.kind === "unavailable") {
|
|
2901
|
+
firstRefusal ??= count;
|
|
2902
|
+
return false;
|
|
2903
|
+
}
|
|
2904
|
+
if (count.kind === "exact-tokenizer") {
|
|
2905
|
+
if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) {
|
|
2906
|
+
firstRefusal ??= unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
|
|
2907
|
+
return false;
|
|
2908
|
+
}
|
|
2909
|
+
identity ??= count;
|
|
2910
|
+
tokens += count.tokens;
|
|
2911
|
+
upperBoundTokens += count.tokens;
|
|
2912
|
+
} else {
|
|
2913
|
+
if (estimateIdentity !== void 0 && (estimateIdentity.estimatorId !== count.estimatorId || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
|
|
2914
|
+
firstRefusal ??= unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`);
|
|
2915
|
+
return false;
|
|
2916
|
+
}
|
|
2917
|
+
estimateIdentity ??= {
|
|
2918
|
+
estimatorId: count.estimatorId,
|
|
2919
|
+
estimatorRevision: count.estimatorRevision
|
|
2920
|
+
};
|
|
2921
|
+
tokens += count.tokens;
|
|
2922
|
+
upperBoundTokens += count.upperBoundTokens;
|
|
2923
|
+
}
|
|
2924
|
+
return Number.isSafeInteger(tokens) && tokens >= 0 && Number.isSafeInteger(upperBoundTokens) && upperBoundTokens >= tokens;
|
|
2925
|
+
};
|
|
2926
|
+
const walk = (content) => {
|
|
2927
|
+
for (const block of content) switch (block.type) {
|
|
2928
|
+
case "text":
|
|
2929
|
+
case "reasoning":
|
|
2930
|
+
if (!absorb(counter.countText(block.text))) return false;
|
|
2931
|
+
break;
|
|
2932
|
+
case "tool-call":
|
|
2933
|
+
if (!absorb(counter.countText(block.name))) return false;
|
|
2934
|
+
if (!absorb(counter.countText(block.arguments))) return false;
|
|
2935
|
+
break;
|
|
2936
|
+
case "image":
|
|
2937
|
+
if (!absorb(counter.countImage(block.attachment))) return false;
|
|
2938
|
+
break;
|
|
2939
|
+
default:
|
|
2940
|
+
firstRefusal ??= unavailableTokenCount(`${subject}: contains an unsupported content block`);
|
|
2941
|
+
return false;
|
|
2942
|
+
}
|
|
2943
|
+
return true;
|
|
2944
|
+
};
|
|
2945
|
+
if (!walk(blocks)) {
|
|
2946
|
+
if (firstRefusal?.kind === "unavailable") return unavailableTokenCount(`${subject}: ${firstRefusal.reason}`);
|
|
2947
|
+
return unavailableTokenCount(`${subject}: contains content the canonical counter cannot count exactly`);
|
|
2948
|
+
}
|
|
2949
|
+
if (identity === void 0 && estimateIdentity === void 0) {
|
|
2950
|
+
const empty = counter.countText("");
|
|
2951
|
+
if (empty.kind !== "exact-tokenizer") return empty;
|
|
2952
|
+
return empty;
|
|
2953
|
+
}
|
|
2954
|
+
if (!Number.isSafeInteger(tokens) || tokens < 0) return unavailableTokenCount(`${subject}: invalid token sum`);
|
|
2955
|
+
if (estimateIdentity !== void 0) return Object.freeze({
|
|
2956
|
+
kind: "tokenizer-estimate",
|
|
2957
|
+
...estimateIdentity,
|
|
2958
|
+
tokens,
|
|
2959
|
+
upperBoundTokens
|
|
2960
|
+
});
|
|
2961
|
+
if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
|
|
2962
|
+
return Object.freeze({
|
|
2963
|
+
...identity,
|
|
2964
|
+
tokens
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
function bindCounter(provider, model) {
|
|
2968
|
+
if (provider === void 0 || model === void 0) {
|
|
2969
|
+
const unavailable = () => unavailableTokenCount("canonical text: no durable provider/model request header");
|
|
2970
|
+
return {
|
|
2971
|
+
countText: unavailable,
|
|
2972
|
+
countImage: () => unavailableTokenCount("canonical image: no durable provider/model request header")
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
if (provider !== "deepseek" && provider !== "deepseek-official") {
|
|
2976
|
+
const reason = `canonical text: provider "${provider}" is not the supported DeepSeek route`;
|
|
2977
|
+
return {
|
|
2978
|
+
countText: () => unavailableTokenCount(reason),
|
|
2979
|
+
countImage: () => unavailableTokenCount(`canonical image: provider "${provider}" is not the supported DeepSeek route`)
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
const tokenizer = deepSeekV4TokenizerForModel(model);
|
|
2983
|
+
if (tokenizer === void 0) {
|
|
2984
|
+
const reason = `canonical text: no verified bundled tokenizer for model "${model}"`;
|
|
2985
|
+
return {
|
|
2986
|
+
countText: () => unavailableTokenCount(reason),
|
|
2987
|
+
countImage: (attachment) => countCanonicalImage(model, attachment)
|
|
2988
|
+
};
|
|
2989
|
+
}
|
|
2990
|
+
return {
|
|
2991
|
+
countText: (text) => tokenizer.countText(text),
|
|
2992
|
+
countImage: (attachment) => countCanonicalImage(model, attachment)
|
|
2993
|
+
};
|
|
2994
|
+
}
|
|
2995
|
+
/**
|
|
2996
|
+
* Images never claim an exact count. The official expansion depends on the
|
|
2997
|
+
* absolute prompt position (system prompt, chat-template framing, adapter
|
|
2998
|
+
* image handles) and on the adapter's final request-image projection, neither
|
|
2999
|
+
* of which is exposed through a public API; a route may even override the
|
|
3000
|
+
* pixel budget or re-project under the byte cap. Valid dimensions therefore
|
|
3001
|
+
* use the midpoint of the four alignment residues as a bounded estimate;
|
|
3002
|
+
* malformed dimensions use a fixed default. Estimate-bearing nodes remain
|
|
3003
|
+
* ineligible for exact rewrite proofs.
|
|
3004
|
+
*/
|
|
3005
|
+
function countCanonicalImage(model, attachment) {
|
|
3006
|
+
if (model !== VISION_MODEL_ID) return unavailableTokenCount(`canonical image: model "${model}" has no vision image counter`);
|
|
3007
|
+
const estimate = estimateDeepSeekVisionImageTokens(attachment.width, attachment.height);
|
|
3008
|
+
return Object.freeze({
|
|
3009
|
+
kind: "tokenizer-estimate",
|
|
3010
|
+
tokens: estimate.tokens,
|
|
3011
|
+
upperBoundTokens: estimate.upperBoundTokens,
|
|
3012
|
+
estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
|
|
3013
|
+
estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision
|
|
3014
|
+
});
|
|
3015
|
+
}
|
|
3016
|
+
/**
|
|
3017
|
+
* Intrinsic-grid diagnostic for one content walk: the official block
|
|
3018
|
+
* arithmetic on intrinsic dimensions at both alignment extremes. Only images
|
|
3019
|
+
* on the pinned DeepSeek vision route with usable metadata contribute.
|
|
3020
|
+
*/
|
|
3021
|
+
function intrinsicImageDiagnostic(blocks, target) {
|
|
3022
|
+
if (target === void 0 || target.provider !== "deepseek" && target.provider !== "deepseek-official" || target.model !== VISION_MODEL_ID) return void 0;
|
|
3023
|
+
let paddingMinimumTokens = 0;
|
|
3024
|
+
let paddingMaximumTokens = 0;
|
|
3025
|
+
let seen = false;
|
|
3026
|
+
const walk = (content) => {
|
|
3027
|
+
for (const block of content) if (block.type === "image") {
|
|
3028
|
+
const { width, height } = block.attachment;
|
|
3029
|
+
const estimate = estimateDeepSeekVisionImageTokens(width, height);
|
|
3030
|
+
if (estimate.source !== "intrinsic-grid" || estimate.paddingMinimumTokens === void 0 || estimate.paddingMaximumTokens === void 0) continue;
|
|
3031
|
+
paddingMinimumTokens += estimate.paddingMinimumTokens;
|
|
3032
|
+
paddingMaximumTokens += estimate.paddingMaximumTokens;
|
|
3033
|
+
seen = true;
|
|
3034
|
+
}
|
|
3035
|
+
};
|
|
3036
|
+
walk(blocks);
|
|
3037
|
+
return seen ? Object.freeze({
|
|
3038
|
+
paddingMinimumTokens,
|
|
3039
|
+
paddingMaximumTokens
|
|
3040
|
+
}) : void 0;
|
|
3041
|
+
}
|
|
3042
|
+
function countSurfaceCounts(counts, subject) {
|
|
3043
|
+
if (counts.length === 0) return unavailableTokenCount(`${subject}: no surface nodes`);
|
|
3044
|
+
let identity;
|
|
3045
|
+
let estimateIdentity;
|
|
3046
|
+
let tokens = 0;
|
|
3047
|
+
let upperBoundTokens = 0;
|
|
3048
|
+
for (const count of counts) {
|
|
3049
|
+
if (count.kind === "unavailable") return unavailableTokenCount(`${subject}: ${count.reason}`);
|
|
3050
|
+
if (count.kind === "exact-tokenizer") {
|
|
3051
|
+
if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
|
|
3052
|
+
identity ??= count;
|
|
3053
|
+
tokens += count.tokens;
|
|
3054
|
+
upperBoundTokens += count.tokens;
|
|
3055
|
+
} else {
|
|
3056
|
+
if (estimateIdentity !== void 0 && (estimateIdentity.estimatorId !== count.estimatorId || estimateIdentity.estimatorRevision !== count.estimatorRevision)) return unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`);
|
|
3057
|
+
estimateIdentity ??= {
|
|
3058
|
+
estimatorId: count.estimatorId,
|
|
3059
|
+
estimatorRevision: count.estimatorRevision
|
|
3060
|
+
};
|
|
3061
|
+
tokens += count.tokens;
|
|
3062
|
+
upperBoundTokens += count.upperBoundTokens;
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isSafeInteger(upperBoundTokens) || upperBoundTokens < tokens) return unavailableTokenCount(`${subject}: invalid token sum`);
|
|
3066
|
+
if (estimateIdentity !== void 0) return Object.freeze({
|
|
3067
|
+
kind: "tokenizer-estimate",
|
|
3068
|
+
...estimateIdentity,
|
|
3069
|
+
tokens,
|
|
3070
|
+
upperBoundTokens
|
|
3071
|
+
});
|
|
3072
|
+
if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
|
|
3073
|
+
return Object.freeze({
|
|
3074
|
+
...identity,
|
|
3075
|
+
tokens
|
|
3076
|
+
});
|
|
3077
|
+
}
|
|
3078
|
+
//#endregion
|
|
3079
|
+
//#region src/runtime/tokenpilot/dedup.ts
|
|
3080
|
+
/**
|
|
3081
|
+
* TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
|
|
3082
|
+
*
|
|
3083
|
+
* Pure helpers behind the ToolResultPruner fresh pass. The per-session table
|
|
3084
|
+
* maps a canonical-content SHA-256 to the first surface seq that produced it;
|
|
3085
|
+
* later identical results may be replaced with a pointer placeholder that the
|
|
3086
|
+
* recovery tool can resolve back to the original full text via the append-only
|
|
3087
|
+
* session log. Only hash+seq metadata is stored — never content.
|
|
3088
|
+
*/
|
|
3089
|
+
/** Per-session dedup index with insertion-order eviction. */
|
|
3090
|
+
var DedupeTable = class {
|
|
3091
|
+
maxEntries;
|
|
3092
|
+
entries = /* @__PURE__ */ new Map();
|
|
3093
|
+
constructor(maxEntries = 2048) {
|
|
3094
|
+
this.maxEntries = maxEntries;
|
|
3095
|
+
}
|
|
3096
|
+
/** Look up the first occurrence for one canonical hash, if any. */
|
|
3097
|
+
get(hash) {
|
|
3098
|
+
return this.entries.get(hash);
|
|
3099
|
+
}
|
|
3100
|
+
/** Record a first occurrence; existing hashes only refresh insertion order. */
|
|
3101
|
+
record(hash, entry) {
|
|
3102
|
+
if (this.entries.has(hash)) return;
|
|
3103
|
+
while (this.entries.size >= this.maxEntries) {
|
|
3104
|
+
const oldest = this.entries.keys().next().value;
|
|
3105
|
+
if (oldest === void 0) break;
|
|
3106
|
+
this.entries.delete(oldest);
|
|
3107
|
+
}
|
|
3108
|
+
this.entries.set(hash, entry);
|
|
3109
|
+
}
|
|
3110
|
+
};
|
|
3111
|
+
/** Canonicalize tool-result text for hashing. */
|
|
3112
|
+
function canonicalizeForDedupe(text, mode) {
|
|
3113
|
+
if (mode === "exact") return text;
|
|
3114
|
+
return text.replace(/[ \t]+\r?\n/g, "\n").replace(/(^\s+)|(\s+$)/g, "");
|
|
3115
|
+
}
|
|
3116
|
+
/** SHA-256 hex of the canonicalized text. */
|
|
3117
|
+
function dedupeHash(text, mode) {
|
|
3118
|
+
return createHash("sha256").update(canonicalizeForDedupe(text, mode), "utf8").digest("hex");
|
|
3119
|
+
}
|
|
3120
|
+
/** Concatenated text of an all-text content block list; null when rich. */
|
|
3121
|
+
function flattenPlainText(content) {
|
|
3122
|
+
let text = "";
|
|
3123
|
+
for (const block of content) {
|
|
3124
|
+
if (block.type !== "text") return void 0;
|
|
3125
|
+
text += block.text;
|
|
3126
|
+
}
|
|
3127
|
+
return text;
|
|
3128
|
+
}
|
|
3129
|
+
/** Pointer placeholder pointing at the first occurrence's original event. */
|
|
3130
|
+
function dedupePlaceholder(entry, originalChars) {
|
|
3131
|
+
return [
|
|
3132
|
+
`[... identical to the earlier ${entry.toolName} result; first seen at ${entry.sourceRef};`,
|
|
3133
|
+
`original_chars=${String(originalChars)};`,
|
|
3134
|
+
"retrieve with context_compression_retrieve({\"ref\":\"" + entry.sourceRef + "\",\"start_line\":1}) if the omitted evidence is necessary.]"
|
|
3135
|
+
].join(" ");
|
|
3136
|
+
}
|
|
3137
|
+
//#endregion
|
|
3138
|
+
//#region src/runtime/savings-projection.ts
|
|
3139
|
+
const EMPTY = Object.freeze({
|
|
3140
|
+
savings: [],
|
|
3141
|
+
offsets: [],
|
|
3142
|
+
registry: []
|
|
3143
|
+
});
|
|
3144
|
+
function blocksOf(event) {
|
|
3145
|
+
if (event.type !== "tool/result") return void 0;
|
|
3146
|
+
return viewToolResult(event.data.message).blocks;
|
|
3147
|
+
}
|
|
3148
|
+
function textOf(event) {
|
|
3149
|
+
const blocks = blocksOf(event);
|
|
3150
|
+
return blocks === void 0 ? void 0 : flattenPlainText(blocks);
|
|
3151
|
+
}
|
|
3152
|
+
/** 与 pruner 的 `plan()` 同口径定价:全文本块可精确,否则字符口径。 */
|
|
3153
|
+
function priceEvent(event, countText) {
|
|
3154
|
+
const blocks = blocksOf(event);
|
|
3155
|
+
if (blocks === void 0) return void 0;
|
|
3156
|
+
const chars = pressureCost(blocks);
|
|
3157
|
+
if (chars <= 0) return void 0;
|
|
3158
|
+
const texts = blocks.map((block) => block.type === "text" ? block.text : void 0);
|
|
3159
|
+
if (texts.every((text) => text !== void 0)) {
|
|
3160
|
+
const count = countExactCanonicalTextFields(texts, countText, "savings projection");
|
|
3161
|
+
if (count.kind === "exact-tokenizer") return {
|
|
3162
|
+
tokens: count.tokens,
|
|
3163
|
+
basis: "exact-tokenizer",
|
|
3164
|
+
chars
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
return {
|
|
3168
|
+
tokens: Math.max(1, charsToTokens(chars)),
|
|
3169
|
+
basis: "characters",
|
|
3170
|
+
chars
|
|
3171
|
+
};
|
|
3172
|
+
}
|
|
3173
|
+
/** 替换事件的被替换 span;非替换节点(或畸形 op)返回 undefined。 */
|
|
3174
|
+
function replacedSpan(event) {
|
|
3175
|
+
const op = event.surfaceOp;
|
|
3176
|
+
if (typeof op !== "object" || op === null || op.op !== "replace") return void 0;
|
|
3177
|
+
const start = Number(op.startSeq);
|
|
3178
|
+
const end = Number(op.endSeq);
|
|
3179
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return void 0;
|
|
3180
|
+
return {
|
|
3181
|
+
start,
|
|
3182
|
+
end
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
function originalText(bySeq, span) {
|
|
3186
|
+
const parts = [];
|
|
3187
|
+
for (let seq = span.start; seq <= span.end; seq++) {
|
|
3188
|
+
const event = bySeq.get(seq);
|
|
3189
|
+
const text = event === void 0 ? void 0 : textOf(event);
|
|
3190
|
+
if (text !== void 0 && text.length > 0) parts.push(text);
|
|
3191
|
+
}
|
|
3192
|
+
return parts.join("\n");
|
|
3193
|
+
}
|
|
3194
|
+
/**
|
|
3195
|
+
* 一个替换节点"压掉了多少"(与实时 `plan()` 同口径:差额>0 才算)。
|
|
3196
|
+
* 原始价 = span 内原始事件之和;替换价 = 替换事件。
|
|
3197
|
+
*/
|
|
3198
|
+
function computeDelta(bySeq, replacement, span, counter) {
|
|
3199
|
+
const after = priceEvent(replacement, counter);
|
|
3200
|
+
if (after === void 0) return void 0;
|
|
3201
|
+
let beforeChars = 0;
|
|
3202
|
+
let beforeExactTokens = 0;
|
|
3203
|
+
let beforeExact = true;
|
|
3204
|
+
let any = false;
|
|
3205
|
+
for (let seq = span.start; seq <= span.end; seq++) {
|
|
3206
|
+
const original = bySeq.get(seq);
|
|
3207
|
+
const priced = original === void 0 ? void 0 : priceEvent(original, counter);
|
|
3208
|
+
if (priced === void 0) continue;
|
|
3209
|
+
any = true;
|
|
3210
|
+
beforeChars += priced.chars;
|
|
3211
|
+
beforeExactTokens += priced.tokens;
|
|
3212
|
+
if (priced.basis !== "exact-tokenizer") beforeExact = false;
|
|
3213
|
+
}
|
|
3214
|
+
if (!any) return void 0;
|
|
3215
|
+
const exact = after.basis === "exact-tokenizer" && beforeExact;
|
|
3216
|
+
const basis = exact ? "exact-tokenizer" : "characters";
|
|
3217
|
+
const delta = (exact ? beforeExactTokens : charsToTokens(beforeChars)) - (exact ? after.tokens : charsToTokens(after.chars));
|
|
3218
|
+
if (delta <= 0) return void 0;
|
|
3219
|
+
return {
|
|
3220
|
+
tokens: delta,
|
|
3221
|
+
basis
|
|
3222
|
+
};
|
|
3223
|
+
}
|
|
3224
|
+
/**
|
|
3225
|
+
* 纯核心:给定事件流、当前 surface 节点与计价计数器,重算节省投影。
|
|
3226
|
+
* @param input - events/surfaceNodes/counter,均为实时路径的只读快照。
|
|
3227
|
+
* @returns savings(当前生效毛节省)/ offsets(每次重读惩罚)/ registry(原文配对键)。
|
|
3228
|
+
*/
|
|
3229
|
+
function projectSavingsCore(input) {
|
|
3230
|
+
const { events, surfaceNodes, counter } = input;
|
|
3231
|
+
if (events.length === 0) return EMPTY;
|
|
3232
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
3233
|
+
for (const event of events) bySeq.set(Number(event.seq), event);
|
|
3234
|
+
const savings = [];
|
|
3235
|
+
for (const rawSeq of surfaceNodes) {
|
|
3236
|
+
const seq = Number(rawSeq);
|
|
3237
|
+
const replacement = bySeq.get(seq);
|
|
3238
|
+
if (replacement === void 0) continue;
|
|
3239
|
+
const span = replacedSpan(replacement);
|
|
3240
|
+
if (span === void 0) continue;
|
|
3241
|
+
const delta = computeDelta(bySeq, replacement, span, counter);
|
|
3242
|
+
if (delta === void 0) continue;
|
|
3243
|
+
savings.push({
|
|
3244
|
+
component: "projection",
|
|
3245
|
+
tokens: delta.tokens,
|
|
3246
|
+
basis: delta.basis,
|
|
3247
|
+
at: Number(replacement.time) || 0,
|
|
3248
|
+
replacementSeq: seq
|
|
3249
|
+
});
|
|
3250
|
+
}
|
|
3251
|
+
const offsets = [];
|
|
3252
|
+
const registry = [];
|
|
3253
|
+
const owned = /* @__PURE__ */ new Map();
|
|
3254
|
+
for (const event of events) {
|
|
3255
|
+
if (event.type !== "tool/result") continue;
|
|
3256
|
+
const span = replacedSpan(event);
|
|
3257
|
+
if (span !== void 0) {
|
|
3258
|
+
const groupText = originalText(bySeq, span);
|
|
3259
|
+
if (groupText.length === 0) continue;
|
|
3260
|
+
const delta = computeDelta(bySeq, event, span, counter);
|
|
3261
|
+
if (delta === void 0) continue;
|
|
3262
|
+
const hash = savingsHash(groupText);
|
|
3263
|
+
owned.set(hash, {
|
|
3264
|
+
claimedTokens: delta.tokens,
|
|
3265
|
+
basis: delta.basis,
|
|
3266
|
+
sourceSeq: span.start
|
|
3267
|
+
});
|
|
3268
|
+
registry.push({
|
|
3269
|
+
hash,
|
|
3270
|
+
claimedTokens: delta.tokens,
|
|
3271
|
+
basis: delta.basis,
|
|
3272
|
+
sourceSeq: span.start
|
|
3273
|
+
});
|
|
3274
|
+
continue;
|
|
3275
|
+
}
|
|
3276
|
+
const text = textOf(event);
|
|
3277
|
+
if (text === void 0 || text.length === 0) continue;
|
|
3278
|
+
const hit = owned.get(savingsHash(text));
|
|
3279
|
+
if (hit === void 0) continue;
|
|
3280
|
+
const priced = priceEvent(event, counter);
|
|
3281
|
+
if (priced === void 0) continue;
|
|
3282
|
+
offsets.push({
|
|
3283
|
+
component: "full-read",
|
|
3284
|
+
tokens: priced.tokens,
|
|
3285
|
+
basis: priced.basis,
|
|
3286
|
+
at: Number(event.time) || 0,
|
|
3287
|
+
seq: Number(event.seq),
|
|
3288
|
+
note: `#${hit.sourceSeq} 的原文被全文重读(投影重建)`
|
|
3289
|
+
});
|
|
3290
|
+
}
|
|
3291
|
+
return {
|
|
3292
|
+
savings,
|
|
3293
|
+
offsets,
|
|
3294
|
+
registry
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
/**
|
|
3298
|
+
* 从会话快照投影节省账。`measureForCompaction` 提供与实时同口径的 tokenizer
|
|
3299
|
+
* 计数器;失败时向上抛,由调用方 fail-open。
|
|
3300
|
+
*/
|
|
3301
|
+
function projectSessionSavings(ctx, session) {
|
|
3302
|
+
const view = measureForCompaction(ctx, session);
|
|
3303
|
+
return projectSavingsCore({
|
|
3304
|
+
events: sessionEvents(session),
|
|
3305
|
+
surfaceNodes: session.surface.nodes,
|
|
3306
|
+
counter: (candidate) => view.countCanonicalText(candidate)
|
|
3307
|
+
});
|
|
3308
|
+
}
|
|
3309
|
+
/** 标记本插件统计库所有权的 application id(ASCII "CCIS")。 */
|
|
3310
|
+
const CCI_STATS_APPLICATION_ID = 1128483155;
|
|
3311
|
+
/** 统计库相对 DSH home 的路径段;刻意避开 sessions 目录(steward purge 会连带真删)。 */
|
|
3312
|
+
const STATS_DB_PATH_SEGMENTS = [
|
|
3313
|
+
"storages",
|
|
3314
|
+
"dsh-context-compression",
|
|
3315
|
+
"stats.sqlite"
|
|
3316
|
+
];
|
|
3317
|
+
const STATS_CLAIM_KINDS = [
|
|
3318
|
+
"saving",
|
|
3319
|
+
"offset",
|
|
3320
|
+
"usage",
|
|
3321
|
+
"sample"
|
|
3322
|
+
];
|
|
3323
|
+
/** 解析 DSH home:显式 dshHome > $DSH_HOME > `~/.dsh`(宿主同名优先级)。 */
|
|
3324
|
+
function resolveStatsDshHome(options = {}) {
|
|
3325
|
+
if (typeof options.dshHome === "string" && options.dshHome.trim() !== "") return options.dshHome;
|
|
3326
|
+
const fromEnv = (options.env ?? process.env)["DSH_HOME"];
|
|
3327
|
+
if (typeof fromEnv === "string" && fromEnv.trim() !== "") return fromEnv;
|
|
3328
|
+
return join(homedir(), ".dsh");
|
|
3329
|
+
}
|
|
3330
|
+
/**
|
|
3331
|
+
* 统计库绝对路径:`<dshHome>/storages/dsh-context-compression/stats.sqlite`
|
|
3332
|
+
* + homedir 兜底。返回值总是绝对路径形态的各段拼接。
|
|
3333
|
+
*/
|
|
3334
|
+
function resolveStatsDbPath(options = {}) {
|
|
3335
|
+
if (typeof options.dbPath === "string" && options.dbPath.trim() !== "") return options.dbPath;
|
|
3336
|
+
return join(resolveStatsDshHome(options), ...STATS_DB_PATH_SEGMENTS);
|
|
3337
|
+
}
|
|
3338
|
+
/**
|
|
3339
|
+
* 建表(幂等)并把 application_id/user_version 盖章到当前版本。
|
|
3340
|
+
* 二次打开同一文件时 CREATE IF NOT EXISTS 全部空转,数据原样保留。
|
|
3341
|
+
*/
|
|
3342
|
+
function ensureStatsSchema(db) {
|
|
3343
|
+
db.exec(`
|
|
3344
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
3345
|
+
key TEXT PRIMARY KEY,
|
|
3346
|
+
value TEXT NOT NULL
|
|
3347
|
+
);
|
|
3348
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
3349
|
+
session_id TEXT PRIMARY KEY,
|
|
3350
|
+
project TEXT NOT NULL DEFAULT '',
|
|
3351
|
+
version INTEGER NOT NULL DEFAULT 0,
|
|
3352
|
+
updated_at INTEGER NOT NULL DEFAULT 0,
|
|
3353
|
+
source TEXT NOT NULL DEFAULT 'live'
|
|
3354
|
+
);
|
|
3355
|
+
CREATE TABLE IF NOT EXISTS claims (
|
|
3356
|
+
session_id TEXT NOT NULL,
|
|
3357
|
+
seq INTEGER NOT NULL,
|
|
3358
|
+
kind TEXT NOT NULL,
|
|
3359
|
+
component TEXT NOT NULL DEFAULT '',
|
|
3360
|
+
basis TEXT NOT NULL DEFAULT '',
|
|
3361
|
+
tokens INTEGER NOT NULL,
|
|
3362
|
+
at INTEGER NOT NULL,
|
|
3363
|
+
PRIMARY KEY (session_id, seq, kind, component, basis)
|
|
3364
|
+
);
|
|
3365
|
+
CREATE INDEX IF NOT EXISTS claims_session_kind ON claims(session_id, kind);
|
|
3366
|
+
`);
|
|
3367
|
+
db.exec(`PRAGMA application_id = ${CCI_STATS_APPLICATION_ID}`);
|
|
3368
|
+
db.exec(`PRAGMA user_version = 1`);
|
|
3369
|
+
}
|
|
3370
|
+
/**
|
|
3371
|
+
* 版本不符时的就地重置:删掉全部自建表(含索引随表消失)、清 user_version,
|
|
3372
|
+
* 保留文件本身;application_id 由随后的 ensureStatsSchema 重新盖章。
|
|
3373
|
+
* 数据丢失是可接受语义——claims 全部可从宿主事件日志幂等重放。
|
|
3374
|
+
*/
|
|
3375
|
+
function resetStatsSchema(db) {
|
|
3376
|
+
for (const row of db.prepare(`
|
|
3377
|
+
SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
|
|
3378
|
+
`).all()) db.exec(`DROP TABLE IF EXISTS "${row.name.replace(/"/g, "\"\"")}"`);
|
|
3379
|
+
db.exec(`PRAGMA user_version = 0`);
|
|
3380
|
+
}
|
|
3381
|
+
//#endregion
|
|
3382
|
+
//#region src/runtime/stats-db.ts
|
|
3383
|
+
/**
|
|
3384
|
+
* 驱动探测顺序打开裸句柄。非字面量 specifier 让 optional 原生依赖缺席时
|
|
3385
|
+
* typecheck/build 全绿(tsdown neverBundle 也不会把它打进产物);
|
|
3386
|
+
* `node:sqlite` 带前缀,verify-release 依赖闸对其零成本跳过。
|
|
3387
|
+
*/
|
|
3388
|
+
async function openRawHandle(actual) {
|
|
3389
|
+
try {
|
|
3390
|
+
const mod = await import("better-sqlite3");
|
|
3391
|
+
return {
|
|
3392
|
+
db: new (mod.default ?? mod)(actual),
|
|
3393
|
+
driver: "better-sqlite3"
|
|
3394
|
+
};
|
|
3395
|
+
} catch {
|
|
3396
|
+
try {
|
|
3397
|
+
const { DatabaseSync: NodeDatabaseSync } = await import("node:sqlite");
|
|
3398
|
+
return {
|
|
3399
|
+
db: new NodeDatabaseSync(actual),
|
|
3400
|
+
driver: "node:sqlite"
|
|
3401
|
+
};
|
|
3402
|
+
} catch {
|
|
3403
|
+
return null;
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
/**
|
|
3408
|
+
* 打开(必要时创建并初始化)统计库文件。缺目录建目录;他人库抛错拒开;
|
|
3409
|
+
* 自家库版本不符先 drop 重建。返回 null 表示无可用驱动(降级,非错误)。
|
|
3410
|
+
*/
|
|
3411
|
+
async function openStatsDatabase(path) {
|
|
3412
|
+
const actual = resolve(path);
|
|
3413
|
+
await mkdir(dirname(actual), { recursive: true });
|
|
3414
|
+
const opened = await openRawHandle(actual);
|
|
3415
|
+
if (opened === null) return null;
|
|
3416
|
+
const { db } = opened;
|
|
3417
|
+
try {
|
|
3418
|
+
const { application_id: applicationId } = db.prepare("PRAGMA application_id").get();
|
|
3419
|
+
const { user_version: version } = db.prepare("PRAGMA user_version").get();
|
|
3420
|
+
if (applicationId === 1146308689) throw new Error(`stats-db: "${actual}" is the official session-query index, refusing to open it`);
|
|
3421
|
+
if (applicationId === 1398229332) throw new Error(`stats-db: "${actual}" belongs to switch-search, refusing to open it`);
|
|
3422
|
+
if (applicationId !== 0 && applicationId !== 1128483155) throw new Error(`stats-db: database at "${actual}" belongs to another application (id 0x${applicationId.toString(16)})`);
|
|
3423
|
+
if (applicationId === 1128483155 && version !== 1) resetStatsSchema(db);
|
|
3424
|
+
db.exec(`PRAGMA journal_mode = wal`);
|
|
3425
|
+
ensureStatsSchema(db);
|
|
3426
|
+
db.exec(`PRAGMA synchronous = NORMAL`);
|
|
3427
|
+
db.exec(`PRAGMA busy_timeout = 5000`);
|
|
3428
|
+
db.exec(`PRAGMA temp_store = MEMORY`);
|
|
3429
|
+
return opened;
|
|
3430
|
+
} catch (error) {
|
|
3431
|
+
db.close();
|
|
3432
|
+
throw error;
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3435
|
+
/**
|
|
3436
|
+
* 一个打开的统计库句柄的读写面。写路径同步小事务(随写随刷,BEGIN
|
|
3437
|
+
* IMMEDIATE),读路径无锁(WAL 允许读并发)。句柄关闭后调用即抛——生命周期
|
|
3438
|
+
* 由 ensureStatsStore/closeStatsStore 统一管,调用方不持有裸 db。
|
|
3439
|
+
*/
|
|
3440
|
+
var StatsStore = class {
|
|
3441
|
+
driver;
|
|
3442
|
+
db;
|
|
3443
|
+
inWriteTx = false;
|
|
3444
|
+
constructor(db, driver) {
|
|
3445
|
+
this.driver = driver;
|
|
3446
|
+
this.db = db;
|
|
3447
|
+
}
|
|
3448
|
+
get isOpen() {
|
|
3449
|
+
return this.db !== void 0;
|
|
3450
|
+
}
|
|
3451
|
+
close() {
|
|
3452
|
+
this.db?.close();
|
|
3453
|
+
this.db = void 0;
|
|
3454
|
+
}
|
|
3455
|
+
requireDb() {
|
|
3456
|
+
if (this.db === void 0) throw new Error("stats-db: handle closed");
|
|
3457
|
+
return this.db;
|
|
3458
|
+
}
|
|
3459
|
+
/**
|
|
3460
|
+
* 外层已开写事务时直接并入(嵌套 join),否则自开一个 BEGIN IMMEDIATE
|
|
3461
|
+
* 小事务并提交;异常一律 ROLLBACK 后原样上抛。
|
|
3462
|
+
*/
|
|
3463
|
+
withWriteTx(fn) {
|
|
3464
|
+
const db = this.requireDb();
|
|
3465
|
+
if (this.inWriteTx) return fn();
|
|
3466
|
+
db.exec("BEGIN IMMEDIATE");
|
|
3467
|
+
this.inWriteTx = true;
|
|
3468
|
+
try {
|
|
3469
|
+
const result = fn();
|
|
3470
|
+
db.exec("COMMIT");
|
|
3471
|
+
return result;
|
|
3472
|
+
} catch (error) {
|
|
3473
|
+
try {
|
|
3474
|
+
db.exec("ROLLBACK");
|
|
3475
|
+
} catch {}
|
|
3476
|
+
throw error;
|
|
3477
|
+
} finally {
|
|
3478
|
+
this.inWriteTx = false;
|
|
3479
|
+
}
|
|
3480
|
+
}
|
|
3481
|
+
/**
|
|
3482
|
+
* claims 批量幂等落库:BEGIN IMMEDIATE + INSERT OR IGNORE,返回**实际新增**
|
|
3483
|
+
* 行数(重放 = 0)。非有限数/未知 kind 的行拒收(抛错=编程错误,静默跳行
|
|
3484
|
+
* =对账黑洞,取前者)。
|
|
3485
|
+
*/
|
|
3486
|
+
recordClaims(sessionId, rows) {
|
|
3487
|
+
if (rows.length === 0) return 0;
|
|
3488
|
+
const db = this.requireDb();
|
|
3489
|
+
const sid = String(sessionId);
|
|
3490
|
+
for (const row of rows) {
|
|
3491
|
+
if (!STATS_CLAIM_KINDS.includes(row.kind)) throw new Error(`stats-db: unsupported claim kind "${String(row.kind)}"`);
|
|
3492
|
+
if (!Number.isFinite(row.seq) || !Number.isFinite(row.tokens) || !Number.isFinite(row.at)) throw new Error(`stats-db: claim row for session "${sid}" carries non-finite seq/tokens/at`);
|
|
3493
|
+
}
|
|
3494
|
+
const insert = db.prepare(`INSERT OR IGNORE INTO claims (session_id, seq, kind, component, basis, tokens, at) VALUES (?, ?, ?, ?, ?, ?, ?)`);
|
|
3495
|
+
return this.withWriteTx(() => {
|
|
3496
|
+
let added = 0;
|
|
3497
|
+
for (const row of rows) {
|
|
3498
|
+
const result = insert.run(sid, Math.trunc(row.seq), row.kind, row.component, row.basis, Math.trunc(row.tokens), Math.trunc(row.at));
|
|
3499
|
+
added += Number(result.changes);
|
|
3500
|
+
}
|
|
3501
|
+
return added;
|
|
3502
|
+
});
|
|
3503
|
+
}
|
|
3504
|
+
/**
|
|
3505
|
+
* 按会话聚合 saving/offset 双 basis 合计,净额精确口径降序(内存账本
|
|
3506
|
+
* snapshot.perSession 的持久层对应物;分页在 T24 路由层做)。
|
|
3507
|
+
*/
|
|
3508
|
+
perSessionAggregates() {
|
|
3509
|
+
const rows = this.requireDb().prepare(`
|
|
3510
|
+
SELECT session_id AS sessionId, kind, basis, SUM(tokens) AS tokens
|
|
3511
|
+
FROM claims WHERE kind IN ('saving', 'offset')
|
|
3512
|
+
GROUP BY session_id, kind, basis
|
|
3513
|
+
`).all();
|
|
3514
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
3515
|
+
for (const row of rows) {
|
|
3516
|
+
let agg = bySession.get(row.sessionId);
|
|
3517
|
+
if (agg === void 0) {
|
|
3518
|
+
agg = {
|
|
3519
|
+
sessionId: row.sessionId,
|
|
3520
|
+
gross: {
|
|
3521
|
+
exact: 0,
|
|
3522
|
+
estimated: 0
|
|
3523
|
+
},
|
|
3524
|
+
offsets: {
|
|
3525
|
+
exact: 0,
|
|
3526
|
+
estimated: 0
|
|
3527
|
+
},
|
|
3528
|
+
net: {
|
|
3529
|
+
exact: 0,
|
|
3530
|
+
estimated: 0
|
|
3531
|
+
}
|
|
3532
|
+
};
|
|
3533
|
+
bySession.set(row.sessionId, agg);
|
|
3534
|
+
}
|
|
3535
|
+
const column = row.basis === "exact-tokenizer" ? "exact" : "estimated";
|
|
3536
|
+
const bucket = row.kind === "saving" ? agg.gross : agg.offsets;
|
|
3537
|
+
bucket[column] += Number(row.tokens);
|
|
3538
|
+
}
|
|
3539
|
+
const list = [...bySession.values()];
|
|
3540
|
+
for (const agg of list) {
|
|
3541
|
+
agg.net.exact = agg.gross.exact - agg.offsets.exact;
|
|
3542
|
+
agg.net.estimated = agg.gross.estimated - agg.offsets.estimated;
|
|
3543
|
+
}
|
|
3544
|
+
return list.sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated);
|
|
3545
|
+
}
|
|
3546
|
+
/** 全会话聚合(不带 perSession 列表的 total)。 */
|
|
3547
|
+
total() {
|
|
3548
|
+
const rows = this.requireDb().prepare(`
|
|
3549
|
+
SELECT kind, basis, SUM(tokens) AS tokens
|
|
3550
|
+
FROM claims WHERE kind IN ('saving', 'offset')
|
|
3551
|
+
GROUP BY kind, basis
|
|
3552
|
+
`).all();
|
|
3553
|
+
const gross = {
|
|
3554
|
+
exact: 0,
|
|
3555
|
+
estimated: 0
|
|
3556
|
+
};
|
|
3557
|
+
const offsets = {
|
|
3558
|
+
exact: 0,
|
|
3559
|
+
estimated: 0
|
|
3560
|
+
};
|
|
3561
|
+
for (const row of rows) {
|
|
3562
|
+
const column = row.basis === "exact-tokenizer" ? "exact" : "estimated";
|
|
3563
|
+
const bucket = row.kind === "saving" ? gross : offsets;
|
|
3564
|
+
bucket[column] += Number(row.tokens);
|
|
3565
|
+
}
|
|
3566
|
+
return {
|
|
3567
|
+
gross,
|
|
3568
|
+
offsets,
|
|
3569
|
+
net: {
|
|
3570
|
+
exact: gross.exact - offsets.exact,
|
|
3571
|
+
estimated: gross.estimated - offsets.estimated
|
|
3572
|
+
}
|
|
3573
|
+
};
|
|
3574
|
+
}
|
|
3575
|
+
/**
|
|
3576
|
+
* 累计积分查询:Σ samples(按 call 边界采样的存量净快照)。calls = 已覆盖的
|
|
3577
|
+
* distinct 边界 seq 数——面板"累计(按 N 次 call)"的 N。
|
|
3578
|
+
*/
|
|
3579
|
+
sumSamples(sessionId) {
|
|
3580
|
+
const db = this.requireDb();
|
|
3581
|
+
const sid = String(sessionId);
|
|
3582
|
+
const sums = db.prepare(`SELECT component, SUM(tokens) AS tokens FROM claims WHERE session_id = ? AND kind = 'sample' GROUP BY component`).all(sid);
|
|
3583
|
+
const { calls } = db.prepare(`SELECT COUNT(DISTINCT seq) AS calls FROM claims WHERE session_id = ? AND kind = 'sample'`).get(sid);
|
|
3584
|
+
const totals = {
|
|
3585
|
+
netExact: 0,
|
|
3586
|
+
netEstimated: 0,
|
|
3587
|
+
cachedInput: 0,
|
|
3588
|
+
uncachedInput: 0,
|
|
3589
|
+
calls: Number(calls)
|
|
3590
|
+
};
|
|
3591
|
+
for (const row of sums) if (row.component === "netExact") totals.netExact += Number(row.tokens);
|
|
3592
|
+
else if (row.component === "netEstimated") totals.netEstimated += Number(row.tokens);
|
|
3593
|
+
else if (row.component === "cachedInput") totals.cachedInput += Number(row.tokens);
|
|
3594
|
+
else if (row.component === "uncachedInput") totals.uncachedInput += Number(row.tokens);
|
|
3595
|
+
return totals;
|
|
3596
|
+
}
|
|
3597
|
+
/** 全会话积分累计(面板"累计"总行的数据源);calls = distinct (session, seq)。 */
|
|
3598
|
+
sumSamplesAll() {
|
|
3599
|
+
const db = this.requireDb();
|
|
3600
|
+
const sums = db.prepare(`SELECT component, SUM(tokens) AS tokens FROM claims WHERE kind = 'sample' GROUP BY component`).all();
|
|
3601
|
+
const { calls } = db.prepare(`SELECT COUNT(DISTINCT session_id || ':' || seq) AS calls FROM claims WHERE kind = 'sample'`).get();
|
|
3602
|
+
const totals = {
|
|
3603
|
+
netExact: 0,
|
|
3604
|
+
netEstimated: 0,
|
|
3605
|
+
cachedInput: 0,
|
|
3606
|
+
uncachedInput: 0,
|
|
3607
|
+
calls: Number(calls)
|
|
3608
|
+
};
|
|
3609
|
+
for (const row of sums) if (row.component === "netExact") totals.netExact += Number(row.tokens);
|
|
3610
|
+
else if (row.component === "netEstimated") totals.netEstimated += Number(row.tokens);
|
|
3611
|
+
else if (row.component === "cachedInput") totals.cachedInput += Number(row.tokens);
|
|
3612
|
+
else if (row.component === "uncachedInput") totals.uncachedInput += Number(row.tokens);
|
|
3613
|
+
return totals;
|
|
3614
|
+
}
|
|
3615
|
+
/** 「怎么省的」组成:saving claims 按压缩路径×口径聚合(可聚焦单会话);浮窗组成块数据源。 */
|
|
3616
|
+
/**
|
|
3617
|
+
* 最近有压缩活动的会话(claims.at 最大者,回填保留原始事件时间)——浮窗
|
|
3618
|
+
* 「怎么省的」的"当前会话"解析基准。sessions.updated_at 会被回填统一盖章,
|
|
3619
|
+
* 不能作活跃判据。
|
|
3620
|
+
*/
|
|
3621
|
+
latestActiveSessionId() {
|
|
3622
|
+
return this.requireDb().prepare("SELECT session_id FROM claims GROUP BY session_id ORDER BY MAX(at) DESC LIMIT 1").get()?.session_id;
|
|
3623
|
+
}
|
|
3624
|
+
sessionComponents(sessionId) {
|
|
3625
|
+
const db = this.requireDb();
|
|
3626
|
+
return (sessionId === void 0 ? db.prepare(`SELECT component, basis, SUM(tokens) AS tokens, COUNT(*) AS events
|
|
3627
|
+
FROM claims WHERE kind = 'saving' GROUP BY component, basis ORDER BY tokens DESC LIMIT 8`).all() : db.prepare(`SELECT component, basis, SUM(tokens) AS tokens, COUNT(*) AS events
|
|
3628
|
+
FROM claims WHERE kind = 'saving' AND session_id = ? GROUP BY component, basis ORDER BY tokens DESC LIMIT 8`).all(sessionId)).map((row) => ({
|
|
3629
|
+
component: row.component,
|
|
3630
|
+
basis: row.basis,
|
|
3631
|
+
tokens: Number(row.tokens),
|
|
3632
|
+
events: Number(row.events)
|
|
3633
|
+
}));
|
|
3634
|
+
}
|
|
3635
|
+
/** 会话已覆盖水位(绝对 seq);未知会话 = 0。 */
|
|
3636
|
+
getSessionWatermark(sessionId) {
|
|
3637
|
+
const row = this.requireDb().prepare(`SELECT version FROM sessions WHERE session_id = ?`).get(String(sessionId));
|
|
3638
|
+
return row === void 0 ? 0 : Number(row.version);
|
|
3639
|
+
}
|
|
3640
|
+
/**
|
|
3641
|
+
* 会话行全容(回填器用来判 source=live 护栏与水位 diff);未知会话 = undefined。
|
|
3642
|
+
*/
|
|
3643
|
+
getSessionRecord(sessionId) {
|
|
3644
|
+
const row = this.requireDb().prepare(`SELECT version, project, source, updated_at AS updatedAt FROM sessions WHERE session_id = ?`).get(String(sessionId));
|
|
3645
|
+
if (row === void 0) return void 0;
|
|
3646
|
+
return {
|
|
3647
|
+
version: Number(row.version),
|
|
3648
|
+
project: row.project,
|
|
3649
|
+
source: row.source,
|
|
3650
|
+
updatedAt: Number(row.updatedAt)
|
|
3651
|
+
};
|
|
3652
|
+
}
|
|
3653
|
+
/**
|
|
3654
|
+
* 最近活跃会话(updated_at 降序;/ccip `session latest` 与面板聚焦的解析源
|
|
3655
|
+
* ——usage 水位每秒 upsert 刷 updated_at,活跃会话自然浮到最前)。
|
|
3656
|
+
*/
|
|
3657
|
+
recentSessionIds(limit) {
|
|
3658
|
+
const db = this.requireDb();
|
|
3659
|
+
const capped = Math.max(1, Math.min(100, Math.trunc(limit)));
|
|
3660
|
+
return db.prepare(`SELECT session_id AS sessionId, updated_at AS updatedAt, source FROM sessions ORDER BY updated_at DESC, session_id ASC LIMIT ?`).all(capped).map((row) => ({
|
|
3661
|
+
sessionId: row.sessionId,
|
|
3662
|
+
updatedAt: Number(row.updatedAt),
|
|
3663
|
+
source: row.source
|
|
3664
|
+
}));
|
|
3665
|
+
}
|
|
3666
|
+
/** meta 键值读(displayPrefs 等);缺键 = undefined。 */
|
|
3667
|
+
getMeta(key) {
|
|
3668
|
+
const row = this.requireDb().prepare(`SELECT value FROM meta WHERE key = ?`).get(String(key));
|
|
3669
|
+
return row === void 0 ? void 0 : row.value;
|
|
3670
|
+
}
|
|
3671
|
+
/** meta 键值写(upsert;值必须是调用方已序列化的字符串)。 */
|
|
3672
|
+
setMeta(key, value) {
|
|
3673
|
+
const db = this.requireDb();
|
|
3674
|
+
this.withWriteTx(() => {
|
|
3675
|
+
db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value`).run(String(key), String(value));
|
|
3676
|
+
});
|
|
3677
|
+
}
|
|
3678
|
+
/**
|
|
3679
|
+
* upsert 会话水位:单调不减(重放/回填旧值不倒退现有水位);
|
|
3680
|
+
* source 一旦为 live 不被 backfill 降级。
|
|
3681
|
+
*/
|
|
3682
|
+
setSessionWatermark(sessionId, version, options = {}) {
|
|
3683
|
+
if (!Number.isFinite(version) || version < 0) throw new Error(`stats-db: watermark for session "${String(sessionId)}" must be a non-negative finite number`);
|
|
3684
|
+
const db = this.requireDb();
|
|
3685
|
+
this.withWriteTx(() => {
|
|
3686
|
+
db.prepare(`
|
|
3687
|
+
INSERT INTO sessions (session_id, project, version, updated_at, source)
|
|
3688
|
+
VALUES (?, ?, ?, ?, ?)
|
|
3689
|
+
ON CONFLICT (session_id) DO UPDATE SET
|
|
3690
|
+
version = MAX(sessions.version, excluded.version),
|
|
3691
|
+
updated_at = MAX(sessions.updated_at, excluded.updated_at),
|
|
3692
|
+
project = CASE WHEN excluded.project <> '' THEN excluded.project ELSE sessions.project END,
|
|
3693
|
+
source = CASE WHEN sessions.source = 'live' THEN 'live' ELSE excluded.source END
|
|
3694
|
+
`).run(String(sessionId), options.project ?? "", Math.trunc(version), Date.now(), options.source ?? "live");
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
3697
|
+
};
|
|
3698
|
+
let activeStore = null;
|
|
3699
|
+
let lastState = {
|
|
3700
|
+
persisted: false,
|
|
3701
|
+
reason: "not-opened",
|
|
3702
|
+
driver: null
|
|
3703
|
+
};
|
|
3704
|
+
let degradedWarned = false;
|
|
3705
|
+
function warnStatsDegradedOnce(message) {
|
|
3706
|
+
if (degradedWarned) return;
|
|
3707
|
+
degradedWarned = true;
|
|
3708
|
+
console.warn("context-compression stats persistence degraded: %s", message);
|
|
3709
|
+
}
|
|
3710
|
+
/** 当前持久化状态(同步读,不触发打开)。 */
|
|
3711
|
+
function statsPersistenceState() {
|
|
3712
|
+
return lastState;
|
|
3713
|
+
}
|
|
3714
|
+
/** 活动句柄;未开/已关 = null。 */
|
|
3715
|
+
function getStatsStore() {
|
|
3716
|
+
return activeStore;
|
|
3717
|
+
}
|
|
3718
|
+
/**
|
|
3719
|
+
* 幂等打开生命周期句柄(apply 后台 arm 与测试用):已开直接复用;无驱动 →
|
|
3720
|
+
* state no-driver + warn 恰一次;拒开/损坏 → state open-failed + warn 恰一次,
|
|
3721
|
+
* **不抛**——统计持久化故障绝不阻塞压缩主路径(dsh-compaction-guard 教训)。
|
|
3722
|
+
*/
|
|
3723
|
+
async function ensureStatsStore(dbPath) {
|
|
3724
|
+
if (activeStore !== null) return activeStore;
|
|
3725
|
+
const path = resolveStatsDbPath(dbPath === void 0 ? {} : { dbPath });
|
|
3726
|
+
try {
|
|
3727
|
+
const opened = await openStatsDatabase(path);
|
|
3728
|
+
if (opened === null) {
|
|
3729
|
+
lastState = {
|
|
3730
|
+
persisted: false,
|
|
3731
|
+
reason: "no-driver",
|
|
3732
|
+
driver: null
|
|
3733
|
+
};
|
|
3734
|
+
warnStatsDegradedOnce("no SQLite driver available (better-sqlite3 absent and node:sqlite unsupported)");
|
|
3735
|
+
return null;
|
|
3736
|
+
}
|
|
3737
|
+
activeStore = new StatsStore(opened.db, opened.driver);
|
|
3738
|
+
lastState = {
|
|
3739
|
+
persisted: true,
|
|
3740
|
+
driver: opened.driver
|
|
3741
|
+
};
|
|
3742
|
+
return activeStore;
|
|
3743
|
+
} catch (error) {
|
|
3744
|
+
const message = String(error?.message ?? error);
|
|
3745
|
+
lastState = {
|
|
3746
|
+
persisted: false,
|
|
3747
|
+
reason: "open-failed",
|
|
3748
|
+
driver: null,
|
|
3749
|
+
error: message
|
|
3750
|
+
};
|
|
3751
|
+
warnStatsDegradedOnce(`open failed: ${message}`);
|
|
3752
|
+
return null;
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
/** 幂等关闭(ctx.effect 卸载缝调用,防热重载泄 fd)。状态回落 not-opened。 */
|
|
3756
|
+
function closeStatsStore() {
|
|
3757
|
+
if (activeStore === null) return;
|
|
3758
|
+
activeStore.close();
|
|
3759
|
+
activeStore = null;
|
|
3760
|
+
lastState = {
|
|
3761
|
+
persisted: false,
|
|
3762
|
+
reason: "not-opened",
|
|
3763
|
+
driver: null
|
|
3764
|
+
};
|
|
3765
|
+
}
|
|
3766
|
+
//#endregion
|
|
3767
|
+
//#region src/runtime/stats-sync.ts
|
|
3768
|
+
/** usage 逐科目枚举:claims.component 的封闭取值(进主键,禁自由文本)。 */
|
|
3769
|
+
const USAGE_COMPONENTS = [
|
|
3770
|
+
{
|
|
3771
|
+
field: "inputTokens",
|
|
3772
|
+
component: "input"
|
|
3773
|
+
},
|
|
3774
|
+
{
|
|
3775
|
+
field: "outputTokens",
|
|
3776
|
+
component: "output"
|
|
3777
|
+
},
|
|
3778
|
+
{
|
|
3779
|
+
field: "cacheReadTokens",
|
|
3780
|
+
component: "cacheRead"
|
|
3781
|
+
},
|
|
3782
|
+
{
|
|
3783
|
+
field: "cacheWriteTokens",
|
|
3784
|
+
component: "cacheWrite"
|
|
3785
|
+
}
|
|
3786
|
+
];
|
|
3787
|
+
/** usage flush 的 debounce 窗口(秒级,spec T8)。 */
|
|
3788
|
+
const USAGE_FLUSH_DEBOUNCE_MS = 1e3;
|
|
3789
|
+
let writeFailureWarned = false;
|
|
3790
|
+
function warnWriteFailureOnce(error) {
|
|
3791
|
+
if (writeFailureWarned) return;
|
|
3792
|
+
writeFailureWarned = true;
|
|
3793
|
+
const message = String(error?.message ?? error);
|
|
3794
|
+
console.warn("context-compression stats persistence write failed (claims fall back to in-memory only): %s", message);
|
|
3795
|
+
}
|
|
3796
|
+
let livePathBusy = false;
|
|
3797
|
+
/** 标记前台压缩窗口开/关(pruner fresh 段 try/finally 驱动)。 */
|
|
3798
|
+
function setStatsLivePathBusy(busy) {
|
|
3799
|
+
livePathBusy = busy;
|
|
3800
|
+
}
|
|
3801
|
+
/** 前台压缩是否进行中(回填让路判据;查询零开销)。 */
|
|
3802
|
+
function isStatsLivePathBusy() {
|
|
3803
|
+
return livePathBusy;
|
|
3804
|
+
}
|
|
3805
|
+
let activeRuntimeSessionId;
|
|
3806
|
+
/** 请求边界处记下活跃会话(pruner/stats-sync 调用;幂等写字符串)。 */
|
|
3807
|
+
function noteStatsSessionActive(sessionId) {
|
|
3808
|
+
activeRuntimeSessionId = sessionId;
|
|
3809
|
+
}
|
|
3810
|
+
/** 当前活跃会话指针(浮窗六值的解析基准;无请求活动 = undefined)。 */
|
|
3811
|
+
function getStatsActiveSessionId() {
|
|
3812
|
+
return activeRuntimeSessionId;
|
|
3813
|
+
}
|
|
3814
|
+
/** store 在场才执行写体;缺席空转,异常一律门闩 warn,绝不上抛。 */
|
|
3815
|
+
function withStoreWrite(label, fn) {
|
|
3816
|
+
const store = getStatsStore();
|
|
3817
|
+
if (store === null) return;
|
|
3818
|
+
try {
|
|
3819
|
+
fn(store);
|
|
3820
|
+
} catch (error) {
|
|
3821
|
+
warnWriteFailureOnce(`${label}: ${String(error?.message ?? error)}`);
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
/** 单条 saving claim(land 成功点与内存账本同位同值)。 */
|
|
3825
|
+
function claimSaving(input) {
|
|
3826
|
+
if (!Number.isFinite(input.tokensRemoved) || input.tokensRemoved <= 0) return;
|
|
3827
|
+
const row = {
|
|
3828
|
+
seq: Math.trunc(input.replacementSeq),
|
|
3829
|
+
kind: "saving",
|
|
3830
|
+
component: input.component,
|
|
3831
|
+
basis: input.basis,
|
|
3832
|
+
tokens: Math.trunc(input.tokensRemoved),
|
|
3833
|
+
at: Date.now()
|
|
3834
|
+
};
|
|
3835
|
+
withStoreWrite("claim saving", (store) => {
|
|
3836
|
+
store.recordClaims(input.sessionId, [row]);
|
|
3837
|
+
});
|
|
3838
|
+
}
|
|
3839
|
+
/** 主 land(pruner land() recordSaving 同点):已落盘削减的 saving claim。 */
|
|
3840
|
+
function claimFromLand(input) {
|
|
3841
|
+
claimSaving({
|
|
3842
|
+
sessionId: input.sessionId,
|
|
3843
|
+
component: input.component,
|
|
3844
|
+
tokensRemoved: input.tokensBefore - input.tokensAfter,
|
|
3845
|
+
basis: input.basis,
|
|
3846
|
+
replacementSeq: input.replacementSeq
|
|
3847
|
+
});
|
|
3848
|
+
}
|
|
3849
|
+
/** tail-trim 组回收(同 land 纪律,component 固定 'tail-trim')。 */
|
|
3850
|
+
function reclaimFromTailTrim(input) {
|
|
3851
|
+
claimSaving({
|
|
3852
|
+
sessionId: input.sessionId,
|
|
3853
|
+
component: "tail-trim",
|
|
3854
|
+
tokensRemoved: input.tokensBefore - input.tokensAfter,
|
|
3855
|
+
basis: input.basis,
|
|
3856
|
+
replacementSeq: input.replacementSeq
|
|
3857
|
+
});
|
|
3858
|
+
}
|
|
3859
|
+
/** retrieve 回读抵消的 offset claim;seq = 被召回源事件绝对 seq(定键见头注)。 */
|
|
3860
|
+
function claimOffset(input) {
|
|
3861
|
+
if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
|
|
3862
|
+
const row = {
|
|
3863
|
+
seq: Math.trunc(input.sourceSeq),
|
|
3864
|
+
kind: "offset",
|
|
3865
|
+
component: input.component,
|
|
3866
|
+
basis: input.basis,
|
|
3867
|
+
tokens: Math.trunc(input.tokens),
|
|
3868
|
+
at: Date.now()
|
|
3869
|
+
};
|
|
3870
|
+
withStoreWrite("claim offset", (store) => {
|
|
3871
|
+
store.recordClaims(input.sessionId, [row]);
|
|
3872
|
+
});
|
|
3873
|
+
}
|
|
3874
|
+
/**
|
|
3875
|
+
* 立即扫描事件日志并把水位之后的 usage 逐科目落库;sessions.version 水位
|
|
3876
|
+
* 单调前推(source=live,即便本轮零新增也 upsert 会话行——dispose 的
|
|
3877
|
+
* "标记 source=live" 出口)。无 store 时空转。
|
|
3878
|
+
*/
|
|
3879
|
+
function flushUsage(session) {
|
|
3880
|
+
withStoreWrite("usage flush", (store) => {
|
|
3881
|
+
const sid = String(session.id);
|
|
3882
|
+
const watermark = store.getSessionWatermark(sid);
|
|
3883
|
+
const rows = [];
|
|
3884
|
+
let covered = watermark;
|
|
3885
|
+
for (const event of sessionEvents(session)) {
|
|
3886
|
+
const seq = Number(event.seq);
|
|
3887
|
+
if (!Number.isFinite(seq) || seq <= watermark) continue;
|
|
3888
|
+
if (seq > covered) covered = seq;
|
|
3889
|
+
if (event.type !== "assistant/message") continue;
|
|
3890
|
+
const usage = event.data.usage;
|
|
3891
|
+
if (usage === void 0) continue;
|
|
3892
|
+
const at = Number(event.time) || Date.now();
|
|
3893
|
+
for (const { field, component } of USAGE_COMPONENTS) {
|
|
3894
|
+
const tokens = usage[field];
|
|
3895
|
+
if (typeof tokens === "number" && Number.isFinite(tokens) && tokens > 0) rows.push({
|
|
3896
|
+
seq,
|
|
3897
|
+
kind: "usage",
|
|
3898
|
+
component,
|
|
3899
|
+
basis: "",
|
|
3900
|
+
tokens: Math.trunc(tokens),
|
|
3901
|
+
at
|
|
3902
|
+
});
|
|
3903
|
+
}
|
|
3904
|
+
}
|
|
3905
|
+
if (rows.length > 0) store.recordClaims(sid, rows);
|
|
3906
|
+
if (covered > 0) store.setSessionWatermark(sid, covered, { source: "live" });
|
|
3907
|
+
});
|
|
3908
|
+
}
|
|
3909
|
+
const pendingUsageFlushes = /* @__PURE__ */ new Map();
|
|
3910
|
+
/** 秒级 debounce 的 usage flush 入口(fresh 边界 recordUsage 同点调度)。 */
|
|
3911
|
+
function scheduleUsageFlush(session) {
|
|
3912
|
+
const sid = String(session.id);
|
|
3913
|
+
noteStatsSessionActive(sid);
|
|
3914
|
+
const existing = pendingUsageFlushes.get(sid);
|
|
3915
|
+
if (existing !== void 0) {
|
|
3916
|
+
existing.session = session;
|
|
3917
|
+
return;
|
|
3918
|
+
}
|
|
3919
|
+
const timer = setTimeout(() => {
|
|
3920
|
+
const entry = pendingUsageFlushes.get(sid);
|
|
3921
|
+
if (entry === void 0) return;
|
|
3922
|
+
pendingUsageFlushes.delete(sid);
|
|
3923
|
+
flushUsage(entry.session);
|
|
3924
|
+
}, USAGE_FLUSH_DEBOUNCE_MS);
|
|
3925
|
+
timer.unref?.();
|
|
3926
|
+
pendingUsageFlushes.set(sid, {
|
|
3927
|
+
session,
|
|
3928
|
+
timer
|
|
3929
|
+
});
|
|
3930
|
+
}
|
|
3931
|
+
/**
|
|
3932
|
+
* session/disposed 残量出口(T9):取消在途 debounce、立即 flush 全部未落库
|
|
3933
|
+
* usage,并 upsert 会话行标记 source=live。老代际不发该事件时本函数只是
|
|
3934
|
+
* 不被调用——随写随刷路径不受影响(不依赖 dispose 的可靠性)。
|
|
3935
|
+
*/
|
|
3936
|
+
function flushUsageOnDispose(session) {
|
|
3937
|
+
const sid = String(session.id);
|
|
3938
|
+
const entry = pendingUsageFlushes.get(sid);
|
|
3939
|
+
if (entry !== void 0) {
|
|
3940
|
+
clearTimeout(entry.timer);
|
|
3941
|
+
entry.timer.unref?.();
|
|
3942
|
+
pendingUsageFlushes.delete(sid);
|
|
3943
|
+
}
|
|
3944
|
+
flushUsage(session);
|
|
3945
|
+
withStoreWrite("dispose session row", (store) => {
|
|
3946
|
+
store.setSessionWatermark(sid, store.getSessionWatermark(sid), { source: "live" });
|
|
3947
|
+
});
|
|
3948
|
+
}
|
|
3949
|
+
/**
|
|
3950
|
+
* 积分器采样落库(spec T15):fresh 边界的存量净快照 + 该次调用 usage 拆分。
|
|
3951
|
+
* 行形 kind='sample'、basis=''、component ∈ {netExact, netEstimated,
|
|
3952
|
+
* cachedInput, uncachedInput}(与 StatsStore.sumSamples 的读取面一致),幂等键
|
|
3953
|
+
* (session_id, boundarySeq, 'sample', component, '')——同一边界重放零新增,
|
|
3954
|
+
* calls(distinct seq 数)不涨。零值行不写(无信息量);负净额照写(召回后
|
|
3955
|
+
* 存量转负正是积分回落的语义)。sample 不前推 sessions 水位——覆盖语义归
|
|
3956
|
+
* flushUsage 的 usage 行。
|
|
3957
|
+
*/
|
|
3958
|
+
function recordIntegralSample(input) {
|
|
3959
|
+
if (!Number.isFinite(input.boundarySeq) || input.boundarySeq < 0) return;
|
|
3960
|
+
const candidates = [
|
|
3961
|
+
["netExact", input.netExact],
|
|
3962
|
+
["netEstimated", input.netEstimated],
|
|
3963
|
+
["cachedInput", input.cachedInput],
|
|
3964
|
+
["uncachedInput", input.uncachedInput]
|
|
3965
|
+
];
|
|
3966
|
+
const rows = [];
|
|
3967
|
+
for (const [component, tokens] of candidates) {
|
|
3968
|
+
if (!Number.isFinite(tokens) || tokens === 0) continue;
|
|
3969
|
+
rows.push({
|
|
3970
|
+
seq: Math.trunc(input.boundarySeq),
|
|
3971
|
+
kind: "sample",
|
|
3972
|
+
component,
|
|
3973
|
+
basis: "",
|
|
3974
|
+
tokens: Math.trunc(tokens),
|
|
3975
|
+
at: Date.now()
|
|
3976
|
+
});
|
|
3977
|
+
}
|
|
3978
|
+
if (rows.length === 0) return;
|
|
3979
|
+
withStoreWrite("integral sample", (store) => {
|
|
3980
|
+
store.recordClaims(input.sessionId, rows);
|
|
3981
|
+
});
|
|
3982
|
+
}
|
|
3983
|
+
/**
|
|
3984
|
+
* /ccip `flush` 的抓手(spec T31):立即冲刷全部在途 usage debounce(等价于
|
|
3985
|
+
* 对每个挂起会话跑一次 dispose 出口,但不 upsert source——活跃会话的归属不变)。
|
|
3986
|
+
*/
|
|
3987
|
+
function flushPendingUsageNow() {
|
|
3988
|
+
const entries = [...pendingUsageFlushes.values()];
|
|
3989
|
+
pendingUsageFlushes.clear();
|
|
3990
|
+
for (const entry of entries) {
|
|
3991
|
+
clearTimeout(entry.timer);
|
|
3992
|
+
entry.timer.unref?.();
|
|
3993
|
+
}
|
|
3994
|
+
for (const entry of entries) flushUsage(entry.session);
|
|
3995
|
+
}
|
|
3996
|
+
/** 测试/卸载清理:丢弃全部在途 debounce(已落库数据不回滚)。 */
|
|
3997
|
+
function cancelPendingUsageFlushes() {
|
|
3998
|
+
for (const entry of pendingUsageFlushes.values()) {
|
|
3999
|
+
clearTimeout(entry.timer);
|
|
4000
|
+
entry.timer.unref?.();
|
|
4001
|
+
}
|
|
4002
|
+
pendingUsageFlushes.clear();
|
|
4003
|
+
}
|
|
4004
|
+
//#endregion
|
|
4005
|
+
//#region src/runtime/stats-backfill.ts
|
|
4006
|
+
/**
|
|
4007
|
+
* 旧会话回填主体(spec 持久层主干 T18/T20)——双后端共用同一 claims 提取核心。
|
|
4008
|
+
*
|
|
4009
|
+
* **后端 A**(优先):宿主 `sessionQuery` 服务的 listSessions/readSession +
|
|
4010
|
+
* version 水位 diff(结构照 SI sync.ts:106-153)。服务面零格式风险;服务缺席
|
|
4011
|
+
* 返回 `available:false` 标记,不抛。
|
|
4012
|
+
*
|
|
4013
|
+
* **后端 B**(fallback,满足"按磁盘行为记录统计旧会话"的显式需求):
|
|
4014
|
+
* `<dshHome>/sessions/**` 目录发现(判据 = 目录里有规范代次产物或迁移暂存,
|
|
4015
|
+
* 不要求任何具体文件名,照 SS scan.ts:62-102)→ T19 叶子模块解码 → 同一提取
|
|
4016
|
+
* 核心。**绝不写会话文件**(SS 红线先例)。
|
|
4017
|
+
*
|
|
4018
|
+
* fail-soft 接线(T19 留的裁决位):header 代次未知/缺失/非会话头 → 跳过该
|
|
4019
|
+
* 会话 + 整进程恰一条聚合 warn(门闩在模块级,测试 resetModules 隔离)。
|
|
4020
|
+
*
|
|
4021
|
+
* 计数口径(裁决 7):零 tokenizer——savings/offsets 由 projectSavingsCore
|
|
4022
|
+
* 注入"拒绝精确计数"的假计数器得到 chars/4 口径行;usage 从
|
|
4023
|
+
* `assistant/message.data.usage` 的固定科目白名单逐事件求和。所有行以
|
|
4024
|
+
* (sessionId, 绝对 seq, kind, component, basis) 主键 INSERT OR IGNORE 幂等。
|
|
4025
|
+
*
|
|
4026
|
+
* live 护栏:会话行 `source='live'` 即整段跳过——live 路径的组件名
|
|
4027
|
+
* (fresh/history/…)与投影行 ('projection') 主键不同,若两边都写会双计。
|
|
4028
|
+
*
|
|
4029
|
+
* @module dsh-context-compression-improved/runtime/stats-backfill
|
|
4030
|
+
*/
|
|
4031
|
+
/** 回填计数口径的注入计数器:恒拒绝精确计数 → 投影全部落 chars/4 分列。 */
|
|
4032
|
+
const BACKFILL_COUNTER = () => unavailableTokenCount("stats backfill counts without tokenizer by design");
|
|
4033
|
+
/** usage 落库科目白名单:字段名(磁盘) → claim component(固定模板,无自由文本)。 */
|
|
4034
|
+
const USAGE_FIELDS = [
|
|
4035
|
+
["inputTokens", "input"],
|
|
4036
|
+
["outputTokens", "output"],
|
|
4037
|
+
["cacheReadTokens", "cacheRead"],
|
|
4038
|
+
["cacheWriteTokens", "cacheWrite"]
|
|
4039
|
+
];
|
|
4040
|
+
/** 语料枚举上限——SS 实测教训:这是防无界遍历的边界而非策略,取宽量级。 */
|
|
4041
|
+
const DISCOVERY_LIMIT = 1e5;
|
|
4042
|
+
/**
|
|
4043
|
+
* 从事件流重建当前 surface 节点集合:顺序走 append/replace 语义
|
|
4044
|
+
* (replace 事件把 [start,end] 移出 surface、自身入 surface)。
|
|
4045
|
+
* 两后端共用——同 feed 必同 surface,这是"双后端结果一致"的前提。
|
|
4046
|
+
*/
|
|
4047
|
+
function replaySurfaceNodes(events) {
|
|
4048
|
+
const surface = /* @__PURE__ */ new Set();
|
|
4049
|
+
for (const event of events) {
|
|
4050
|
+
const op = event.surfaceOp;
|
|
4051
|
+
if (op !== null && typeof op === "object" && op.op === "replace") {
|
|
4052
|
+
const start = Number(op.startSeq);
|
|
4053
|
+
const end = Number(op.endSeq);
|
|
4054
|
+
if (Number.isFinite(start) && Number.isFinite(end)) for (let seq = start; seq <= end; seq += 1) surface.delete(seq);
|
|
4055
|
+
}
|
|
4056
|
+
surface.add(Number(event.seq));
|
|
4057
|
+
}
|
|
4058
|
+
return [...surface];
|
|
4059
|
+
}
|
|
4060
|
+
/**
|
|
4061
|
+
* 同一 claims 提取核心(后端 A/B 共用,T23 的一致性对象):
|
|
4062
|
+
* 投影 savings/offsets + `assistant/message` 的 usage 固定科目求和。
|
|
4063
|
+
* 纯函数:不落库、不告警、不抛事件形状问题(坏行走投影内部 fail-open)。
|
|
4064
|
+
*/
|
|
4065
|
+
function extractBackfillClaims(events) {
|
|
4066
|
+
if (events.length === 0) return {
|
|
4067
|
+
rows: [],
|
|
4068
|
+
maxSeq: 0
|
|
4069
|
+
};
|
|
4070
|
+
let maxSeq = 0;
|
|
4071
|
+
for (const event of events) maxSeq = Math.max(maxSeq, Number(event.seq));
|
|
4072
|
+
const projection = projectSavingsCore({
|
|
4073
|
+
events,
|
|
4074
|
+
surfaceNodes: replaySurfaceNodes(events),
|
|
4075
|
+
counter: BACKFILL_COUNTER
|
|
4076
|
+
});
|
|
4077
|
+
const rows = [];
|
|
4078
|
+
for (const saving of projection.savings) rows.push({
|
|
4079
|
+
seq: saving.replacementSeq,
|
|
4080
|
+
kind: "saving",
|
|
4081
|
+
component: "projection",
|
|
4082
|
+
basis: saving.basis,
|
|
4083
|
+
tokens: saving.tokens,
|
|
4084
|
+
at: saving.at
|
|
4085
|
+
});
|
|
4086
|
+
for (const offset of projection.offsets) rows.push({
|
|
4087
|
+
seq: offset.seq,
|
|
4088
|
+
kind: "offset",
|
|
4089
|
+
component: offset.component,
|
|
4090
|
+
basis: offset.basis,
|
|
4091
|
+
tokens: offset.tokens,
|
|
4092
|
+
at: offset.at
|
|
4093
|
+
});
|
|
4094
|
+
for (const event of events) {
|
|
4095
|
+
if (event.type !== "assistant/message") continue;
|
|
4096
|
+
const usage = event.data?.["usage"];
|
|
4097
|
+
if (usage === void 0 || typeof usage !== "object") continue;
|
|
4098
|
+
for (const [field, component] of USAGE_FIELDS) {
|
|
4099
|
+
const value = usage[field];
|
|
4100
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) continue;
|
|
4101
|
+
rows.push({
|
|
4102
|
+
seq: Number(event.seq),
|
|
4103
|
+
kind: "usage",
|
|
4104
|
+
component,
|
|
4105
|
+
basis: "",
|
|
4106
|
+
tokens: Math.round(value),
|
|
4107
|
+
at: Number(event.time) || 0
|
|
4108
|
+
});
|
|
4109
|
+
}
|
|
4110
|
+
}
|
|
4111
|
+
return {
|
|
4112
|
+
rows,
|
|
4113
|
+
maxSeq
|
|
4114
|
+
};
|
|
4115
|
+
}
|
|
4116
|
+
function newPassResult(backend, available) {
|
|
4117
|
+
return {
|
|
4118
|
+
backend,
|
|
4119
|
+
available,
|
|
4120
|
+
sessions: 0,
|
|
4121
|
+
skipped: 0,
|
|
4122
|
+
claimsAdded: 0,
|
|
4123
|
+
failures: []
|
|
4124
|
+
};
|
|
4125
|
+
}
|
|
4126
|
+
/** live 护栏:会话行已被 live 路径认领 → 回填整段跳过(防双计)。 */
|
|
4127
|
+
function isLiveOwned(store, sessionId) {
|
|
4128
|
+
return store.getSessionRecord(sessionId)?.source === "live";
|
|
4129
|
+
}
|
|
4130
|
+
/**
|
|
4131
|
+
* 后端 A 一轮:listSessions → 与 sessions.version 水位 diff → 新/变更会话
|
|
4132
|
+
* readSession → 提取核心落库 → 写回 version 水位。
|
|
4133
|
+
* 服务缺席(老线宿主无该可选服务)→ available:false,调用方应退后端 B。
|
|
4134
|
+
*/
|
|
4135
|
+
async function backfillViaSessionQuery(store, sessionQuery, options = {}) {
|
|
4136
|
+
const result = newPassResult("sessionQuery", sessionQuery !== void 0);
|
|
4137
|
+
if (sessionQuery === void 0) return result;
|
|
4138
|
+
let records;
|
|
4139
|
+
try {
|
|
4140
|
+
records = await sessionQuery.listSessions();
|
|
4141
|
+
} catch (error) {
|
|
4142
|
+
result.available = false;
|
|
4143
|
+
result.failures.push({
|
|
4144
|
+
sessionId: "*",
|
|
4145
|
+
error: String(error?.message ?? error)
|
|
4146
|
+
});
|
|
4147
|
+
return result;
|
|
4148
|
+
}
|
|
4149
|
+
const limit = options.maxSessions ?? records.length;
|
|
4150
|
+
for (const record of records.slice(0, Math.max(0, limit))) {
|
|
4151
|
+
const sessionId = String(record.header.id);
|
|
4152
|
+
if (isLiveOwned(store, sessionId)) {
|
|
4153
|
+
result.skipped += 1;
|
|
4154
|
+
continue;
|
|
4155
|
+
}
|
|
4156
|
+
const existing = store.getSessionRecord(sessionId);
|
|
4157
|
+
if (existing !== void 0 && existing.version === record.header.version) {
|
|
4158
|
+
result.skipped += 1;
|
|
4159
|
+
continue;
|
|
4160
|
+
}
|
|
4161
|
+
try {
|
|
4162
|
+
const log = await sessionQuery.readSession(sessionId);
|
|
4163
|
+
const { rows } = extractBackfillClaims(log.events);
|
|
4164
|
+
result.claimsAdded += store.recordClaims(sessionId, rows);
|
|
4165
|
+
const version = Number.isFinite(log.session.version) ? log.session.version : record.header.version;
|
|
4166
|
+
store.setSessionWatermark(sessionId, version, {
|
|
4167
|
+
project: log.session.cwd ?? record.header.cwd ?? "",
|
|
4168
|
+
source: "backfill"
|
|
4169
|
+
});
|
|
4170
|
+
result.sessions += 1;
|
|
4171
|
+
} catch (error) {
|
|
4172
|
+
result.failures.push({
|
|
4173
|
+
sessionId,
|
|
4174
|
+
error: String(error?.message ?? error)
|
|
4175
|
+
});
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
4178
|
+
return result;
|
|
4179
|
+
}
|
|
4180
|
+
/**
|
|
4181
|
+
* `<dshHome>/sessions/**` 递归发现:判据 = 目录内有规范代次产物或迁移暂存
|
|
4182
|
+
* (不要求具体文件名,照 SS scan 的栈遍历)。仅暂存(迁移进行中)的目录
|
|
4183
|
+
* 不构成可解码产物,跳过。
|
|
4184
|
+
*/
|
|
4185
|
+
function discoverBackfillSessionLogs(dshHome, limit = DISCOVERY_LIMIT) {
|
|
4186
|
+
const root = join(dshHome, "sessions");
|
|
4187
|
+
const out = [];
|
|
4188
|
+
if (!existsSync(root)) return out;
|
|
4189
|
+
const stack = [root];
|
|
4190
|
+
while (stack.length > 0 && out.length < limit) {
|
|
4191
|
+
const dir = stack.pop();
|
|
4192
|
+
if (dir === void 0) continue;
|
|
4193
|
+
let entries;
|
|
4194
|
+
try {
|
|
4195
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
4196
|
+
} catch {
|
|
4197
|
+
continue;
|
|
4198
|
+
}
|
|
4199
|
+
for (const entry of entries) {
|
|
4200
|
+
if (!entry.isDirectory()) continue;
|
|
4201
|
+
const path = join(dir, entry.name);
|
|
4202
|
+
const generations = readSessionGenerations(path);
|
|
4203
|
+
if (generations.canonical.length === 0 && generations.staging.length === 0) {
|
|
4204
|
+
stack.push(path);
|
|
4205
|
+
continue;
|
|
4206
|
+
}
|
|
4207
|
+
const current = generations.current;
|
|
4208
|
+
if (current === void 0) continue;
|
|
4209
|
+
if (out.length >= limit) break;
|
|
4210
|
+
out.push({
|
|
4211
|
+
dirSessionId: entry.name,
|
|
4212
|
+
dir: path,
|
|
4213
|
+
artifact: current
|
|
4214
|
+
});
|
|
4215
|
+
}
|
|
4216
|
+
}
|
|
4217
|
+
return out;
|
|
4218
|
+
}
|
|
4219
|
+
let unknownGenerationWarned = false;
|
|
4220
|
+
function emitFailSoftWarnOnce(sink, skipped) {
|
|
4221
|
+
if (unknownGenerationWarned || skipped.length === 0) return;
|
|
4222
|
+
unknownGenerationWarned = true;
|
|
4223
|
+
const sample = skipped.slice(0, 3).map((entry) => `${entry.sessionId}(${entry.state})`).join(", ");
|
|
4224
|
+
sink(`${skipped.length} session log(s) skipped: header generation unknown (${sample}${skipped.length > 3 ? ", …" : ""})`);
|
|
4225
|
+
}
|
|
4226
|
+
/**
|
|
4227
|
+
* 后端 B 一轮:目录发现 → 当前代产物只读解码 → fail-soft 代次裁决 →
|
|
4228
|
+
* 提取核心落库(source=backfill,水位 = 观测 maxSeq)。
|
|
4229
|
+
* 绝不写会话文件;单会话失败隔离进 failures。
|
|
4230
|
+
*/
|
|
4231
|
+
async function backfillViaSessionFiles(store, options = {}) {
|
|
4232
|
+
const result = newPassResult("files", true);
|
|
4233
|
+
const dshHome = options.dshHome ?? resolveStatsDshHome(options);
|
|
4234
|
+
const decoders = options.decoders !== void 0 ? options.decoders : await loadOfficialDecoders();
|
|
4235
|
+
const sink = options.warn ?? ((message) => {
|
|
4236
|
+
console.warn("context-compression stats backfill: %s", message);
|
|
4237
|
+
});
|
|
4238
|
+
const softSkipped = [];
|
|
4239
|
+
const discovered = discoverBackfillSessionLogs(dshHome, options.maxSessions ?? DISCOVERY_LIMIT);
|
|
4240
|
+
result.totalDiscovered = discovered.length;
|
|
4241
|
+
const offset = Math.max(0, options.slice?.offset ?? 0);
|
|
4242
|
+
const windowLimit = Math.max(0, options.slice?.limit ?? discovered.length);
|
|
4243
|
+
const windowed = discovered.slice(offset, offset + windowLimit);
|
|
4244
|
+
for (const found of windowed) {
|
|
4245
|
+
if (isLiveOwned(store, found.dirSessionId)) {
|
|
4246
|
+
result.skipped += 1;
|
|
4247
|
+
continue;
|
|
4248
|
+
}
|
|
4249
|
+
let log;
|
|
4250
|
+
try {
|
|
4251
|
+
log = decodeSessionLogBytes(readFileSync(found.artifact.path), decoders);
|
|
4252
|
+
} catch (error) {
|
|
4253
|
+
result.failures.push({
|
|
4254
|
+
sessionId: found.dirSessionId,
|
|
4255
|
+
error: String(error?.message ?? error)
|
|
4256
|
+
});
|
|
4257
|
+
continue;
|
|
4258
|
+
}
|
|
4259
|
+
const verdict = classifySessionHeader(log.header);
|
|
4260
|
+
if (verdict.state !== "known") {
|
|
4261
|
+
softSkipped.push({
|
|
4262
|
+
sessionId: found.dirSessionId,
|
|
4263
|
+
state: verdict.state
|
|
4264
|
+
});
|
|
4265
|
+
result.skipped += 1;
|
|
4266
|
+
continue;
|
|
4267
|
+
}
|
|
4268
|
+
const headerId = log.header?.["id"];
|
|
4269
|
+
const sessionId = typeof headerId === "string" && headerId.trim() !== "" ? headerId.trim() : found.dirSessionId;
|
|
4270
|
+
if (isLiveOwned(store, sessionId)) {
|
|
4271
|
+
result.skipped += 1;
|
|
4272
|
+
continue;
|
|
4273
|
+
}
|
|
4274
|
+
const { rows, maxSeq } = extractBackfillClaims(log.events);
|
|
4275
|
+
const existingRecord = store.getSessionRecord(sessionId);
|
|
4276
|
+
if (existingRecord !== void 0 && existingRecord.source === "backfill" && existingRecord.version >= maxSeq) {
|
|
4277
|
+
result.skipped += 1;
|
|
4278
|
+
continue;
|
|
4279
|
+
}
|
|
4280
|
+
try {
|
|
4281
|
+
result.claimsAdded += store.recordClaims(sessionId, rows);
|
|
4282
|
+
const headerCwd = log.header?.["cwd"];
|
|
4283
|
+
store.setSessionWatermark(sessionId, maxSeq, {
|
|
4284
|
+
project: typeof headerCwd === "string" ? headerCwd : "",
|
|
4285
|
+
source: "backfill"
|
|
4286
|
+
});
|
|
4287
|
+
result.sessions += 1;
|
|
4288
|
+
} catch (error) {
|
|
4289
|
+
result.failures.push({
|
|
4290
|
+
sessionId,
|
|
4291
|
+
error: String(error?.message ?? error)
|
|
4292
|
+
});
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
4295
|
+
emitFailSoftWarnOnce(sink, softSkipped);
|
|
4296
|
+
return result;
|
|
4297
|
+
}
|
|
4298
|
+
/**
|
|
4299
|
+
* 回填调度器:把双后端包成分块、可暂停、有触发源的进程级单例。
|
|
4300
|
+
*
|
|
4301
|
+
* 触发源(spec T21):
|
|
4302
|
+
* - `/savings|/monitor` 路由首次命中(`kickStatsBackfillOnRouteHit`,一次性
|
|
4303
|
+
* 闸——面板轮询每 2-5s 打一次路由,闸保证只播一轮);
|
|
4304
|
+
* - dispose 后低频(`kickStatsBackfillOnDispose`,10 分钟节流——老代际不发
|
|
4305
|
+
* session/disposed 时该源静默闲置,与 T9 同一宽容语义)。
|
|
4306
|
+
*
|
|
4307
|
+
* 分块:后端 A 本就是逐会话 await(服务面 IO 天然让出);后端 B 的 decode 是
|
|
4308
|
+
* 同步 CPU(实测 ~84ms/会话),按 chunk 切片、chunk 间 setImmediate 让出事件
|
|
4309
|
+
* 循环,一轮 pass 至多完整扫一遍发现列表(游标跨 pass 记忆,wrap 后归零——
|
|
4310
|
+
* 水位让重扫幂等零新增)。
|
|
4311
|
+
*
|
|
4312
|
+
* 暂停面(/ccip T31 的预留挂点):`pauseStatsBackfill` 后所有 kick 与直接
|
|
4313
|
+
* `runStatsBackfillPass` 都空转;status 面板/命令读 `getStatsBackfillStatus`。
|
|
4314
|
+
* 调度器绝不抛错到触发源——所有失败进 pass.failures / lastSummary。
|
|
4315
|
+
*/
|
|
4316
|
+
const DISPOSE_KICK_MIN_INTERVAL_MS = 6e5;
|
|
4317
|
+
/** 每 chunk 处理的会话数(10-50 区间中点;25×84ms ≈ 2.1s CPU/chunk,间隙让出)。 */
|
|
4318
|
+
const FILES_CHUNK_SIZE = 25;
|
|
4319
|
+
/** 后端 A 单轮服务的会话上限(listSessions 全量但 readSession 逐个 await;防御性封顶)。 */
|
|
4320
|
+
const SESSION_QUERY_PASS_CAP = 500;
|
|
4321
|
+
const schedulerState = {
|
|
4322
|
+
sessionQuery: void 0,
|
|
4323
|
+
routeKickArmed: false,
|
|
4324
|
+
lastDisposeKickAt: 0,
|
|
4325
|
+
running: false,
|
|
4326
|
+
paused: false,
|
|
4327
|
+
filesCursor: 0,
|
|
4328
|
+
runs: 0,
|
|
4329
|
+
lastRunAt: 0,
|
|
4330
|
+
lastSummary: void 0
|
|
4331
|
+
};
|
|
4332
|
+
/** 注入触发源依赖(index.ts apply 时调用一次):sessionQuery 服务的惰性解析器。 */
|
|
4333
|
+
function configureStatsBackfillTrigger(input = {}) {
|
|
4334
|
+
schedulerState.sessionQuery = input.sessionQuery;
|
|
4335
|
+
}
|
|
4336
|
+
/** 路由首次命中触发(一次性闸;面板轮询重复命中零开销)。 */
|
|
4337
|
+
function kickStatsBackfillOnRouteHit() {
|
|
4338
|
+
if (schedulerState.routeKickArmed) return;
|
|
4339
|
+
schedulerState.routeKickArmed = true;
|
|
4340
|
+
runStatsBackfillPass().catch(() => void 0);
|
|
4341
|
+
}
|
|
4342
|
+
/** dispose 后低频触发(10 分钟节流);paused/running 时不消耗节流窗口。 */
|
|
4343
|
+
function kickStatsBackfillOnDispose() {
|
|
4344
|
+
if (schedulerState.paused || schedulerState.running) return;
|
|
4345
|
+
const now = Date.now();
|
|
4346
|
+
if (now - schedulerState.lastDisposeKickAt < DISPOSE_KICK_MIN_INTERVAL_MS) return;
|
|
4347
|
+
schedulerState.lastDisposeKickAt = now;
|
|
4348
|
+
runStatsBackfillPass().catch(() => void 0);
|
|
4349
|
+
}
|
|
4350
|
+
/** /ccip T31 预留:暂停后所有 kick 与直接 pass 空转(在途 chunk 完成本轮即止)。 */
|
|
4351
|
+
function pauseStatsBackfill() {
|
|
4352
|
+
schedulerState.paused = true;
|
|
4353
|
+
}
|
|
4354
|
+
function resumeStatsBackfill() {
|
|
4355
|
+
schedulerState.paused = false;
|
|
4356
|
+
}
|
|
4357
|
+
function getStatsBackfillStatus() {
|
|
4358
|
+
return {
|
|
4359
|
+
running: schedulerState.running,
|
|
4360
|
+
paused: schedulerState.paused,
|
|
4361
|
+
runs: schedulerState.runs,
|
|
4362
|
+
lastRunAt: schedulerState.lastRunAt,
|
|
4363
|
+
...schedulerState.lastSummary === void 0 ? {} : { lastSummary: schedulerState.lastSummary }
|
|
4364
|
+
};
|
|
4365
|
+
}
|
|
4366
|
+
/** chunk 间让出事件循环(setImmediate 不吊进程退出)。 */
|
|
4367
|
+
function yieldToEventLoop() {
|
|
4368
|
+
return new Promise((resolve) => {
|
|
4369
|
+
setImmediate(() => resolve()).unref?.();
|
|
4370
|
+
});
|
|
4371
|
+
}
|
|
4372
|
+
function mergeFileChunk(merged, chunk) {
|
|
4373
|
+
merged.sessions += chunk.sessions;
|
|
4374
|
+
merged.skipped += chunk.skipped;
|
|
4375
|
+
merged.claimsAdded += chunk.claimsAdded;
|
|
4376
|
+
for (const failure of chunk.failures) {
|
|
4377
|
+
if (merged.failures.length >= 50) break;
|
|
4378
|
+
merged.failures.push(failure);
|
|
4379
|
+
}
|
|
4380
|
+
}
|
|
4381
|
+
/** 前台活跃压缩期间回填让路(轮询 busy 旗标);上限防旗标异常悬挂饿死回填。 */
|
|
4382
|
+
const LIVE_PATH_POLL_MS = 800;
|
|
4383
|
+
const LIVE_PATH_MAX_WAIT_MS = 12e4;
|
|
4384
|
+
async function yieldToLivePath() {
|
|
4385
|
+
const start = Date.now();
|
|
4386
|
+
while (isStatsLivePathBusy() && Date.now() - start < LIVE_PATH_MAX_WAIT_MS) await new Promise((resolve) => setTimeout(resolve, LIVE_PATH_POLL_MS));
|
|
4387
|
+
}
|
|
4388
|
+
/**
|
|
4389
|
+
* 跑一轮回填(后端 A 优先,缺席降级后端 B 分块全扫)。running/paused/无 store
|
|
4390
|
+
* 时返回 undefined(触发源丢弃即可);异常一律吞进返回值语义,绝不上抛到触发源。
|
|
4391
|
+
* 前台优先纪律:pass 开始与后端 B 每个 chunk 前都先让路活跃压缩窗口。
|
|
4392
|
+
*/
|
|
4393
|
+
async function runStatsBackfillPass(options = {}) {
|
|
4394
|
+
const store = options.store ?? getStatsStore();
|
|
4395
|
+
if (store === null || schedulerState.running || schedulerState.paused) return void 0;
|
|
4396
|
+
schedulerState.running = true;
|
|
4397
|
+
try {
|
|
4398
|
+
await yieldToLivePath();
|
|
4399
|
+
const passA = await backfillViaSessionQuery(store, options.sessionQuery ?? schedulerState.sessionQuery?.(), { maxSessions: Math.min(options.maxSessionsPerBackend ?? SESSION_QUERY_PASS_CAP, SESSION_QUERY_PASS_CAP) });
|
|
4400
|
+
if (passA.available) {
|
|
4401
|
+
schedulerState.runs += 1;
|
|
4402
|
+
schedulerState.lastRunAt = Date.now();
|
|
4403
|
+
schedulerState.lastSummary = {
|
|
4404
|
+
backend: passA.backend,
|
|
4405
|
+
sessions: passA.sessions,
|
|
4406
|
+
skipped: passA.skipped,
|
|
4407
|
+
claimsAdded: passA.claimsAdded,
|
|
4408
|
+
failures: passA.failures.length
|
|
4409
|
+
};
|
|
4410
|
+
return passA;
|
|
4411
|
+
}
|
|
4412
|
+
const merged = newPassResult("files", true);
|
|
4413
|
+
const chunkLimit = Math.max(1, options.maxSessionsPerBackend ?? FILES_CHUNK_SIZE);
|
|
4414
|
+
let sweepOffset = schedulerState.filesCursor;
|
|
4415
|
+
for (;;) {
|
|
4416
|
+
await yieldToLivePath();
|
|
4417
|
+
const chunk = await backfillViaSessionFiles(store, {
|
|
4418
|
+
...options.dshHome === void 0 ? {} : { dshHome: options.dshHome },
|
|
4419
|
+
...options.warn === void 0 ? {} : { warn: options.warn },
|
|
4420
|
+
slice: {
|
|
4421
|
+
offset: sweepOffset,
|
|
4422
|
+
limit: chunkLimit
|
|
4423
|
+
}
|
|
4424
|
+
});
|
|
4425
|
+
const total = chunk.totalDiscovered ?? 0;
|
|
4426
|
+
mergeFileChunk(merged, chunk);
|
|
4427
|
+
if (total === 0) {
|
|
4428
|
+
sweepOffset = 0;
|
|
4429
|
+
break;
|
|
4430
|
+
}
|
|
4431
|
+
sweepOffset += chunkLimit;
|
|
4432
|
+
if (sweepOffset >= total) {
|
|
4433
|
+
sweepOffset = 0;
|
|
4434
|
+
break;
|
|
4435
|
+
}
|
|
4436
|
+
await yieldToEventLoop();
|
|
4437
|
+
}
|
|
4438
|
+
schedulerState.filesCursor = sweepOffset;
|
|
4439
|
+
schedulerState.runs += 1;
|
|
4440
|
+
schedulerState.lastRunAt = Date.now();
|
|
4441
|
+
schedulerState.lastSummary = {
|
|
4442
|
+
backend: merged.backend,
|
|
4443
|
+
sessions: merged.sessions,
|
|
4444
|
+
skipped: merged.skipped,
|
|
4445
|
+
claimsAdded: merged.claimsAdded,
|
|
4446
|
+
failures: merged.failures.length
|
|
4447
|
+
};
|
|
4448
|
+
return merged;
|
|
4449
|
+
} finally {
|
|
4450
|
+
schedulerState.running = false;
|
|
4451
|
+
}
|
|
4452
|
+
}
|
|
4453
|
+
//#endregion
|
|
4454
|
+
//#region src/runtime/savings-integral.ts
|
|
4455
|
+
/** 采样时刻事件日志的最大绝对 seq;空日志(无从定键)返回 undefined。 */
|
|
4456
|
+
function latestEventSeq(session) {
|
|
4457
|
+
let max;
|
|
4458
|
+
for (const event of sessionEvents(session)) {
|
|
4459
|
+
const seq = Number(event.seq);
|
|
4460
|
+
if (Number.isFinite(seq)) max = max === void 0 ? seq : Math.max(max, seq);
|
|
4461
|
+
}
|
|
4462
|
+
return max;
|
|
4463
|
+
}
|
|
4464
|
+
/** usage 拆分:cacheRead = 命中;uncached = input − cacheRead(负截 0);非法值记 0。 */
|
|
4465
|
+
function splitCachedUncached(usage) {
|
|
4466
|
+
const cached = typeof usage?.cacheReadTokens === "number" && Number.isFinite(usage.cacheReadTokens) && usage.cacheReadTokens > 0 ? Math.trunc(usage.cacheReadTokens) : 0;
|
|
4467
|
+
const input = typeof usage?.inputTokens === "number" && Number.isFinite(usage.inputTokens) && usage.inputTokens > 0 ? Math.trunc(usage.inputTokens) : 0;
|
|
4468
|
+
return {
|
|
4469
|
+
cachedInput: cached,
|
|
4470
|
+
uncachedInput: Math.max(0, input - cached)
|
|
4471
|
+
};
|
|
4472
|
+
}
|
|
4473
|
+
/** fresh 边界采样入口:定键 → 拆分 → 经 stats-sync 幂等落库;空日志静默跳过。 */
|
|
4474
|
+
function sampleIntegralBoundary(input) {
|
|
4475
|
+
const boundarySeq = latestEventSeq(input.session);
|
|
4476
|
+
if (boundarySeq === void 0) return;
|
|
4477
|
+
const { cachedInput, uncachedInput } = splitCachedUncached(input.usage);
|
|
4478
|
+
recordIntegralSample({
|
|
4479
|
+
sessionId: input.sessionId,
|
|
4480
|
+
boundarySeq,
|
|
4481
|
+
netExact: input.net.exact,
|
|
4482
|
+
netEstimated: input.net.estimated,
|
|
4483
|
+
cachedInput,
|
|
4484
|
+
uncachedInput
|
|
4485
|
+
});
|
|
4486
|
+
}
|
|
4487
|
+
/**
|
|
4488
|
+
* 省钱估计(T16):cached 走 inputCacheHit、uncached 走 inputCacheMiss,
|
|
4489
|
+
* femto = tokens × nanoRate(与定价模块 amountFor 同构,输出侧不计——
|
|
4490
|
+
* 积分口径只对输入省钱)。费率不可解析(理论上目录内不会)返回 null。
|
|
4491
|
+
*/
|
|
4492
|
+
function estimateIntegralMoney(input) {
|
|
4493
|
+
const hit = decimalRateNanoUnits(input.record.inputCacheHit);
|
|
4494
|
+
const miss = decimalRateNanoUnits(input.record.inputCacheMiss);
|
|
4495
|
+
if (hit === void 0 || miss === void 0) return null;
|
|
4496
|
+
const cached = Number.isFinite(input.cachedInput) && input.cachedInput > 0 ? BigInt(Math.trunc(input.cachedInput)) : 0n;
|
|
4497
|
+
const uncached = Number.isFinite(input.uncachedInput) && input.uncachedInput > 0 ? BigInt(Math.trunc(input.uncachedInput)) : 0n;
|
|
4498
|
+
if (cached === 0n && uncached === 0n) return null;
|
|
4499
|
+
const femtoUnits = cached * hit + uncached * miss;
|
|
4500
|
+
return {
|
|
4501
|
+
decimal: formatFemtoUnits(femtoUnits),
|
|
4502
|
+
femtoUnits: femtoUnits.toString(),
|
|
4503
|
+
currency: input.record.currency,
|
|
4504
|
+
band: input.record.band
|
|
4505
|
+
};
|
|
4506
|
+
}
|
|
4507
|
+
/** femto(1e-15)整数 → 十进制串;与定价模块的 femto 渲染同构(模块内私有,此处独立实现)。 */
|
|
4508
|
+
function formatFemtoUnits(value) {
|
|
4509
|
+
const digits = value.toString().padStart(16, "0");
|
|
4510
|
+
const whole = digits.slice(0, -15);
|
|
4511
|
+
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
4512
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
4513
|
+
}
|
|
4514
|
+
//#endregion
|
|
4515
|
+
export { isValidAutoCompactThresholdPercent as $, officialRequestUsage as A, recordRecertified as At, unavailableCount as B, resolveStatsDshHome as C, getAdvisorState as Ct, dedupePlaceholder as D, invalidateOnTaskChange as Dt, dedupeHash as E, getSummaryOverride as Et, onlyTextBlocks as F, priceOfficialDeepSeekUsage as Ft, ContextCompressionSettingsSchema as G, countOmittedLines as H, pressureCost as I, resolveOfficialDeepSeekPrice as It, PRUNE_MARKER as J, DEFAULTS as K, recoveryMarker as L, getSavingsLedger as Lt, emptyResult as M, setSummaryOverride as Mt, nativePruneContent as N, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as Nt, flattenPlainText as O, observeIntentEnabled as Ot, onlyTextBlock as P, decimalRateNanoUnits as Pt, isCompressionProfile as Q, sameProviderMeasurementKey as R, statsPersistenceState as S, evaluateIntentGate as St, DedupeTable as T, getObservedIntentEnabled as Tt, AUTO_COMPACT_THRESHOLD_LIMITS as U, CAPACITY_PRESSURE_RATIO as V, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as W, charsToTokens as X, charsForTokens as Y, codePointLength as Z, scheduleUsageFlush as _, isSessionOverrideAction as _t, getStatsBackfillStatus as a, resolveCustomPolicy as at, ensureStatsStore as b, INTENT_GATE_FLOOR_FRACTION as bt, pauseStatsBackfill as c, COMPRESSION_PROFILES as ct, claimFromLand as d, decodeSessionLogBytes as dt, parseContextCompressionSettings as et, claimOffset as f, deepSeekV4TokenizerForModel as ft, reclaimFromTailTrim as g, estimateSavingsPricing as gt, getStatsActiveSessionId as h, drsTotalsFragment as ht, discoverBackfillSessionLogs as i, DEFAULT_CUSTOM_COMPRESSION_POLICY as it, countToolContent as j, recordScore as jt, measureForCompaction as k, recordIntentFold as kt, resumeStatsBackfill as l, countExactCanonicalTextFields as lt, flushUsageOnDispose as m, buildMonitorSnapshot as mt, sampleIntegralBoundary as n, resolvePolicy as nt, kickStatsBackfillOnDispose as o, assertNever as ot, flushPendingUsageNow as p, applySessionOverride as pt, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as q, configureStatsBackfillTrigger as r, CustomCompressionPolicySchema as rt, kickStatsBackfillOnRouteHit as s, deepFreeze as st, estimateIntegralMoney as t, resolveConfig as tt, cancelPendingUsageFlushes as u, unavailableTokenCount as ut, setStatsLivePathBusy as v, mergeCompositionByComponent as vt, projectSessionSavings as w, getLastIntentFold as wt, getStatsStore as x, INTENT_GATE_GROWTH_TOKENS as xt, closeStatsStore as y, observeContextUsage as yt, summarize as z };
|