dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/eslint.config.js +30 -30
  3. package/package.json +163 -163
  4. package/packages/selector/dsh.plugin.json +16 -16
  5. package/packages/selector/lib/client.d.ts +20 -0
  6. package/packages/selector/lib/client.js +433 -17
  7. package/packages/selector/lib/index.js +213 -2
  8. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +593 -3
  9. package/packages/selector/lib/profiles.d.ts +9 -0
  10. package/packages/selector/lib/pruner.d.ts +59 -0
  11. package/packages/selector/lib/pruner.js +494 -262
  12. package/packages/selector/lib/style.css +42 -0
  13. package/packages/selector/src/client/CompressionProfileControls.tsx +34 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  15. package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
  16. package/packages/selector/src/client/decode.ts +53 -49
  17. package/packages/selector/src/client/index.ts +4 -0
  18. package/packages/selector/src/client/locales/de.ts +20 -0
  19. package/packages/selector/src/client/locales/es.ts +20 -0
  20. package/packages/selector/src/client/locales/fr.ts +20 -0
  21. package/packages/selector/src/client/locales/it.ts +20 -0
  22. package/packages/selector/src/client/locales/ja.ts +20 -0
  23. package/packages/selector/src/client/locales/ko.ts +20 -0
  24. package/packages/selector/src/client/locales/ru.ts +20 -0
  25. package/packages/selector/src/client/locales.ts +236 -196
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +133 -124
  28. package/packages/selector/src/index.ts +554 -411
  29. package/packages/selector/src/profiles.ts +414 -394
  30. package/packages/selector/src/pruner/state.ts +57 -50
  31. package/packages/selector/src/pruner.ts +2745 -2421
  32. package/packages/selector/src/runtime/audit.ts +303 -286
  33. package/packages/selector/src/runtime/config.ts +731 -706
  34. package/packages/selector/src/runtime/retrieve.ts +479 -457
  35. package/packages/selector/src/runtime/savings.ts +337 -0
  36. package/packages/selector/src/runtime/summary-command.ts +127 -0
  37. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  38. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  39. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  43. package/packages/selector/src/runtime/types.ts +358 -346
  44. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  45. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  46. package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
  47. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  48. package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
  49. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  50. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  51. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  52. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  53. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  54. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
  55. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  56. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  57. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  58. package/scripts/packed-install-e2e.mjs +1 -1
  59. package/scripts/verify-release.mjs +2 -1
@@ -1,4 +1,506 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
+ import { createHash } from "node:crypto";
3
+ //#region src/runtime/savings.ts
4
+ /**
5
+ * 节省统计账本(诚实口径)。
6
+ *
7
+ * 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
8
+ * 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
9
+ * tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
10
+ * 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
11
+ * 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
12
+ * 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
13
+ * 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
14
+ * 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
15
+ * 汇总,永不合并成一个数。
16
+ *
17
+ * 存储:进程内 per-session 账本(条目环形缓冲 + hash 注册表)。不落盘——
18
+ * 节省统计是运行期面板数据,重启归零是可接受语义(审计日志里已有全量原始记录)。
19
+ *
20
+ * @module dsh-context-compression-improved/runtime/savings
21
+ */
22
+ const MAX_ENTRIES_PER_SESSION = 400;
23
+ const MAX_REGISTRY = 2048;
24
+ var SavingsLedger = class {
25
+ entries = /* @__PURE__ */ new Map();
26
+ registry = /* @__PURE__ */ new Map();
27
+ seenFullText = /* @__PURE__ */ new Set();
28
+ usage = /* @__PURE__ */ new Map();
29
+ startedAt = Date.now();
30
+ /**
31
+ * 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
32
+ * dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
33
+ */
34
+ recordUsage(sessionId, usage) {
35
+ let total = this.usage.get(sessionId);
36
+ if (total === void 0) {
37
+ total = {
38
+ requests: 0,
39
+ inputTokens: 0,
40
+ outputTokens: 0,
41
+ cacheReadTokens: 0,
42
+ cacheWriteTokens: 0
43
+ };
44
+ this.usage.set(sessionId, total);
45
+ }
46
+ total.requests += 1;
47
+ total.inputTokens += positiveOrZero(usage.inputTokens);
48
+ total.outputTokens += positiveOrZero(usage.outputTokens);
49
+ total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens);
50
+ total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens);
51
+ }
52
+ totalsFor(scope) {
53
+ const sum = {
54
+ requests: 0,
55
+ inputTokens: 0,
56
+ outputTokens: 0,
57
+ cacheReadTokens: 0,
58
+ cacheWriteTokens: 0
59
+ };
60
+ for (const sid of scope) {
61
+ const t = this.usage.get(sid);
62
+ if (t === void 0) continue;
63
+ sum.requests += t.requests;
64
+ sum.inputTokens += t.inputTokens;
65
+ sum.outputTokens += t.outputTokens;
66
+ sum.cacheReadTokens += t.cacheReadTokens;
67
+ sum.cacheWriteTokens += t.cacheWriteTokens;
68
+ }
69
+ return sum;
70
+ }
71
+ /** 单行会话汇总(session/disposed 日志用)。 */
72
+ sessionSummaryLine(sessionId) {
73
+ const snap = this.snapshot(sessionId);
74
+ const hit = snap.usage.cacheHitRate;
75
+ return `net=${snap.net.exact}(exact)/${snap.net.estimated}(est) gross=${snap.gross.exact}/${snap.gross.estimated} offsets=${snap.offsets.exact}/${snap.offsets.estimated} requests=${snap.usage.requests} cacheHit=${hit === null ? "–" : `${Math.round(hit * 100)}%`}`;
76
+ }
77
+ /** 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。 */
78
+ recordSaving(input) {
79
+ const removed = input.tokensBefore - input.tokensAfter;
80
+ if (!Number.isFinite(removed) || removed <= 0) return;
81
+ this.push(input.sessionId, {
82
+ kind: "saving",
83
+ component: input.component,
84
+ tokens: removed,
85
+ basis: input.basis,
86
+ at: Date.now()
87
+ });
88
+ if (typeof input.originalText === "string" && input.originalText.length > 0) {
89
+ const hash = savingsHash(input.originalText);
90
+ if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
91
+ const oldest = this.registry.keys().next().value;
92
+ if (oldest !== void 0) this.registry.delete(oldest);
93
+ }
94
+ this.registry.set(hash, {
95
+ sessionId: input.sessionId,
96
+ component: input.component,
97
+ claimedTokens: removed,
98
+ basis: input.basis,
99
+ sourceSeq: input.sourceSeq,
100
+ consumed: false
101
+ });
102
+ }
103
+ }
104
+ /**
105
+ * 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
106
+ * 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
107
+ * @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
108
+ */
109
+ noteFullText(input) {
110
+ if (typeof input.text !== "string" || input.text.length === 0) return;
111
+ const seenKey = `${input.sessionId}:${input.seq}`;
112
+ if (this.seenFullText.has(seenKey)) return;
113
+ this.seenFullText.add(seenKey);
114
+ if (this.seenFullText.size > MAX_REGISTRY * 4) {
115
+ this.seenFullText.clear();
116
+ this.seenFullText.add(seenKey);
117
+ }
118
+ const hit = this.registry.get(savingsHash(input.text));
119
+ if (hit === void 0 || hit.consumed || hit.sessionId !== input.sessionId) return;
120
+ hit.consumed = true;
121
+ const { tokens, basis } = input.measure(input.text);
122
+ if (tokens <= 0) return;
123
+ this.push(input.sessionId, {
124
+ kind: "offset",
125
+ component: "full-read",
126
+ tokens,
127
+ basis,
128
+ at: Date.now(),
129
+ note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`
130
+ });
131
+ }
132
+ /** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
133
+ recordOffset(input) {
134
+ if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
135
+ this.push(input.sessionId, {
136
+ kind: "offset",
137
+ component: input.component,
138
+ tokens: input.tokens,
139
+ basis: input.basis,
140
+ at: Date.now(),
141
+ ...input.note === void 0 ? {} : { note: input.note }
142
+ });
143
+ }
144
+ sourceSeqOf(item) {
145
+ return item.sourceSeq;
146
+ }
147
+ push(sessionId, entry) {
148
+ let list = this.entries.get(sessionId);
149
+ if (list === void 0) {
150
+ list = [];
151
+ this.entries.set(sessionId, list);
152
+ }
153
+ list.push(entry);
154
+ if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION);
155
+ }
156
+ /** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
157
+ snapshot(sessionId) {
158
+ const scope = sessionId === void 0 ? [...this.entries.keys()] : [sessionId];
159
+ const totals = {
160
+ grossExact: 0,
161
+ grossEstimated: 0,
162
+ offsetExact: 0,
163
+ offsetEstimated: 0
164
+ };
165
+ const perComponent = /* @__PURE__ */ new Map();
166
+ const recentOffsets = [];
167
+ for (const sid of scope) for (const entry of this.entries.get(sid) ?? []) {
168
+ const exact = entry.basis === "exact-tokenizer";
169
+ if (entry.kind === "saving") {
170
+ if (exact) totals.grossExact += entry.tokens;
171
+ else totals.grossEstimated += entry.tokens;
172
+ } else {
173
+ if (exact) totals.offsetExact += entry.tokens;
174
+ else totals.offsetEstimated += entry.tokens;
175
+ recentOffsets.push(entry);
176
+ }
177
+ const key = `${entry.kind}:${entry.component}:${entry.basis}`;
178
+ const agg = perComponent.get(key);
179
+ if (agg === void 0) perComponent.set(key, {
180
+ component: entry.component,
181
+ tokens: entry.tokens,
182
+ basis: entry.basis,
183
+ kind: entry.kind
184
+ });
185
+ else agg.tokens += entry.tokens;
186
+ }
187
+ recentOffsets.sort((a, b) => b.at - a.at);
188
+ const usageTotals = this.totalsFor(scope);
189
+ const perSession = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...this.entries.keys(), ...this.usage.keys()])].map((sid) => {
190
+ const s = this.snapshot(sid);
191
+ return {
192
+ sessionId: sid,
193
+ gross: s.gross,
194
+ offsets: s.offsets,
195
+ net: s.net,
196
+ requests: s.usage.requests,
197
+ cacheHitRate: s.usage.cacheHitRate
198
+ };
199
+ }).sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated).slice(0, 8) : [];
200
+ return {
201
+ startedAt: new Date(this.startedAt).toISOString(),
202
+ sessions: sessionId === void 0 ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
203
+ gross: {
204
+ exact: totals.grossExact,
205
+ estimated: totals.grossEstimated
206
+ },
207
+ offsets: {
208
+ exact: totals.offsetExact,
209
+ estimated: totals.offsetEstimated
210
+ },
211
+ net: {
212
+ exact: totals.grossExact - totals.offsetExact,
213
+ estimated: totals.grossEstimated - totals.offsetEstimated
214
+ },
215
+ perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
216
+ recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
217
+ component: e.component,
218
+ tokens: e.tokens,
219
+ basis: e.basis,
220
+ at: new Date(e.at).toISOString(),
221
+ ...e.note === void 0 ? {} : { note: e.note }
222
+ })),
223
+ usage: {
224
+ ...usageTotals,
225
+ cacheHitRate: cacheHitRateOf(usageTotals)
226
+ },
227
+ perSession
228
+ };
229
+ }
230
+ /** 测试与停机清理。 */
231
+ clear() {
232
+ this.entries.clear();
233
+ this.registry.clear();
234
+ this.seenFullText.clear();
235
+ this.usage.clear();
236
+ this.startedAt = Date.now();
237
+ }
238
+ };
239
+ function cacheHitRateOf(t) {
240
+ const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens;
241
+ return denom <= 0 ? null : Math.round(t.cacheReadTokens / denom * 1e3) / 1e3;
242
+ }
243
+ /** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
244
+ function savingsHash(text) {
245
+ return createHash("sha256").update(text.replace(/\r\n?/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/(^\s+)|(\s+$)/g, ""), "utf8").digest("hex");
246
+ }
247
+ function positiveOrZero(v) {
248
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0;
249
+ }
250
+ const singleton = new SavingsLedger();
251
+ /** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
252
+ function getSavingsLedger() {
253
+ return singleton;
254
+ }
255
+ //#endregion
256
+ //#region src/runtime/deepseek-official-pricing.ts
257
+ /** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
258
+ const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
259
+ /** Wall-clock time at which the checked-in official price pages were verified. */
260
+ const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
261
+ const PRICES = Object.freeze({
262
+ "deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
263
+ "0.007",
264
+ "0.22",
265
+ "0.66"
266
+ ], [
267
+ "0.014",
268
+ "0.44",
269
+ "1.32"
270
+ ], [
271
+ "0.05",
272
+ "1.5",
273
+ "4.5"
274
+ ], [
275
+ "0.10",
276
+ "3.0",
277
+ "9.0"
278
+ ]),
279
+ "deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
280
+ "0.022",
281
+ "0.66",
282
+ "1.98"
283
+ ], [
284
+ "0.044",
285
+ "1.32",
286
+ "3.96"
287
+ ], [
288
+ "0.15",
289
+ "4.5",
290
+ "13.5"
291
+ ], [
292
+ "0.30",
293
+ "9.0",
294
+ "27.0"
295
+ ]),
296
+ "deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
297
+ "0.007",
298
+ "0.22",
299
+ "0.66"
300
+ ], [
301
+ "0.014",
302
+ "0.44",
303
+ "1.32"
304
+ ], [
305
+ "0.05",
306
+ "1.5",
307
+ "4.5"
308
+ ], [
309
+ "0.10",
310
+ "3.0",
311
+ "9.0"
312
+ ])
313
+ });
314
+ const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
315
+ const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
316
+ const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
317
+ /**
318
+ * Resolve one immutable official price record; aliases and compatible gateways fail closed.
319
+ * @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
320
+ * @returns An immutable price record or an explicit unpriced reason.
321
+ */
322
+ function resolveOfficialDeepSeekPrice(input) {
323
+ if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
324
+ if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
325
+ if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
326
+ if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
327
+ if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
328
+ const band = priceBandAt(input.at);
329
+ if (band === void 0) return unpriced("invalid price timestamp");
330
+ const model = PRICES[input.modelId];
331
+ const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
332
+ return {
333
+ kind: "priced",
334
+ record: Object.freeze({
335
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
336
+ checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
337
+ provider: "deepseek-official",
338
+ baseUrlClass: "official-public",
339
+ apiRoute: input.apiRoute,
340
+ modelId: input.modelId,
341
+ modelVersion: model.version,
342
+ currency: input.currency,
343
+ unitTokens: 1e6,
344
+ band,
345
+ inputCacheHit,
346
+ inputCacheMiss,
347
+ output,
348
+ sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
349
+ sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
350
+ peakRule: PEAK_RULE
351
+ })
352
+ };
353
+ }
354
+ /**
355
+ * Classify a timestamp under the published Beijing peak schedule.
356
+ * @param at - absolute request time to interpret in Asia/Shanghai.
357
+ * @returns Peak/off-peak, or undefined for an invalid timestamp.
358
+ */
359
+ function priceBandAt(at) {
360
+ if (!Number.isFinite(at.getTime())) return void 0;
361
+ const parts = new Intl.DateTimeFormat("en-US", {
362
+ timeZone: "Asia/Shanghai",
363
+ weekday: "short",
364
+ hour: "2-digit",
365
+ minute: "2-digit",
366
+ second: "2-digit",
367
+ hourCycle: "h23"
368
+ }).formatToParts(at);
369
+ const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
370
+ const weekday = values.weekday;
371
+ const hour = Number(values.hour);
372
+ const minute = Number(values.minute);
373
+ const second = Number(values.second);
374
+ if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
375
+ const workday = weekday !== "Sat" && weekday !== "Sun";
376
+ const seconds = hour * 3600 + minute * 60 + second;
377
+ return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
378
+ }
379
+ /**
380
+ * Price one completed request, returning a range when it spans a published band boundary.
381
+ * @param input - exact applicability, request interval, and complete disjoint usage buckets.
382
+ * @returns Fixed-point exact/range cost or an explicit unpriced reason.
383
+ */
384
+ function priceOfficialDeepSeekUsage(input) {
385
+ for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
386
+ if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
387
+ const start = resolveOfficialDeepSeekPrice({
388
+ ...input,
389
+ at: input.startedAt
390
+ });
391
+ if (start.kind === "unpriced") return start;
392
+ const end = resolveOfficialDeepSeekPrice({
393
+ ...input,
394
+ at: input.completedAt
395
+ });
396
+ if (end.kind === "unpriced") return end;
397
+ const startAmount = amountFor(start.record, input.usage);
398
+ if (startAmount === void 0) return unpriced("invalid decimal price record");
399
+ const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
400
+ if (start.record.band === end.record.band && !crossesBoundary) return {
401
+ kind: "exact",
402
+ currency: start.record.currency,
403
+ band: start.record.band,
404
+ ...startAmount
405
+ };
406
+ const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
407
+ const endAmount = amountFor(comparisonRecord, input.usage);
408
+ if (endAmount === void 0) return unpriced("invalid decimal price record");
409
+ const startFemto = BigInt(startAmount.femtoUnits);
410
+ const endFemto = BigInt(endAmount.femtoUnits);
411
+ return {
412
+ kind: "range",
413
+ currency: start.record.currency,
414
+ bands: [start.record.band, comparisonRecord.band],
415
+ minimum: startFemto <= endFemto ? startAmount : endAmount,
416
+ maximum: startFemto <= endFemto ? endAmount : startAmount
417
+ };
418
+ }
419
+ /** Detect any published UTC band boundary, even when both endpoints share a band. */
420
+ function spansPublishedPriceBoundary(startedAt, completedAt) {
421
+ const start = startedAt.getTime();
422
+ const end = completedAt.getTime();
423
+ if (end <= start) return false;
424
+ const dayMs = 864e5;
425
+ if (end - start >= 7 * dayMs) return true;
426
+ const firstDay = Math.floor(start / dayMs) * dayMs;
427
+ for (let day = firstDay; day <= end; day += dayMs) {
428
+ const weekday = new Date(day).getUTCDay();
429
+ if (weekday === 0 || weekday === 6) continue;
430
+ for (const hour of [
431
+ 1,
432
+ 4,
433
+ 6,
434
+ 10
435
+ ]) {
436
+ const boundary = day + hour * 60 * 60 * 1e3;
437
+ if (boundary > start && boundary <= end) return true;
438
+ }
439
+ }
440
+ return false;
441
+ }
442
+ function priceRecordInBand(record, band) {
443
+ const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
444
+ return Object.freeze({
445
+ ...record,
446
+ band,
447
+ inputCacheHit,
448
+ inputCacheMiss,
449
+ output
450
+ });
451
+ }
452
+ /**
453
+ * Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
454
+ * @param value - canonical non-negative decimal with at most nine fractional digits.
455
+ * @returns Integer nano-units, or undefined when the decimal is invalid.
456
+ */
457
+ function decimalRateNanoUnits(value) {
458
+ const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
459
+ if (match === null) return void 0;
460
+ const whole = match[1] ?? "0";
461
+ const fraction = (match[2] ?? "").padEnd(9, "0");
462
+ return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
463
+ }
464
+ function amountFor(record, usage) {
465
+ const hit = decimalRateNanoUnits(record.inputCacheHit);
466
+ const miss = decimalRateNanoUnits(record.inputCacheMiss);
467
+ const output = decimalRateNanoUnits(record.output);
468
+ if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
469
+ const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
470
+ return {
471
+ femtoUnits: femtoUnits.toString(),
472
+ decimal: formatFemto(femtoUnits)
473
+ };
474
+ }
475
+ function formatFemto(value) {
476
+ const digits = value.toString().padStart(16, "0");
477
+ const whole = digits.slice(0, -15);
478
+ const fraction = digits.slice(-15).replace(/0+$/u, "");
479
+ return fraction.length === 0 ? whole : `${whole}.${fraction}`;
480
+ }
481
+ function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
482
+ return Object.freeze({
483
+ version,
484
+ USD: Object.freeze({
485
+ "off-peak": usdOffPeak,
486
+ peak: usdPeak
487
+ }),
488
+ CNY: Object.freeze({
489
+ "off-peak": cnyOffPeak,
490
+ peak: cnyPeak
491
+ })
492
+ });
493
+ }
494
+ function isOfficialModel(value) {
495
+ return Object.prototype.hasOwnProperty.call(PRICES, value);
496
+ }
497
+ function unpriced(reason) {
498
+ return {
499
+ kind: "unpriced",
500
+ reason
501
+ };
502
+ }
503
+ //#endregion
2
504
  //#region src/runtime/types.ts
3
505
  /** User-facing mixed strategy profile. */
4
506
  const COMPRESSION_PROFILES = [
@@ -373,6 +875,20 @@ function parseCodeSkeletonSettings(value) {
373
875
  return { enabled };
374
876
  }
375
877
  /**
878
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
879
+ * section semantics: absent inherits the lossless `false` default, while a
880
+ * present-but-invalid section is an explicitly invalid document.
881
+ */
882
+ function parseIntentSummarySettings(value) {
883
+ if (value === void 0) return { enabled: false };
884
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
885
+ const keys = Object.keys(value);
886
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
887
+ const enabled = value.enabled;
888
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
889
+ return { enabled };
890
+ }
891
+ /**
376
892
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
377
893
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
378
894
  * codeSkeleton section semantics.
@@ -479,7 +995,8 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
479
995
  profile: "balanced",
480
996
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
481
997
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
482
- codeSkeleton: { enabled: false }
998
+ codeSkeleton: { enabled: false },
999
+ intentSummary: { enabled: false }
483
1000
  };
484
1001
  /**
485
1002
  * Parse one settings document with the persisted-section semantics: `undefined`
@@ -497,17 +1014,19 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
497
1014
  if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
498
1015
  assertPlainDataTree(value);
499
1016
  const candidate = structuredClone(value);
500
- const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions");
1017
+ const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "presetOptions");
501
1018
  if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
502
1019
  assertPresentSection(candidate, "profile", isSupportedProfile);
503
1020
  assertPresentSection(candidate, "custom", isUsableCustomDocument);
504
1021
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
505
1022
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
1023
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
506
1024
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
507
1025
  return {
508
1026
  ...contextCompressionSettingsInputSchema(candidate),
509
1027
  autoCompact,
510
1028
  codeSkeleton,
1029
+ intentSummary,
511
1030
  ...presetOptions === void 0 ? {} : { presetOptions }
512
1031
  };
513
1032
  }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
@@ -958,5 +1477,76 @@ function invalidateOnTaskChange(state, todoVersion) {
958
1477
  state.lastSummaryTurn = -1;
959
1478
  return true;
960
1479
  }
1480
+ /**
1481
+ * `/ctx-summary off|on` overrides, keyed by session id (string). The command
1482
+ * handler only sees `invocation.agent.session.id`, not the pruner's Session
1483
+ * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
1484
+ * strings per session and cleared whenever the override is lifted.
1485
+ */
1486
+ const summaryOverrides = /* @__PURE__ */ new Map();
1487
+ /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
1488
+ function getSummaryOverride(sessionId) {
1489
+ return summaryOverrides.get(sessionId);
1490
+ }
1491
+ /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
1492
+ function setSummaryOverride(sessionId, value) {
1493
+ if (value === void 0) summaryOverrides.delete(sessionId);
1494
+ else summaryOverrides.set(sessionId, value);
1495
+ }
1496
+ /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
1497
+ const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
1498
+ /** Record the gate input the pass last evaluated for this session. */
1499
+ function observeIntentEnabled(sessionId, enabled) {
1500
+ lastObservedIntentEnabled.set(sessionId, enabled);
1501
+ }
1502
+ /** The settings-side enabled flag last observed for the session, if any. */
1503
+ function getObservedIntentEnabled(sessionId) {
1504
+ return lastObservedIntentEnabled.get(sessionId);
1505
+ }
1506
+ const lastIntentFolds = /* @__PURE__ */ new Map();
1507
+ /** Record a landed intent fold for the session (newest wins). */
1508
+ function recordIntentFold(sessionId, record) {
1509
+ lastIntentFolds.set(sessionId, record);
1510
+ }
1511
+ /** The most recent landed intent fold for the session, if any. */
1512
+ function getLastIntentFold(sessionId) {
1513
+ return lastIntentFolds.get(sessionId);
1514
+ }
1515
+ //#endregion
1516
+ //#region src/runtime/tokenpilot/intent-gate.ts
1517
+ /**
1518
+ * Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
1519
+ *
1520
+ * Pure decision helper evaluated at the turn-boundary postflight: it decides
1521
+ * whether this turn may spend a summary-writer LLM call and stage a fold for
1522
+ * the next pressure round. The gate is deliberately conservative — every
1523
+ * unresolved input (unknown context window, non-finite counters) fails closed
1524
+ * toward "do not run", because a skipped fold is free while a wasted summary
1525
+ * call is not. Content safety is unaffected either way: fail-open semantics
1526
+ * live in the fold landing path, not here.
1527
+ */
1528
+ /** Floor: the live surface must exceed this fraction of the context window. */
1529
+ const INTENT_GATE_FLOOR_FRACTION = .45;
1530
+ /** Growth: the live surface must have grown by more than this since the last landed fold. */
1531
+ const INTENT_GATE_GROWTH_TOKENS = 5e4;
1532
+ function isUsableNumber(value) {
1533
+ return Number.isFinite(value) && value >= 0;
1534
+ }
1535
+ /** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
1536
+ function evaluateIntentGate(input) {
1537
+ const snapshot = (decision, reason) => ({
1538
+ ...input,
1539
+ decision,
1540
+ reason
1541
+ });
1542
+ if (!input.enabled) return snapshot(false, "disabled");
1543
+ if (input.override === "off") return snapshot(false, "override-off");
1544
+ if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
1545
+ if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
1546
+ if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
1547
+ if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
1548
+ if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
1549
+ return snapshot(true, "passed");
1550
+ }
961
1551
  //#endregion
962
- export { deepFreeze as C, assertNever as S, resolveConfig as _, AUTO_COMPACT_THRESHOLD_LIMITS as a, DEFAULT_CUSTOM_COMPRESSION_POLICY as b, DEFAULTS as c, charsForTokens as d, charsToTokens as f, parseContextCompressionSettings as g, isValidAutoCompactThresholdPercent as h, recordScore as i, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as l, isCompressionProfile as m, invalidateOnTaskChange as n, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as o, codePointLength as p, recordRecertified as r, ContextCompressionSettingsSchema as s, getAdvisorState as t, PRUNE_MARKER as u, resolvePolicy as v, COMPRESSION_PROFILES as w, resolveCustomPolicy as x, CustomCompressionPolicySchema as y };
1552
+ export { resolveCustomPolicy as A, isCompressionProfile as C, resolvePolicy as D, resolveConfig as E, decimalRateNanoUnits as F, priceOfficialDeepSeekUsage as I, resolveOfficialDeepSeekPrice as L, deepFreeze as M, COMPRESSION_PROFILES as N, CustomCompressionPolicySchema as O, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as P, getSavingsLedger as R, codePointLength as S, parseContextCompressionSettings as T, DEFAULTS as _, getLastIntentFold as a, charsForTokens as b, invalidateOnTaskChange as c, recordRecertified as d, recordScore as f, ContextCompressionSettingsSchema as g, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as h, getAdvisorState as i, assertNever as j, DEFAULT_CUSTOM_COMPRESSION_POLICY as k, observeIntentEnabled as l, AUTO_COMPACT_THRESHOLD_LIMITS as m, INTENT_GATE_GROWTH_TOKENS as n, getObservedIntentEnabled as o, setSummaryOverride as p, evaluateIntentGate as r, getSummaryOverride as s, INTENT_GATE_FLOOR_FRACTION as t, recordIntentFold as u, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as v, isValidAutoCompactThresholdPercent as w, charsToTokens as x, PRUNE_MARKER as y };
@@ -68,6 +68,13 @@ interface AutoCompactSettings {
68
68
  interface CodeSkeletonSettings {
69
69
  enabled: boolean;
70
70
  }
71
+ /**
72
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
73
+ * runtime: independent of every profile, default off.
74
+ */
75
+ interface IntentSummarySettings {
76
+ enabled: boolean;
77
+ }
71
78
  /** Browser-safe mirror of the runtime presetOptions section. */
72
79
  interface PresetOptionsSettings {
73
80
  readonly dedupeToolResults?: boolean;
@@ -98,6 +105,8 @@ interface ContextCompressionSettings {
98
105
  autoCompact: AutoCompactSettings;
99
106
  /** Code-skeleton reducer gate captured independently of `profile`. */
100
107
  codeSkeleton: CodeSkeletonSettings;
108
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
109
+ intentSummary: IntentSummarySettings;
101
110
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
102
111
  presetOptions?: PresetOptionsSettings;
103
112
  }