dsh-boost 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +141 -51
- package/README.md +115 -47
- package/dist/admission/usage.js +41 -7
- package/dist/admission/usage.js.map +1 -1
- package/dist/gate/decide.js +33 -2
- package/dist/gate/decide.js.map +1 -1
- package/dist/hooks/llm-stream.js +232 -58
- package/dist/hooks/llm-stream.js.map +1 -1
- package/dist/hooks/post-execute.js +206 -39
- package/dist/hooks/post-execute.js.map +1 -1
- package/dist/hooks/session-state.js +18 -8
- package/dist/hooks/session-state.js.map +1 -1
- package/dist/index.js +601 -72
- package/dist/index.js.map +1 -1
- package/dist/scope/doc.js.map +1 -1
- package/dist/scope/store.js +24 -9
- package/dist/scope/store.js.map +1 -1
- package/dist/tools/boost.js +82 -2
- package/dist/tools/boost.js.map +1 -1
- package/package.json +9 -5
- package/dist/admission/fixed-cost.d.ts +0 -23
- package/dist/admission/ledger.d.ts +0 -113
- package/dist/admission/retrieval.d.ts +0 -65
- package/dist/admission/usage.d.ts +0 -75
- package/dist/config.d.ts +0 -43
- package/dist/gate/binding.d.ts +0 -113
- package/dist/gate/decide.d.ts +0 -82
- package/dist/gate/guard.d.ts +0 -69
- package/dist/gate/invalidate.d.ts +0 -112
- package/dist/gate/plan.d.ts +0 -86
- package/dist/hooks/clock.d.ts +0 -68
- package/dist/hooks/execute.d.ts +0 -79
- package/dist/hooks/llm-stream.d.ts +0 -283
- package/dist/hooks/pending.d.ts +0 -89
- package/dist/hooks/post-execute.d.ts +0 -257
- package/dist/hooks/session-state.d.ts +0 -158
- package/dist/hooks/synthesize.d.ts +0 -74
- package/dist/host/loader.d.ts +0 -23
- package/dist/host/platform.d.ts +0 -18
- package/dist/host/root.d.ts +0 -25
- package/dist/projection/apply.d.ts +0 -174
- package/dist/projection/canonicalise.d.ts +0 -43
- package/dist/projection/counters.d.ts +0 -65
- package/dist/projection/truncate.d.ts +0 -47
- package/dist/prompt/protocol.d.ts +0 -45
- package/dist/receipts/store.d.ts +0 -198
- package/dist/scope/doc.d.ts +0 -117
- package/dist/scope/resolve.d.ts +0 -91
- package/dist/scope/store.d.ts +0 -135
- package/dist/selector/jev.d.ts +0 -93
- package/dist/tools/boost.d.ts +0 -380
- package/dist/tools/family.d.ts +0 -26
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
## 它解决什么
|
|
9
9
|
|
|
10
10
|
DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
|
|
11
|
-
`--silent` 时 npm 会把 `> dsh-boost@0.1.
|
|
11
|
+
`--silent` 时 npm 会把 `> dsh-boost@0.1.2 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
|
|
12
12
|
`node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
|
|
13
13
|
195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
|
|
14
14
|
(bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
|
|
@@ -26,18 +26,28 @@ DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的
|
|
|
26
26
|
(把上一步回执里的值直接搬进下一步参数)在实践中只对 `glob` 的单 token 输出有效;
|
|
27
27
|
`read` 与 `grep` 的输出带行号或是裸路径,标识符投影匹配不到,这些调用会退回模型。
|
|
28
28
|
|
|
29
|
+
多候选选择器**不读独立的模型配置**:它复用**边界请求**的 `provider` / `model` /
|
|
30
|
+
`reasoningEffort`(`src/index.ts` 的 `rememberRoute`,主来源是 `agent/pre-step` 的
|
|
31
|
+
`modelSelection`,`agent/request` 的解析结果只作回退),所以它不一定是廉价模型。要让它走
|
|
32
|
+
别的模型,只能在边界会话上换模型(宿主按 agent 选路由),或让计划只留一个候选(单候选
|
|
33
|
+
不调用选择器)。
|
|
34
|
+
|
|
29
35
|
v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**,按 raw `totalTokens` 计;
|
|
30
36
|
**3.5% 不是保底**——它是设计阶段对一个 300 会话语料做离线估算得到的下界,其中替换账的
|
|
31
37
|
2.70% 是**上限**,不能算进保底;诚实的净保底只有约 **0.4%**(投影侧毛额约 0.8% 减去每请求
|
|
32
38
|
固定开销约 0.4%)。这个区间不是保证,也不是从交付的 `session-snapshot.json` 能复算出来的
|
|
33
|
-
|
|
39
|
+
数字:快照按会话存了聚合计数,也存了每个会话的 `requestTokens` / `receiptChars` 数组、
|
|
40
|
+
`valueTransfer` / `whitelist` 计数,以及该会话按工具族归因的 `toolChars` 字符总量,但
|
|
41
|
+
**没有逐回执的族别字节**,估算所需的投影分项仍然凑不出来——交付物里**没有任何工具能复算它**。影子周也
|
|
34
42
|
**不能**把这个区间变成实测百分比:影子报告只输出四个比例(见「影子周」一节),没有总 token
|
|
35
43
|
分母,`boost status` 也只有绝对值;区间要被实测取代,得等后续版本补上分母统计。
|
|
36
44
|
|
|
37
45
|
## 前置条件
|
|
38
46
|
|
|
39
|
-
- Node.js `>=24.9.0`,DSH
|
|
40
|
-
`
|
|
47
|
+
- Node.js `>=24.9.0`,DSH `>=0.2.2-rc.4 <0.2.3-0`(**区间**,不是精确钉法;宿主按
|
|
48
|
+
`includePrerelease` 语义判定,不满足时会直接停用插件,而 `0.2.2-rc.5` 与本插件触及的宿主包
|
|
49
|
+
逐字节相同)。两者都在 `package.json` 的 `engines` 里;Node 下限对齐宿主
|
|
50
|
+
`@deepseek-ai/dsh@0.2.2-rc.4`。
|
|
41
51
|
- **本包不声明任何 peerDependencies**:安装它不会带出任何 `@deepseek-ai/*` 包,模块脱离它们也能
|
|
42
52
|
加载;运行时能力(`tokenMeter`、`spillStore`、估算器、页脚格式化器)由 DSH 宿主进程提供,
|
|
43
53
|
缺失时走降级(见「宿主依赖」)。
|
|
@@ -50,16 +60,26 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
|
|
|
50
60
|
`dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
|
|
51
61
|
|
|
52
62
|
```bash
|
|
53
|
-
# 从 registry
|
|
54
|
-
|
|
63
|
+
# 从 registry 安装:npmjs 上的 latest 是 0.1.2(本仓库 .npmrc 与 lockfile
|
|
64
|
+
# 也已钉在 npmjs,见下)
|
|
65
|
+
dsh plugin --profile <name> add dsh-boost@^0.1.2 --registry=https://registry.npmjs.org/
|
|
55
66
|
|
|
56
67
|
# 或从本地 checkout 安装(先构建;dist/ 不入库)
|
|
57
68
|
npm run build
|
|
58
69
|
dsh plugin --profile <name> add /absolute/path/to/dsh-boost
|
|
59
70
|
```
|
|
60
71
|
|
|
61
|
-
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.
|
|
62
|
-
|
|
72
|
+
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.2 --registry=https://registry.npmjs.org/`。
|
|
73
|
+
`dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
|
|
74
|
+
|
|
75
|
+
> **两个 registry 现在都到 0.1.2,`^0.1.2` 是安全的钉法。** `registry.npmjs.org` 与
|
|
76
|
+
> `registry.npmmirror.com` 各有四条版本记录:`0.1.2`(两边都是当前 `latest`)、`0.1.1`、
|
|
77
|
+
> `0.1.0`,以及首次发布时 npm 自动创建的占位版本 `0.0.0-stage`——**不要安装 `0.0.0-stage`**,
|
|
78
|
+
> 它不是可用构建。0.1.2 修掉了 scope 文件被静默覆盖的问题:坏 JSON(含非对象或数组)与
|
|
79
|
+
> 无法识别的版本不再被默认文档覆盖。请用 `dsh-boost@^0.1.2`(或 `@latest`)。本仓库已把 `.npmrc`
|
|
80
|
+
> 与 lockfile 钉在 npmjs,但**你机器上的全局 npm 配置**可能仍指向一个尚未同步 0.1.2 的镜像:
|
|
81
|
+
> 那是本机配置,不是本仓库的状态。在意 registry 时显式传
|
|
82
|
+
> `--registry=https://registry.npmjs.org/`;镜像滞后时,`@^0.1.2` 会在同步前解析失败。
|
|
63
83
|
|
|
64
84
|
包是 ESM(`"type": "module"`),`exports` 的 `.` 条目同时映射 `require` / `default`:Node ≥ 24.9
|
|
65
85
|
下 `require('dsh-boost')` 与 `import` 加载同一份代码,装好的包里**不做任何构建**(`files` 只带
|
|
@@ -79,17 +99,17 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
|
|
|
79
99
|
```
|
|
80
100
|
|
|
81
101
|
`workspaceIds` 为空时没有可见工作区:协议段不注入,投影与替换都原样放行,但每个工具调用
|
|
82
|
-
仍会记一条 `skip:no-scope`
|
|
102
|
+
仍会记一条 `skip:no-scope` 收据——但 PTC 内层调用(`exec.parent` 存在)与被取消的调用在 scope 门之前就返回,两条都不记。`boost` 工具本身是唯一的 scope 豁免,因此没有工作区时仍然
|
|
83
103
|
可以调用它来启用。
|
|
84
104
|
|
|
85
105
|
`boost` 是**模型工具,不是 shell 命令**——这个包没有 `bin`,启用全程都要在对话里让模型调用
|
|
86
|
-
它(status、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
|
|
106
|
+
它(status、scope-get、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
|
|
87
107
|
|
|
88
108
|
> 调用 boost 工具,参数 `{"cmd":"status"}`,把 JSON 结果给我。
|
|
89
109
|
|
|
90
110
|
首次 `status` 应看到 `ok: true`;`data.scope.workspaceIds` 为空、`revision` 为 `0`,`shadow` 为
|
|
91
|
-
`true`、`projection` 为 `"shadow"`,`counts`
|
|
92
|
-
|
|
111
|
+
`true`、`projection` 为 `"shadow"`,`counts` 为空(**仅限全新回执根**——`scan()` 读全部分片,同一 DSH home 里别的会话早先的
|
|
112
|
+
越界调用已经各记过一条 `skip:no-scope`)。首次 `status` 的 `degraded` 里**不会**因为 `scope.json`
|
|
93
113
|
缺失而出现 `ERR_SCOPE_READ_FAILED`:缺失是干净的默认值(`ENOENT` 不带降级码,
|
|
94
114
|
`src/scope/store.ts`);全新根目录且宿主能力齐全时,`degraded` 就是空数组。在 `status` 的
|
|
95
115
|
读取路径上,`ERR_SCOPE_READ_FAILED` 只表示文件**存在但读不出来**(权限、I/O、路径是目录
|
|
@@ -112,10 +132,13 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
|
|
|
112
132
|
```
|
|
113
133
|
|
|
114
134
|
- `workspaceIds` 是宿主的 workspace UUID,不是路径;宿主通过 workspace registry 把 agent 的
|
|
115
|
-
cwd 映射成这个 id。**发现 UUID
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
135
|
+
cwd 映射成这个 id。**发现 UUID 本身有摩擦**:要么问宿主/翻会话记录,要么自己读宿主的
|
|
136
|
+
`<hostDshHome>/storages/workspace.json` 的 `tables.workspaces`(id ↔ path 的映射表)——v1
|
|
137
|
+
没有任何命令替你做这件事。宿主的 home 解析顺序是「非空 `$DSH_HOME`(`~` 会展开)→
|
|
138
|
+
`~/.dsh`」,所以默认安装下文件是 `~/.dsh/storages/workspace.json`,**不是**
|
|
139
|
+
`$DSH_HOME/storages/workspace.json`(除非 `$DSH_HOME` 真的设了)。注意 `config.dshHome`
|
|
140
|
+
只移动插件的 `<dshHome>/boost`,不会移动宿主的这个文件。找不到 UUID 且是单用户机器时,
|
|
141
|
+
可以用 `"mode": "global"` 放开到所有**已定义**的工作区;没有工作区的会话仍然不可见。
|
|
119
142
|
- `baseRevision` 取你刚读到的 `data.scope.revision`(首次写入是 `0`)。这是 compare-and-swap:
|
|
120
143
|
revision 过期会返回 `ERR_SCOPE_REVISION_CONFLICT`,重读 `status` 再试。调用被调用方的取消
|
|
121
144
|
信号打断时返回 `ERR_SCOPE_ABORTED`:锁已释放、`scope.json` 原样未动,重读 `revision` 重试
|
|
@@ -166,17 +189,21 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
|
|
|
166
189
|
## 影子周
|
|
167
190
|
|
|
168
191
|
设计选择**影子优先**:先用一周只记账(不合成回合、不跳过调用,投影只记账不改内容),再决定
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
192
|
+
是否真的投影与替换。**「什么都不改」并不成立**:`boost` 工具 schema(399 token)只要插件装配
|
|
193
|
+
就常驻;只要有可见工作区,协议段(379 token)还会注入系统提示——推荐配置下每请求固定成本
|
|
194
|
+
**778**;多候选计划仍会**真实调用一次选择器**(一次独立的辅助模型请求)。影子周不省任何
|
|
195
|
+
token,它只产出下一节的四个比例;`selected + []` 下协议段为空,固定成本仍有 **399**。
|
|
172
196
|
|
|
173
197
|
其中 `saveableRatio`、`byFamily`、`candidateRecall` 能决定的是**替换侧是否值得打开**:
|
|
174
198
|
白名单能兑现多少替换决策、命中落在哪些工具族、候选集召回多高——也就是替换打开后会不会
|
|
175
|
-
|
|
176
|
-
|
|
199
|
+
真的触发、主要落在哪些族。它们**不能决定发布**:v1 按正常版本发布,不把影子期收益当发布
|
|
200
|
+
门;这个决定是**实现者在设计阶段做的,不是用户裁决**——用户只接受了为期一周的影子期,没有
|
|
201
|
+
裁定影子结果是否该当发布门。它们也**不能测出节省**:报告没有总 token 分母,
|
|
177
202
|
`retrievalUpperBound` 在影子期结构性为 `0`(它只统计 `projection:'on'` 的已应用投影取回),
|
|
178
|
-
|
|
179
|
-
|
|
203
|
+
连投影的取回损害都约束不了。投影的放行依据只有可见性契约(原文可经页脚取回),不是影子
|
|
204
|
+
标签,也**不是事后检测**:v1 没有误截检测器——`src/admission/retrieval.ts` 只按精确 locator
|
|
205
|
+
统计取回次数,设计稿 §6.1 也写明损害度量未交付、取回计数不是损害上界。唯一的护栏是模型
|
|
206
|
+
能取回原文;而「发生过取回」只是信号,不是「没有误截」的证明。
|
|
180
207
|
`scope.json` 里有两个独立开关:
|
|
181
208
|
|
|
182
209
|
| 开关 | 取值 | 行为 |
|
|
@@ -198,8 +225,8 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
|
|
|
198
225
|
是每一次替换决策,不只是白名单调用;影子期全族记账,bash/ssh 的潜力看 `byFamily`)、`byFamily`(按候选工具族的命中率)、
|
|
199
226
|
`candidateRecall`(候选集召回)、`retrievalUpperBound`(取回率上界;影子期没有真正投影,
|
|
200
227
|
结构上恒为 `0`)。
|
|
201
|
-
3.
|
|
202
|
-
后端可用后,保持 `shadow: true`,把 `projection` 改成 `'on'`:
|
|
228
|
+
3. **打开投影**:投影的放行不靠影子标签(依据是可见性契约:原文可经页脚取回;v1 没有
|
|
229
|
+
误截检测器),确认宿主 spill 后端可用后,保持 `shadow: true`,把 `projection` 改成 `'on'`:
|
|
203
230
|
|
|
204
231
|
```json
|
|
205
232
|
{ "cmd": "scope-set", "body": { "projection": "on" }, "baseRevision": 1 }
|
|
@@ -248,13 +275,13 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
|
|
|
248
275
|
字符按 Unicode 码点计。错误回执与超过 256 KiB 的回执不投影。
|
|
249
276
|
|
|
250
277
|
不变量不是 `triggerChars ≥ headChars + tailChars + 1`。真实替换串是 head line + head + 页脚 +
|
|
251
|
-
tail + 3 个换行;页脚由宿主 `formatSpillNotice`
|
|
252
|
-
|
|
253
|
-
`400 + 100 + 50(head line) +
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
locator 与数字位数浮动。
|
|
278
|
+
tail + 3 个换行;页脚由宿主 `formatSpillNotice` 生成:68 字符 locator 加宿主固定的 66 字符
|
|
279
|
+
retrieval hint 下,3 位省略字节数是 190 字符,5 位是 192 字符。grep/glob 默认 400+100 时:
|
|
280
|
+
`400 + 100 + 50(head line) + 190(页脚) + 3 = 743 > 700`(5 位计数时页脚 192、head line 里的数字也各长一位,实测 747–749)。于是刚过 700、
|
|
281
|
+
约 743 以下的回执会被 `truncate` 判定“可裁”,但 `projectApply` 组装后并不短于原文,直接返回
|
|
282
|
+
原文——这是死区,不是净亏。运行时的 `assembled.length >= text.length` 检查保证投影绝不会让
|
|
283
|
+
回执变长;要消除死区,把 `triggerChars` 提到至少这个和(例如 grep/glob 用 800),或缩小窗口。
|
|
284
|
+
页脚长度会随 locator 与数字位数浮动。
|
|
258
285
|
|
|
259
286
|
(`projection: 'shadow'` 定价只含 `(Omitted N bytes.)` 省略句,不含 locator/页脚全文,所以
|
|
260
287
|
影子账的 `after` 是下界;apply 路径在写入后还会再核对一次。)
|
|
@@ -305,20 +332,59 @@ plugin manager 才能把运行中的 entry 认成本包的行、通过 profile p
|
|
|
305
332
|
|
|
306
333
|
- `scope.json`——暴露面的唯一事实来源(version 2,带 revision)。
|
|
307
334
|
- `scope.lock`——写路径的短锁,正常写入结束后删除。
|
|
308
|
-
- `receipts/<encoded-session>.jsonl
|
|
309
|
-
|
|
335
|
+
- `receipts/<encoded-session>.jsonl`——追加式收据。**收据按“决定”写,不是每次调用都写**:
|
|
336
|
+
只有发生投影、替换决策(含 skip)或越界 `skip:no-scope` 时才落一行;一个没有计划的
|
|
337
|
+
`write` / `edit` 不产生任何收据,它的参数不会被记录。每行携带元数据、回执前 256 个码点的
|
|
338
|
+
preview(不存 stdout 全文)和该调用的绑定参数 `args`(模型所写:超过 2048 个码点时以
|
|
310
339
|
`args_truncated` 标记的截断 JSON 落盘;嵌套超过 64 层时以 `args_depth_truncated` 标记,
|
|
311
|
-
并把更深的子树换成 `{ "truncated_depth": 64 }
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
`
|
|
315
|
-
|
|
316
|
-
|
|
340
|
+
并把更深的子树换成 `{ "truncated_depth": 64 }`)。**只有替换类收据**另外携带计划 goal
|
|
341
|
+
(≤256 码点)与守卫(≤8 条,各 ≤300 码点):`kind:'substitute'`、
|
|
342
|
+
`kind:'substitute-settled'`,以及 `kind:'shadow'` 且 `code:'ok'` 的影子提交。
|
|
343
|
+
`kind:'shadow'` 不是替换专用——投影影子也写 `kind:'shadow'`,但带
|
|
344
|
+
`code:'projection-shadow'`,属于投影收据,没有 plan 证据。
|
|
345
|
+
**投影收据**(`kind:'projection'`、`code:'projected'`,以及投影影子)带 `before` /
|
|
346
|
+
`after` / `saved_projection_tokens` / `unit` / `estimate` / `horizon_steps`;没有 token
|
|
347
|
+
meter 时只有 `estimate:'unknown'`,三个数值字段整体省略。**取回收据**
|
|
348
|
+
(`kind:'projection'`、`code:'projection-retrieval'`)带 `locator` 与
|
|
349
|
+
`retrieval_call_tokens` / `retrieval_content_tokens` / `retrieval_tokens`;三个取回字段
|
|
350
|
+
只在这次取回被定价时写入,未定价时 `estimate` 为 `'unknown'`、字段省略。`skip` 收据只有
|
|
351
|
+
preview 与 args(`skip:no-scope` 连这两个都没有,只记工具名)。
|
|
352
|
+
|
|
353
|
+
当前分片超过 8 MiB 或 20,000 行时,下一次写入前轮转为 `<encoded-session>.1.jsonl`;只保留
|
|
354
|
+
当前分片和它的前一份(旧的 `.1` 被覆盖)。`boost status` 先读 `.1` 再读当前分片。256 分片
|
|
355
|
+
上限按**编码后的会话名**计数:轮转出的 `.1.jsonl` 与当前文件同属一个名字,不额外占名额,
|
|
356
|
+
但扫描会把该名字下的两份都读入。
|
|
317
357
|
|
|
318
358
|
`boost status` 的投影账按每条收据自己的 `horizon_steps` 重放;没有该字段的旧收据按当前
|
|
319
359
|
horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizon_steps` 报告当前
|
|
320
360
|
生效的 horizon(活动会话的最小值;没有历史时回落到 `horizonSteps`)。
|
|
321
361
|
|
|
362
|
+
`status.data` 里还有几个不在 `degraded` 里的状态/账目字段:
|
|
363
|
+
|
|
364
|
+
- `receipts_stopped`:收据连续写失败 3 次后为 `true`。此时替换被**整体拒绝**(fail-closed,
|
|
365
|
+
不再花选择器调用或预算),投影照常;所有账目是停写前的旧快照。恢复写盘并成功追加一行后
|
|
366
|
+
计数清零、该字段回到 `false`。它是唯一说出「收据已停写」的地方——没有对应的 `degraded` 码。
|
|
367
|
+
- `protocol_suppressed`:协议段在装配时被压掉的次数(不可见工作区、没有 agent 的诊断装配,
|
|
368
|
+
以及 `complete: true` 覆盖)。装配每请求都跑,所以只计数、不写收据。
|
|
369
|
+
- `projection_locator_evictions`:因每会话 locator 上限(512 个,最旧先丢)被丢弃的 locator
|
|
370
|
+
数;大于 0 表示取回账目有损。
|
|
371
|
+
- `projection_unknown_families`:带 `mcp__` 前缀、进入投影阶段但没有匹配到工具族的调用数;
|
|
372
|
+
`projection_unknown_tools` 是其中保留的未映射工具名及次数(最多 32 个),用来发现 mapper
|
|
373
|
+
缺口。
|
|
374
|
+
- `hasWorkspaceRegistry`:宿主是否**提供** `workspaceRegistry`(同样是存在性)。生产装配总是传入
|
|
375
|
+
这个键,所以它**总是布尔**:宿主没有该服务是 `false` + `ERR_HOST_NO_WORKSPACE_REGISTRY`;服务在但
|
|
376
|
+
`list()` 抛错是 `true` + `ERR_HOST_WORKSPACE_REGISTRY_BROKEN`——两种都让每个会话被判不可见,但
|
|
377
|
+
修法不同。只有直接构造 `boost` 依赖、完全不给宿主事实时该键才省略(测试场景)。
|
|
378
|
+
- `hasSpill`:宿主是否**提供** spill 后端(存在性,不是可用性)。服务缺失是 `false` +
|
|
379
|
+
`ERR_HOST_NO_SPILL`;服务在但不提供 `saveText` 时它**仍是 `true`**,同时 `degraded` 带
|
|
380
|
+
`ERR_HOST_SPILL_UNUSABLE`——能力事实在 `degraded` 里,不在这个布尔里。
|
|
381
|
+
- `saved`:兼容旧消费者的 camelCase 账目对象(`substitution` / `substitutionAvoided` /
|
|
382
|
+
`projectionGross` / `projectionNet` / `retrievals`),与顶层 snake_case 字段由同一次聚合派生。
|
|
383
|
+
旧投影收据(pre-T23b)没有 `saved_projection_tokens` 时,按收据里的 legacy `saved` 字段回退计价。
|
|
384
|
+
**两个替换数是一对区间,不是同一个量**:`substitution` 取被跳过请求的**下一**个真实请求的输入
|
|
385
|
+
(含被替换调用自己的结果,所以是**上界**);`substitutionAvoided` 取计划那一次请求的
|
|
386
|
+
`input + cacheRead + output`(不含被替换调用的结果,所以是**下界**)。真实节省落在两者之间。
|
|
387
|
+
|
|
322
388
|
`projection: 'on'` 时,完整原文在替换发生**之前**写入宿主的 spill 后端,页脚 locator 可以用
|
|
323
389
|
`read` / `grep` 取回。投影不会丢掉唯一副本;spill 写入失败就不替换(收据记
|
|
324
390
|
`projection-skipped:spill-failed`,页脚渲染失败记 `projection-skipped:footer-failed`;页脚
|
|
@@ -354,7 +420,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
|
|
|
354
420
|
|
|
355
421
|
## 宿主依赖
|
|
356
422
|
|
|
357
|
-
`inject` 是硬依赖:`tools`、`systemPrompt
|
|
423
|
+
`inject` 是硬依赖:`tools`、`systemPrompt`——缺任一,cordis 让插件停在 pending、不 apply(不是抛错,但对使用者而言效果相同:插件不工作)。`llm` 是软依赖(只有
|
|
358
424
|
选择器用),缺失时选择器以 `selector-unavailable` 退回,投影与替换的其余部分照常。
|
|
359
425
|
|
|
360
426
|
| 依赖 | 形态 | 缺失时 |
|
|
@@ -362,7 +428,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
|
|
|
362
428
|
| `workspaceRegistry` | 软(`ctx.get('workspaceRegistry')`) | **工作区不可见**:cwd 永远映射不到工作区 id,一切按 fail-closed 视为不可见——协议段不注入、投影与替换全部跳过,只有 `skip:no-scope` 收据在涨;`status.degraded` 带 `ERR_HOST_NO_WORKSPACE_REGISTRY`。这是**工作区本应可见却不可见**时的宿主能力解释,不是「装上了却什么都不发生」的唯一解释:默认 `selected + []` 按设计就是惰性的且不报错;缺 token meter 会拒绝真正的替换;`complete: true` 提示段会压掉协议段 |
|
|
363
429
|
| `tokenMeter` | 软(`ctx.get('tokenMeter')`) | 拒绝替换;投影仍可用,投影账记 `unknown`(不伪造数字);`status.degraded` 带 `ERR_HOST_NO_TOKENMETER` |
|
|
364
430
|
| `spillStore` | 软(`ctx.get('spillStore')`) | `projection: 'on'` 时超限回执不投影(保住证据),收据记 `projection-skipped:no-spill`;`status.degraded` 带 `ERR_HOST_NO_SPILL`(实时探测只在 on 模式;历史收据在任何模式下都会让它出现) |
|
|
365
|
-
| `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
|
|
431
|
+
| `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`;页脚渲染时抛错则记 `projection-skipped:footer-failed`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
|
|
366
432
|
| (spill 后端存在但写失败) | — | 每次 `saveText` 被拒:收据 `projection-skipped:spill-failed`,`status.degraded` 带 **`ERR_HOST_SPILL_FAILING`**。这是**第三种**状态,既不是「没有后端」也不是「没有页脚渲染器」——让操作者去「恢复 spill 包」会把一个已装好却报错的包当成没装 |
|
|
367
433
|
| `@deepseek-ai/dsh-token-meter/estimate` | 软(动态 import) | 固定开销无法测量,`fixedOverheadTokens` 为 `'unknown'`;`status.degraded` 带 `ERR_HOST_NO_ESTIMATOR` |
|
|
368
434
|
| `win32` 平台 | 运行时检查 `isPosixOnly()` | 拒绝替换,投影照常;`status.degraded` 带 `ERR_HOST_PLATFORM_UNSUPPORTED` |
|
|
@@ -404,10 +470,12 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
|
|
|
404
470
|
- **不去重、不合并工具调用**(设计 N5)——这条完全没开工,且 v1 **没有任何工具能测出重复
|
|
405
471
|
调用率**:设计稿里用来触发重启判定的「影子周重复率统计」没有交付,`shadow-report.mjs`
|
|
406
472
|
不产出它。
|
|
407
|
-
-
|
|
408
|
-
|
|
409
|
-
- **v1 不评判「结果更好」**:只有 token
|
|
410
|
-
|
|
473
|
+
- **影子周不省 token**:只记账(协议段照注入、选择器照调用),推荐配置下每请求仍固定花
|
|
474
|
+
778(`selected + []` 为 399);它的产出是四个比例,不是省下的 token。
|
|
475
|
+
- **v1 不评判「结果更好」**:只有 token 账目和一套**人工**的 20 任务回退流程(任务集不随包发布,
|
|
476
|
+
见 `docs/RELEASE.md` §3),没有任何质量指标;「替换后结果质量」在 v1 是不可判的。这套流程
|
|
477
|
+
本身也没交付完整:冒烟 runner(`test/regression/run.mjs`)与同一节的取回完整性检查都未实现,
|
|
478
|
+
`test/regression/` 只有 `.gitkeep`,因此 pass 谓词里的「无数据丢失」不变量在 v1 **未经核实**。
|
|
411
479
|
- **投影是截断,不是精炼**:它保留头尾、丢掉中段;账本里的 before/after token 差量的是
|
|
412
480
|
「变短」,不是「变相关」。被丢掉的中段可能正是下一步决策要用的内容——`projection: 'on'`
|
|
413
481
|
下原文可经页脚 locator 取回,但取回要花一次工具调用,且 v1 没有指标区分「精炼」与
|
|
@@ -437,7 +505,7 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
|
|
|
437
505
|
| [设计稿](docs/superpowers/specs/2026-11-18-dsh-token-efficiency-design.md) | 目标、证据、架构、契约、度量、风险、发布形态 |
|
|
438
506
|
| [宿主契约附录](docs/superpowers/plans/2026-11-18-host-contracts.md) | 逐条抄自宿主源码的接口准绳 |
|
|
439
507
|
| [三层委派研究](docs/research/2026-11-18-three-tier-delegation.md) | 缓存、路由阈值、压缩、校验的 25 条一手来源 |
|
|
440
|
-
| [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20
|
|
508
|
+
| [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回退流程(人工;任务集、runner 与取回完整性检查均未交付)、影子周与统计复算 |
|
|
441
509
|
|
|
442
510
|
## 许可证
|
|
443
511
|
|
package/dist/admission/usage.js
CHANGED
|
@@ -9,6 +9,14 @@
|
|
|
9
9
|
* next request is `'unknown'`; an interpolated number would be indistinguishable
|
|
10
10
|
* from a measurement once written to a receipt.
|
|
11
11
|
*
|
|
12
|
+
* That next request is not the avoided request: it also carries the executed
|
|
13
|
+
* call and its result, which the avoided request would not have seen. So
|
|
14
|
+
* `saved_input_tokens` is an **upper** estimate. `settle()` therefore also
|
|
15
|
+
* reports `avoided_total_tokens = before.input + before.cacheRead +
|
|
16
|
+
* before.output` — the whole request that produced the plan, which the avoided
|
|
17
|
+
* request would have carried (plus the plan) — as a **lower** estimate. Each
|
|
18
|
+
* side is `'unknown'` from its own sample, never a copy of the other's.
|
|
19
|
+
*
|
|
12
20
|
* The ledger keeps two request slots plus a mark: `latest`, the first request
|
|
13
21
|
* after the mark, and the mark itself — which holds the request that preceded
|
|
14
22
|
* it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
|
|
@@ -91,12 +99,25 @@ export class UsageLedger {
|
|
|
91
99
|
/**
|
|
92
100
|
* Consume the mark and report the substitution's measured cost.
|
|
93
101
|
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
102
|
+
* Two estimates of the avoided request, from the same pair of samples:
|
|
103
|
+
*
|
|
104
|
+
* - `saved_input_tokens` is the first after-mark request's `input +
|
|
105
|
+
* cacheRead`. That request is the next real one, so its input also carries
|
|
106
|
+
* the executed call and its result — tokens the avoided request would never
|
|
107
|
+
* have seen. It is therefore the **upper** estimate of the avoided input,
|
|
108
|
+
* and the plugin's headline number.
|
|
109
|
+
* - `avoided_total_tokens` is the pre-mark request's `input + cacheRead +
|
|
110
|
+
* output`: the whole request that produced the plan. The avoided request
|
|
111
|
+
* would have carried that request's context plus the plan, so this is a
|
|
112
|
+
* **lower** estimate of the avoided total. It includes output, hence
|
|
113
|
+
* "total", never "input".
|
|
114
|
+
*
|
|
115
|
+
* Each side is `'unknown'` when its own sample is missing or unusable —
|
|
116
|
+
* never a copy of the other request's numbers. `output_tokens` is the
|
|
117
|
+
* after-mark request's `output`, a third count never folded into either
|
|
118
|
+
* estimate. `cache_hit_delta` is the after-mark hit rate minus the pre-mark
|
|
119
|
+
* hit rate, `null` when either side cannot be told (a `null` delta means
|
|
120
|
+
* "cannot tell", not zero).
|
|
100
121
|
*
|
|
101
122
|
* A second `settle()` has nothing left to consume and reports the same
|
|
102
123
|
* `'unknown'` / `null`.
|
|
@@ -108,14 +129,27 @@ export class UsageLedger {
|
|
|
108
129
|
this.beforeMark = undefined;
|
|
109
130
|
this.afterMark = undefined;
|
|
110
131
|
this.candidateId = undefined;
|
|
132
|
+
// The lower estimate depends only on the pre-mark sample: a settlement
|
|
133
|
+
// with no after-mark request still knows how much that request would have
|
|
134
|
+
// had to replay, and reporting it cannot overstate anything.
|
|
135
|
+
const avoided = before !== undefined && usable(before)
|
|
136
|
+
? before.input + before.cacheRead + before.output
|
|
137
|
+
: undefined;
|
|
138
|
+
const avoidedTotal = avoided !== undefined && Number.isFinite(avoided) ? avoided : 'unknown';
|
|
111
139
|
if (after === undefined || !usable(after)) {
|
|
112
|
-
return {
|
|
140
|
+
return {
|
|
141
|
+
saved_input_tokens: 'unknown',
|
|
142
|
+
avoided_total_tokens: avoidedTotal,
|
|
143
|
+
cache_hit_delta: null,
|
|
144
|
+
output_tokens: 'unknown',
|
|
145
|
+
};
|
|
113
146
|
}
|
|
114
147
|
const afterRate = hitRate(after);
|
|
115
148
|
const beforeRate = hitRate(before);
|
|
116
149
|
const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null;
|
|
117
150
|
return {
|
|
118
151
|
saved_input_tokens: after.input + after.cacheRead,
|
|
152
|
+
avoided_total_tokens: avoidedTotal,
|
|
119
153
|
cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,
|
|
120
154
|
output_tokens: after.output,
|
|
121
155
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/admission/usage.ts"],"names":[],"mappings":"AAAA;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AK,GAAG,KAAK,CAAC,SAAS;YACjD,eAAe,EAAE,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACxE,aAAa,EAAE,KAAK,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC;CACF","sourcesContent":["/**\n * Usage pairing: turn two consecutive model requests into the measured saving\n * of one substitution (design §5.3).\n *\n * When the plugin substitutes a call, the model is not asked for that step, so\n * the next real request replays a shorter history. The saving is therefore\n * measured as the size of that next request — `input + cacheRead`, because the\n * host reports `inputTokens` excluding cache reads — never estimated. A missing\n * next request is `'unknown'`; an interpolated number would be indistinguishable\n * from a measurement once written to a receipt.\n *\n * The ledger keeps two request slots plus a mark: `latest`, the first request\n * after the mark, and the mark itself — which holds the request that preceded\n * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no\n * timers, no I/O, no host calls.\n *\n * @module dsh-boost/admission/usage\n */\n\n/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */\nexport interface Usage {\n input: number\n cacheRead: number\n output: number\n}\n\n/**\n * A sample is usable only when all three counts are finite and non-negative\n * and their input total does not overflow. A negative or non-finite count is a\n * protocol violation, and any arithmetic on it would invent `NaN` or\n * `Infinity` — a bogus number no receipt reader could tell from a measurement.\n * An unusable after-mark sample makes the whole settlement unusable; an\n * unusable pre-mark sample only loses the delta.\n */\nfunction usable(u: Usage): boolean {\n return (\n [u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&\n Number.isFinite(u.input + u.cacheRead)\n )\n}\n\n/**\n * Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`\n * when the rate cannot be told: no sample, an unusable sample, or a\n * non-positive denominator. Both sides of the delta go through this one\n * helper so they cannot drift.\n */\nfunction hitRate(u: Usage | undefined): number | null {\n if (u === undefined || !usable(u)) return null\n const denominator = u.input + u.cacheRead\n if (denominator <= 0) return null\n const rate = u.cacheRead / denominator\n return Number.isFinite(rate) ? rate : null\n}\n\n/**\n * Pairs two consecutive model requests around one substitution.\n *\n * The pairing target is the FIRST request after the mark, never the latest:\n * when a caller forgets to settle, a later unrelated request must not be\n * attributed to the substitution. `settle()` consumes the mark and clears the\n * pairing slots; `last()` is a pure reader and survives it.\n */\nexport class UsageLedger {\n private latest: Usage | undefined\n private hasMark = false\n private beforeMark: Usage | undefined\n private afterMark: Usage | undefined\n private candidateId: string | undefined\n\n /**\n * Record one real request. The first request after a mark claims the pairing\n * slot and keeps it; later requests only advance `last()`.\n */\n request(u: Usage): void {\n this.latest = u\n if (this.hasMark && this.afterMark === undefined) this.afterMark = u\n }\n\n /** Most recent request, or `undefined` before the first one. Never consumes. */\n last(): Usage | undefined {\n return this.latest\n }\n\n /**\n * Record that a substitution just happened.\n *\n * `candidateId` is kept only so the caller can pair `settle()` with the right\n * substitution receipt (`pendingCandidateId()`); it never changes the\n * arithmetic. A new mark discards any unconsumed pairing and starts over from\n * the current latest request.\n */\n markSubstituted(candidateId: string): void {\n this.hasMark = true\n this.beforeMark = this.latest\n this.afterMark = undefined\n this.candidateId = candidateId\n }\n\n /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */\n pendingCandidateId(): string | undefined {\n return this.candidateId\n }\n\n /**\n * Consume the mark and report the substitution's measured cost.\n *\n * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;\n * `output_tokens` is that request's `output`, a third count that is never\n * folded into input. Both are `'unknown'` when no usable request arrived after\n * the mark — never a copy of the previous request's numbers. `cache_hit_delta`\n * is the after-mark hit rate minus the pre-mark hit rate, `null` when either\n * side cannot be told (a `null` delta means \"cannot tell\", not zero).\n *\n * A second `settle()` has nothing left to consume and reports the same\n * `'unknown'` / `null`.\n */\n settle(): {\n saved_input_tokens: number | 'unknown'\n cache_hit_delta: number | null\n output_tokens: number | 'unknown'\n } {\n const after = this.hasMark ? this.afterMark : undefined\n const before = this.hasMark ? this.beforeMark : undefined\n this.hasMark = false\n this.beforeMark = undefined\n this.afterMark = undefined\n this.candidateId = undefined\n\n if (after === undefined || !usable(after)) {\n return { saved_input_tokens: 'unknown', cache_hit_delta: null, output_tokens: 'unknown' }\n }\n\n const afterRate = hitRate(after)\n const beforeRate = hitRate(before)\n const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null\n\n return {\n saved_input_tokens: after.input + after.cacheRead,\n cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,\n output_tokens: after.output,\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/admission/usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AASH;;;;;;;GAOG;AACH,SAAS,MAAM,CAAC,CAAQ;IACtB,OAAO,CACL,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC3E,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,SAAS,CAAC,CACvC,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,OAAO,CAAC,CAAoB;IACnC,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;QAAE,OAAO,IAAI,CAAA;IAC9C,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,SAAS,CAAA;IACzC,IAAI,WAAW,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACjC,MAAM,IAAI,GAAG,CAAC,CAAC,SAAS,GAAG,WAAW,CAAA;IACtC,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAA;AAC5C,CAAC;AAED;;;;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X,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC;YACpC,CAAC,CAAC,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM;YACjD,CAAC,CAAC,SAAS,CAAA;QACf,MAAM,YAAY,GAChB,OAAO,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAE,SAAmB,CAAA;QAEpF,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,OAAO;gBACL,kBAAkB,EAAE,SAAS;gBAC7B,oBAAoB,EAAE,YAAY;gBAClC,eAAe,EAAE,IAAI;gBACrB,aAAa,EAAE,SAAS;aACzB,CAAA;QACH,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAClC,MAAM,KAAK,GAAG,SAAS,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,CAAC,IAAI,CAAA;QAEvF,OAAO;YACL,kBAAkB,EAAE,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS;YACjD,oBAAoB,EAAE,YAAY;YAClC,eAAe,EAAE,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACxE,aAAa,EAAE,KAAK,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC;CACF","sourcesContent":["/**\n * Usage pairing: turn two consecutive model requests into the measured saving\n * of one substitution (design §5.3).\n *\n * When the plugin substitutes a call, the model is not asked for that step, so\n * the next real request replays a shorter history. The saving is therefore\n * measured as the size of that next request — `input + cacheRead`, because the\n * host reports `inputTokens` excluding cache reads — never estimated. A missing\n * next request is `'unknown'`; an interpolated number would be indistinguishable\n * from a measurement once written to a receipt.\n *\n * That next request is not the avoided request: it also carries the executed\n * call and its result, which the avoided request would not have seen. So\n * `saved_input_tokens` is an **upper** estimate. `settle()` therefore also\n * reports `avoided_total_tokens = before.input + before.cacheRead +\n * before.output` — the whole request that produced the plan, which the avoided\n * request would have carried (plus the plan) — as a **lower** estimate. Each\n * side is `'unknown'` from its own sample, never a copy of the other's.\n *\n * The ledger keeps two request slots plus a mark: `latest`, the first request\n * after the mark, and the mark itself — which holds the request that preceded\n * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no\n * timers, no I/O, no host calls.\n *\n * @module dsh-boost/admission/usage\n */\n\n/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */\nexport interface Usage {\n input: number\n cacheRead: number\n output: number\n}\n\n/**\n * A sample is usable only when all three counts are finite and non-negative\n * and their input total does not overflow. A negative or non-finite count is a\n * protocol violation, and any arithmetic on it would invent `NaN` or\n * `Infinity` — a bogus number no receipt reader could tell from a measurement.\n * An unusable after-mark sample makes the whole settlement unusable; an\n * unusable pre-mark sample only loses the delta.\n */\nfunction usable(u: Usage): boolean {\n return (\n [u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&\n Number.isFinite(u.input + u.cacheRead)\n )\n}\n\n/**\n * Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`\n * when the rate cannot be told: no sample, an unusable sample, or a\n * non-positive denominator. Both sides of the delta go through this one\n * helper so they cannot drift.\n */\nfunction hitRate(u: Usage | undefined): number | null {\n if (u === undefined || !usable(u)) return null\n const denominator = u.input + u.cacheRead\n if (denominator <= 0) return null\n const rate = u.cacheRead / denominator\n return Number.isFinite(rate) ? rate : null\n}\n\n/**\n * Pairs two consecutive model requests around one substitution.\n *\n * The pairing target is the FIRST request after the mark, never the latest:\n * when a caller forgets to settle, a later unrelated request must not be\n * attributed to the substitution. `settle()` consumes the mark and clears the\n * pairing slots; `last()` is a pure reader and survives it.\n */\nexport class UsageLedger {\n private latest: Usage | undefined\n private hasMark = false\n private beforeMark: Usage | undefined\n private afterMark: Usage | undefined\n private candidateId: string | undefined\n\n /**\n * Record one real request. The first request after a mark claims the pairing\n * slot and keeps it; later requests only advance `last()`.\n */\n request(u: Usage): void {\n this.latest = u\n if (this.hasMark && this.afterMark === undefined) this.afterMark = u\n }\n\n /** Most recent request, or `undefined` before the first one. Never consumes. */\n last(): Usage | undefined {\n return this.latest\n }\n\n /**\n * Record that a substitution just happened.\n *\n * `candidateId` is kept only so the caller can pair `settle()` with the right\n * substitution receipt (`pendingCandidateId()`); it never changes the\n * arithmetic. A new mark discards any unconsumed pairing and starts over from\n * the current latest request.\n */\n markSubstituted(candidateId: string): void {\n this.hasMark = true\n this.beforeMark = this.latest\n this.afterMark = undefined\n this.candidateId = candidateId\n }\n\n /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */\n pendingCandidateId(): string | undefined {\n return this.candidateId\n }\n\n /**\n * Consume the mark and report the substitution's measured cost.\n *\n * Two estimates of the avoided request, from the same pair of samples:\n *\n * - `saved_input_tokens` is the first after-mark request's `input +\n * cacheRead`. That request is the next real one, so its input also carries\n * the executed call and its result — tokens the avoided request would never\n * have seen. It is therefore the **upper** estimate of the avoided input,\n * and the plugin's headline number.\n * - `avoided_total_tokens` is the pre-mark request's `input + cacheRead +\n * output`: the whole request that produced the plan. The avoided request\n * would have carried that request's context plus the plan, so this is a\n * **lower** estimate of the avoided total. It includes output, hence\n * \"total\", never \"input\".\n *\n * Each side is `'unknown'` when its own sample is missing or unusable —\n * never a copy of the other request's numbers. `output_tokens` is the\n * after-mark request's `output`, a third count never folded into either\n * estimate. `cache_hit_delta` is the after-mark hit rate minus the pre-mark\n * hit rate, `null` when either side cannot be told (a `null` delta means\n * \"cannot tell\", not zero).\n *\n * A second `settle()` has nothing left to consume and reports the same\n * `'unknown'` / `null`.\n */\n settle(): {\n saved_input_tokens: number | 'unknown'\n avoided_total_tokens: number | 'unknown'\n cache_hit_delta: number | null\n output_tokens: number | 'unknown'\n } {\n const after = this.hasMark ? this.afterMark : undefined\n const before = this.hasMark ? this.beforeMark : undefined\n this.hasMark = false\n this.beforeMark = undefined\n this.afterMark = undefined\n this.candidateId = undefined\n\n // The lower estimate depends only on the pre-mark sample: a settlement\n // with no after-mark request still knows how much that request would have\n // had to replay, and reporting it cannot overstate anything.\n const avoided =\n before !== undefined && usable(before)\n ? before.input + before.cacheRead + before.output\n : undefined\n const avoidedTotal =\n avoided !== undefined && Number.isFinite(avoided) ? avoided : ('unknown' as const)\n\n if (after === undefined || !usable(after)) {\n return {\n saved_input_tokens: 'unknown',\n avoided_total_tokens: avoidedTotal,\n cache_hit_delta: null,\n output_tokens: 'unknown',\n }\n }\n\n const afterRate = hitRate(after)\n const beforeRate = hitRate(before)\n const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null\n\n return {\n saved_input_tokens: after.input + after.cacheRead,\n avoided_total_tokens: avoidedTotal,\n cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,\n output_tokens: after.output,\n }\n }\n}"]}
|
package/dist/gate/decide.js
CHANGED
|
@@ -22,7 +22,11 @@
|
|
|
22
22
|
* 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`
|
|
23
23
|
* has nothing to verify, so it is not substitution potential either. If
|
|
24
24
|
* every survivor is trivial (including the empty plan, vacuously), the
|
|
25
|
-
* answer is `guard-trivial`.
|
|
25
|
+
* answer is `guard-trivial`. **Step admission follows (row 7).** When the
|
|
26
|
+
* caller supplies this step's `ResolvedToolSet` predicate, a candidate whose
|
|
27
|
+
* tool it does not admit is dropped before the selector is paid for: the
|
|
28
|
+
* host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the
|
|
29
|
+
* ordinary `no-candidate`.
|
|
26
30
|
* 3. **Bind, then guard, each remaining candidate in plan order.** Binding
|
|
27
31
|
* failure drops the candidate (it does not abort the plan); only a bound
|
|
28
32
|
* candidate has its guards evaluated. Guards read the receipt for
|
|
@@ -74,6 +78,29 @@ function whitelisted(whitelist) {
|
|
|
74
78
|
return kept;
|
|
75
79
|
};
|
|
76
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Step-admission filter (row 7).
|
|
83
|
+
*
|
|
84
|
+
* The host's `ResolvedToolSet` is this step's dispatch admission. A candidate
|
|
85
|
+
* whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the
|
|
86
|
+
* plugin had already paid for the selector and taken a budget step, so it is
|
|
87
|
+
* dropped here, before both. An emptied list falls through to `no-candidate`:
|
|
88
|
+
* the plan had candidates and none survived, exactly like a failed guard.
|
|
89
|
+
*
|
|
90
|
+
* A throwing membership read drops that candidate: an unverifiable tool is not
|
|
91
|
+
* one this plugin may dispatch, and dropping under-reports instead of producing
|
|
92
|
+
* a call the host rejects.
|
|
93
|
+
*/
|
|
94
|
+
function admittedBy(admitted) {
|
|
95
|
+
return (candidates) => candidates.filter((candidate) => {
|
|
96
|
+
try {
|
|
97
|
+
return admitted(candidate.tool);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
77
104
|
/**
|
|
78
105
|
* Trivial-candidate filter (rule 3).
|
|
79
106
|
*
|
|
@@ -154,7 +181,11 @@ function resolve(survivors) {
|
|
|
154
181
|
export function decide(input) {
|
|
155
182
|
const filters = input.shadow
|
|
156
183
|
? [nonTrivial]
|
|
157
|
-
: [
|
|
184
|
+
: [
|
|
185
|
+
whitelisted(input.whitelist),
|
|
186
|
+
nonTrivial,
|
|
187
|
+
...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),
|
|
188
|
+
];
|
|
158
189
|
const narrowed = narrow(input.plan.steps, filters);
|
|
159
190
|
if (!Array.isArray(narrowed))
|
|
160
191
|
return narrowed;
|
package/dist/gate/decide.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decide.js","sourceRoot":"","sources":["../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AAI,EAAE,KAAK,CAAC,IAAI;gBAChB,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;SACJ,CAAA;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAA;AAC5E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CAAC,KAMtB;IACC,MAAM,OAAO,GAAsB,KAAK,CAAC,MAAM;QAC7C,CAAC,CAAC,CAAC,UAAU,CAAC;QACd,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,UAAU,CAAC,CAAA;IAC9C,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC7C,OAAO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [whitelisted(input.whitelist), nonTrivial]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EAAE,WAAW,EAA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AI,EAAE,cAAc;YACpB,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;gBACpC,GAAG,KAAK,CAAC,SAAS;gBAClB,IAAI,EAAE,KAAK,CAAC,IAAI;gBAChB,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;SACJ,CAAA;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAA;AAC5E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CAAC,KAgBtB;IACC,MAAM,OAAO,GAAsB,KAAK,CAAC,MAAM;QAC7C,CAAC,CAAC,CAAC,UAAU,CAAC;QACd,CAAC,CAAC;YACE,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC;YAC5B,UAAU;YACV,GAAG,CAAC,KAAK,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;SACtE,CAAA;IACL,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC7C,OAAO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`. **Step admission follows (row 7).** When the\n * caller supplies this step's `ResolvedToolSet` predicate, a candidate whose\n * tool it does not admit is dropped before the selector is paid for: the\n * host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the\n * ordinary `no-candidate`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Step-admission filter (row 7).\n *\n * The host's `ResolvedToolSet` is this step's dispatch admission. A candidate\n * whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the\n * plugin had already paid for the selector and taken a budget step, so it is\n * dropped here, before both. An emptied list falls through to `no-candidate`:\n * the plan had candidates and none survived, exactly like a failed guard.\n *\n * A throwing membership read drops that candidate: an unverifiable tool is not\n * one this plugin may dispatch, and dropping under-reports instead of producing\n * a call the host rejects.\n */\nfunction admittedBy(admitted: (tool: string) => boolean): Filter {\n return (candidates) =>\n candidates.filter((candidate) => {\n try {\n return admitted(candidate.tool)\n } catch {\n return false\n }\n })\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n /**\n * Whether this step's `ResolvedToolSet` admits a tool (row 7).\n *\n * `undefined` means the admission evidence is unavailable (an embedded or\n * legacy call site); the caller proceeds and records the missing evidence\n * itself, because refusing on absence would silently disable substitution on\n * paths it cannot enumerate. Shadow mode ignores the predicate: shadow\n * measures potential, not dispatchability.\n */\n admitted?: (tool: string) => boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [\n whitelisted(input.whitelist),\n nonTrivial,\n ...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),\n ]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}
|