@zhushanwen/pi-subagent-workflow 8.5.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/package.json +7 -6
  2. package/src/execution/__tests__/bg-notify-render.test.ts +73 -0
  3. package/src/execution/__tests__/chat-engine-routing.test.ts +6 -2
  4. package/src/execution/__tests__/delivery-methods.test.ts +38 -1
  5. package/src/execution/__tests__/execute-options-mapper.test.ts +11 -0
  6. package/src/execution/__tests__/execution-record.test.ts +110 -0
  7. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  8. package/src/execution/__tests__/format-schema-instruction.test.ts +63 -32
  9. package/src/execution/__tests__/helpers/spawn-mock.ts +4 -0
  10. package/src/execution/__tests__/index-session-start.test.ts +86 -7
  11. package/src/execution/__tests__/lifecycle-manager.test.ts +46 -0
  12. package/src/execution/__tests__/list-fields.test.ts +45 -14
  13. package/src/execution/__tests__/model-resolver.test.ts +57 -5
  14. package/src/execution/__tests__/notifier-flush.test.ts +64 -26
  15. package/src/execution/__tests__/notify-ledger.test.ts +826 -0
  16. package/src/execution/__tests__/output-collector.test.ts +299 -2
  17. package/src/execution/__tests__/rpc-mode.test.ts +1 -1
  18. package/src/execution/__tests__/run-spawn-edges.test.ts +44 -1
  19. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  20. package/src/execution/__tests__/session-runner-schema-env.test.ts +39 -0
  21. package/src/execution/__tests__/spawn-args.test.ts +37 -26
  22. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  23. package/src/execution/__tests__/subprocess-agent-runner.test.ts +94 -1
  24. package/src/execution/__tests__/timeout-integration.test.ts +220 -2
  25. package/src/execution/__tests__/tool-action.test.ts +92 -1
  26. package/src/execution/agent-registry.ts +6 -0
  27. package/src/execution/argv-mirror.ts +5 -1
  28. package/src/execution/concurrency-pool.ts +1 -1
  29. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +13 -0
  30. package/src/execution/engine/engines/zcode/zcode-engine.ts +11 -1
  31. package/src/execution/engine/types.ts +6 -1
  32. package/src/execution/execute-options-mapper.ts +8 -7
  33. package/src/execution/execution-record.ts +60 -1
  34. package/src/execution/lifecycle-manager.ts +23 -1
  35. package/src/execution/model-config-service.ts +16 -1
  36. package/src/execution/model-resolver.ts +31 -59
  37. package/src/execution/notifier.ts +105 -35
  38. package/src/execution/notify-ledger.ts +580 -0
  39. package/src/execution/output-collector.ts +143 -3
  40. package/src/execution/session-runner.ts +304 -71
  41. package/src/execution/subagent-service.ts +24 -2
  42. package/src/execution/subprocess-agent-runner.ts +14 -0
  43. package/src/execution/types.ts +68 -5
  44. package/src/execution/ui-request-queue.ts +14 -4
  45. package/src/index.ts +54 -1
  46. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +157 -0
  47. package/src/interface/__tests__/subagent-tool-prompt.test.ts +12 -0
  48. package/src/interface/bg-notify-render.ts +33 -12
  49. package/src/interface/helpers.ts +2 -2
  50. package/src/interface/subagent-actions.ts +26 -9
  51. package/src/interface/subagent-tool-schema.ts +156 -0
  52. package/src/interface/subagent-tool.ts +56 -125
  53. package/src/interface/subagents.ts +2 -2
  54. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +16 -3
  55. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -6
  56. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -5
  57. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +89 -4
  58. package/src/orchestration/__tests__/execute-agent-call.test.ts +137 -0
  59. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +150 -0
  60. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +202 -0
  61. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +326 -3
  62. package/src/orchestration/__tests__/lifecycle.test.ts +41 -7
  63. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  64. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +57 -3
  65. package/src/orchestration/__tests__/skill-discovery.test.ts +44 -0
  66. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  67. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +43 -0
  68. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +21 -2
  69. package/src/orchestration/agent-opts-resolver.ts +104 -23
  70. package/src/orchestration/error-recovery.ts +189 -33
  71. package/src/orchestration/execute-agent-call.ts +39 -0
  72. package/src/orchestration/jsonl-run-store.ts +121 -7
  73. package/src/orchestration/launcher.ts +60 -15
  74. package/src/orchestration/lifecycle.ts +10 -7
  75. package/src/orchestration/models/__tests__/budget.test.ts +1 -61
  76. package/src/orchestration/models/budget.ts +5 -35
  77. package/src/orchestration/models/run-runtime.ts +24 -9
  78. package/src/orchestration/models/types.ts +9 -0
  79. package/src/orchestration/script-lint.ts +1 -1
  80. package/src/orchestration/skill-discovery.ts +31 -8
  81. package/src/orchestration/worker-script-builder.ts +16 -3
  82. package/src/shared/__tests__/model-ref.test.ts +306 -0
  83. package/src/shared/__tests__/schema-jsonify.test.ts +1 -1
  84. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  85. package/src/shared/model-ref.ts +286 -0
  86. package/src/shared/schema-env.ts +44 -0
  87. package/src/shared/schema-jsonify.ts +6 -4
  88. package/src/shared/timer-delay.ts +54 -0
  89. package/workflows/review-fix-loop-utils.cjs +9 -7
  90. package/workflows/review-fix-loop.js +20 -12
  91. package/src/orchestration/__tests__/concurrency-gate.test.ts +0 -125
  92. package/src/orchestration/concurrency-gate.ts +0 -69
@@ -0,0 +1,306 @@
1
+ // src/shared/__tests__/model-ref.test.ts
2
+ //
3
+ // [U1 ModelRef 全等裁决] assertCanonicalModelRef / modelRefFromVerified 单测族。
4
+ // 设计权威:docs/design/subagent-dispatch-reliability.md §3.3 D1(规则①~⑤含孪生守卫)、D2(继承路径豁免口径)。
5
+ //
6
+ // P-A2(实施期门):孪生守卫行为验证——含孪生的 registry 快照实测拒单路径 +
7
+ // 无孪生快照实测放行路径。「有孪生仍放行」= 守卫失效,阻断合入。
8
+
9
+ import { describe, expect, it } from "vitest";
10
+
11
+ import {
12
+ type ModelRefSource,
13
+ assertCanonicalModelRef,
14
+ assertThinkingLevel,
15
+ modelRefFromVerified,
16
+ stripThinkingSuffix,
17
+ THINKING_ORDER,
18
+ } from "../model-ref.ts";
19
+
20
+ // ============================================================
21
+ // helpers
22
+ // ============================================================
23
+
24
+ /** registry 快照构造(getAvailable 顺序即判定顺序)。 */
25
+ function makeSource(entries: ReadonlyArray<{ provider: string; id: string }>): ModelRefSource {
26
+ return { getAvailable: () => entries };
27
+ }
28
+
29
+ /** 基线快照:模拟真实 registry 形态(大小写混合 id + 无关条目)。 */
30
+ const BASELINE: ReadonlyArray<{ provider: string; id: string }> = [
31
+ { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
32
+ { provider: "zai-coding-cn", id: "GLM-5.3" },
33
+ { provider: "xiaomi-token-plan-cn", id: "mimo-v2.5-pro" },
34
+ { provider: "deepseek", id: "deepseek-v4-pro" },
35
+ ];
36
+
37
+ // ============================================================
38
+ // 全等放行(规则③)+ 无孪生快照(P-A2 放行路径)
39
+ // ============================================================
40
+
41
+ describe("assertCanonicalModelRef — exact match passes (rule ③)", () => {
42
+ it("全等命中 → 返回 {provider, id},与 registry 条目逐字段全等", () => {
43
+ const ref = assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash", makeSource(BASELINE));
44
+ expect(ref).toEqual({ provider: "zai-coding-cn", id: "GLM-5.3-Flash" });
45
+ });
46
+
47
+ it("P-A2 放行路径:无孪生快照下全等写法放行(含大小写差异的 id 原样保留)", () => {
48
+ // 快照中该 id 仅一种大小写形态(GLM-5.3-Flash ≠ glm-5.3,后者是不同 id 而非孪生)
49
+ const ref = assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash", makeSource(BASELINE));
50
+ expect(ref.id).toBe("GLM-5.3-Flash");
51
+ expect(ref.provider).toBe("zai-coding-cn");
52
+ });
53
+
54
+ it("无关大小写的不同 id(GLM-5.3 vs GLM-5.3-Flash)不构成孪生,全等命中各自放行", () => {
55
+ const source = makeSource(BASELINE);
56
+ expect(assertCanonicalModelRef("zai-coding-cn/GLM-5.3", source)).toEqual({
57
+ provider: "zai-coding-cn",
58
+ id: "GLM-5.3",
59
+ });
60
+ });
61
+ });
62
+
63
+ // ============================================================
64
+ // 非全等同步拒单(规则②⑤)+ case variant 首位建议
65
+ // ============================================================
66
+
67
+ describe("assertCanonicalModelRef — non-exact rejected synchronously (rule ⑤)", () => {
68
+ it("小写变体输入 → 同步抛错(不采纳、不改写),错误含原始输入", () => {
69
+ expect(() =>
70
+ assertCanonicalModelRef("zai-coding-cn/glm-5.3-flash", makeSource(BASELINE)),
71
+ ).toThrow(/is not a registry entry/);
72
+ });
73
+
74
+ it("case variant 是首个建议且标注 ← case variant(S2 负面路径)", () => {
75
+ let msg = "";
76
+ try {
77
+ assertCanonicalModelRef("zai-coding-cn/glm-5.3-flash", makeSource(BASELINE), { source: "paramOverride" });
78
+ } catch (e) {
79
+ msg = (e as Error).message;
80
+ }
81
+ expect(msg).toMatch(/is not a registry entry/);
82
+ expect(msg).toContain('Model "zai-coding-cn/glm-5.3-flash" (paramOverride)');
83
+ expect(msg).toMatch(/Registry match is case-sensitive/);
84
+ expect(msg).toMatch(/Did you mean one of these\?/);
85
+ // case variant 排首位并标注
86
+ const didYouMeanIdx = msg.indexOf("Did you mean one of these?");
87
+ const variantLine = msg.indexOf("zai-coding-cn/GLM-5.3-Flash ← case variant of \"glm-5.3-flash\"");
88
+ expect(variantLine).toBeGreaterThan(didYouMeanIdx);
89
+ // 其他模糊候选在 case variant 之后
90
+ const otherIdx = msg.indexOf("Other models you may have meant");
91
+ expect(otherIdx).toBeGreaterThan(variantLine);
92
+ expect(msg).toContain("zai-coding-cn/GLM-5.3");
93
+ });
94
+
95
+ it("错误末尾附「省略 model 继承主 agent」指引", () => {
96
+ let msg = "";
97
+ try {
98
+ assertCanonicalModelRef("zai-coding-cn/glm-5.3-flash", makeSource(BASELINE));
99
+ } catch (e) {
100
+ msg = (e as Error).message;
101
+ }
102
+ expect(msg).toMatch(/Or omit the `model` param to inherit the main agent model\./);
103
+ });
104
+
105
+ it("provider 大小写不同(Zai-Coding-CN)→ 不命中(provider 精确匹配,规则②)", () => {
106
+ let msg = "";
107
+ try {
108
+ assertCanonicalModelRef("Zai-Coding-CN/GLM-5.3-Flash", makeSource(BASELINE));
109
+ } catch (e) {
110
+ msg = (e as Error).message;
111
+ }
112
+ expect(msg).toMatch(/is not a registry entry/);
113
+ // provider 拼写相近 → general 候选命中
114
+ expect(msg).toMatch(/Other models you may have meant/);
115
+ });
116
+
117
+ it("同 provider 但 id 不存在 → provider 相似度候选(同 provider 下其他条目)", () => {
118
+ let msg = "";
119
+ try {
120
+ assertCanonicalModelRef("zai-coding-cn/nonexistent-probe", makeSource(BASELINE), { source: "agentConfig" });
121
+ } catch (e) {
122
+ msg = (e as Error).message;
123
+ }
124
+ expect(msg).toMatch(/is not a registry entry/);
125
+ expect(msg).not.toMatch(/Did you mean/);
126
+ expect(msg).toMatch(/Other models you may have meant/);
127
+ expect(msg).toContain("zai-coding-cn/GLM-5.3-Flash");
128
+ expect(msg).toContain("(agentConfig)");
129
+ });
130
+
131
+ it("provider 与 id 均无相似物 → 列合法串全集 + 继承指引(S2 前者路径)", () => {
132
+ let msg = "";
133
+ try {
134
+ assertCanonicalModelRef("ghost-provider/zzz-unknown", makeSource(BASELINE));
135
+ } catch (e) {
136
+ msg = (e as Error).message;
137
+ }
138
+ expect(msg).toMatch(/is not a registry entry/);
139
+ expect(msg).not.toMatch(/Did you mean/);
140
+ expect(msg).toMatch(/No similar models found\./);
141
+ expect(msg).toMatch(/Available models:/);
142
+ // 合法串全集(canonical 形态,可复制)
143
+ expect(msg).toContain("zai-coding-cn/GLM-5.3-Flash");
144
+ expect(msg).toContain("xiaomi-token-plan-cn/mimo-v2.5-pro");
145
+ expect(msg).toMatch(/Or omit the `model` param to inherit the main agent model\./);
146
+ });
147
+
148
+ it("无 slash / 空 id → 同步拒单(结构非法)", () => {
149
+ const source = makeSource(BASELINE);
150
+ expect(() => assertCanonicalModelRef("no-slash", source)).toThrow(/is not a registry entry/);
151
+ expect(() => assertCanonicalModelRef("only-provider/", source)).toThrow(/is not a registry entry/);
152
+ });
153
+
154
+ it("空 registry → 明确提示 + 继承指引", () => {
155
+ let msg = "";
156
+ try {
157
+ assertCanonicalModelRef("p/m", makeSource([]));
158
+ } catch (e) {
159
+ msg = (e as Error).message;
160
+ }
161
+ expect(msg).toMatch(/Registry has no available models\./);
162
+ expect(msg).toMatch(/Or omit the `model` param/);
163
+ });
164
+ });
165
+
166
+ // ============================================================
167
+ // strip thinking 后缀(规则①)
168
+ // ============================================================
169
+
170
+ describe("assertCanonicalModelRef — strips legal thinking suffix (rule ①)", () => {
171
+ it('":xhigh" 后缀剥离后全等命中', () => {
172
+ const ref = assertCanonicalModelRef("deepseek/deepseek-v4-pro:xhigh", makeSource(BASELINE));
173
+ expect(ref).toEqual({ provider: "deepseek", id: "deepseek-v4-pro" });
174
+ });
175
+
176
+ it('":max" 后缀剥离后全等命中(THINKING_ORDER 含 max)', () => {
177
+ const ref = assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash:max", makeSource(BASELINE));
178
+ expect(ref.id).toBe("GLM-5.3-Flash");
179
+ });
180
+
181
+ it('非白名单后缀(":foo")不剥离 → 未命中拒单', () => {
182
+ expect(() =>
183
+ assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash:foo", makeSource(BASELINE)),
184
+ ).toThrow(/is not a registry entry/);
185
+ });
186
+ });
187
+
188
+ // ============================================================
189
+ // 孪生守卫(规则④)—— P-A2 拒单路径
190
+ // ============================================================
191
+
192
+ describe("assertCanonicalModelRef — twin guard (rule ④, P-A2)", () => {
193
+ /** 含大小写孪生的 registry 快照(模拟 models-store 刷新后 GLM-5.3-Flash 与 glm-5.3-flash 并存)。 */
194
+ const TWIN_SNAPSHOT: ReadonlyArray<{ provider: string; id: string }> = [
195
+ { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
196
+ { provider: "zai-coding-cn", id: "glm-5.3-flash" },
197
+ { provider: "deepseek", id: "deepseek-v4-pro" },
198
+ ];
199
+
200
+ it("P-A2 拒单路径:有孪生仍放行 = 守卫失效——全等命中(大写形态)也必须拒绝", () => {
201
+ let msg = "";
202
+ try {
203
+ // 输入与快照条目逐字符全等,但 registry 存在 case-insensitive 相等的另一条目
204
+ assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash", makeSource(TWIN_SNAPSHOT));
205
+ } catch (e) {
206
+ msg = (e as Error).message;
207
+ }
208
+ expect(msg).toContain('Model "zai-coding-cn/GLM-5.3-Flash" matches a registry entry exactly');
209
+ expect(msg).toMatch(
210
+ /registry contains ambiguous case variants for zai-coding-cn\/GLM-5\.3-Flash: \[zai-coding-cn\/GLM-5\.3-Flash, zai-coding-cn\/glm-5\.3-flash\]/,
211
+ );
212
+ // 恢复指引:清理重复条目后重试
213
+ expect(msg).toMatch(/Recovery: remove the duplicate case variant from models\.json/);
214
+ expect(msg).toMatch(/then retry with the exact registry string\./);
215
+ });
216
+
217
+ it("P-A2 拒单路径:孪生快照下小写全等形态同样拒绝(两个方向都不放行)", () => {
218
+ expect(() =>
219
+ assertCanonicalModelRef("zai-coding-cn/glm-5.3-flash", makeSource(TWIN_SNAPSHOT)),
220
+ ).toThrow(/ambiguous case variants/);
221
+ });
222
+
223
+ it("无孪生快照下同串放行(守卫零误伤)", () => {
224
+ const ref = assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash", makeSource(BASELINE));
225
+ expect(ref.id).toBe("GLM-5.3-Flash");
226
+ });
227
+
228
+ it("不同 provider 下的同形 id 不构成孪生(provider 精确作用域)", () => {
229
+ const snapshot = [
230
+ { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
231
+ { provider: "other-cn", id: "glm-5.3-flash" },
232
+ ];
233
+ const ref = assertCanonicalModelRef("zai-coding-cn/GLM-5.3-Flash", makeSource(snapshot));
234
+ expect(ref.id).toBe("GLM-5.3-Flash");
235
+ });
236
+ });
237
+
238
+ // ============================================================
239
+ // 继承路径包装(D2 豁免口径):modelRefFromVerified
240
+ // ============================================================
241
+
242
+ describe("modelRefFromVerified — ctxModel inheritance path (D2)", () => {
243
+ it("无孪生 → 包装为 ModelRef({provider, id} 形态,供 ${provider}/${id} 拼接)", () => {
244
+ const ref = modelRefFromVerified(
245
+ { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
246
+ makeSource(BASELINE),
247
+ );
248
+ expect(ref).toEqual({ provider: "zai-coding-cn", id: "GLM-5.3-Flash" });
249
+ });
250
+
251
+ it("豁免存在性复查:ctxModel 不在 registry 快照中仍放行(运行时已验证)", () => {
252
+ // registry 为空(快照过期等)不阻塞继承——缺省继承是输入缺省而非变体放行
253
+ const ref = modelRefFromVerified(
254
+ { provider: "runtime-only", id: "live-model" },
255
+ makeSource([]),
256
+ );
257
+ expect(ref).toEqual({ provider: "runtime-only", id: "live-model" });
258
+ });
259
+
260
+ it("P-A2 双路径生效:含孪生快照下继承路径同样拒绝(豁免的只是存在性复查,不是孪生守卫)", () => {
261
+ const TWIN_SNAPSHOT = [
262
+ { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
263
+ { provider: "zai-coding-cn", id: "glm-5.3-flash" },
264
+ ];
265
+ expect(() =>
266
+ modelRefFromVerified({ provider: "zai-coding-cn", id: "GLM-5.3-Flash" }, makeSource(TWIN_SNAPSHOT)),
267
+ ).toThrow(/ambiguous case variants/);
268
+ });
269
+ });
270
+
271
+ // ============================================================
272
+ // stripThinkingSuffix / assertThinkingLevel
273
+ // ============================================================
274
+
275
+ describe("stripThinkingSuffix", () => {
276
+ it("剥白名单后缀", () => {
277
+ expect(stripThinkingSuffix("p/m:high")).toBe("p/m");
278
+ expect(stripThinkingSuffix("p/m:off")).toBe("p/m");
279
+ expect(stripThinkingSuffix("p/m")).toBe("p/m");
280
+ });
281
+
282
+ it("非白名单冒号后缀不剥", () => {
283
+ expect(stripThinkingSuffix("p/m:foo")).toBe("p/m:foo");
284
+ });
285
+ });
286
+
287
+ describe("assertThinkingLevel", () => {
288
+ it("undefined 透传", () => {
289
+ expect(assertThinkingLevel(undefined)).toBeUndefined();
290
+ });
291
+
292
+ it("白名单值放行并窄化为字面量联合", () => {
293
+ expect(assertThinkingLevel("high")).toBe("high");
294
+ expect(assertThinkingLevel("max")).toBe("max");
295
+ });
296
+
297
+ it("非白名单值同步抛错(可操作文案:列出合法值)", () => {
298
+ expect(() => assertThinkingLevel("ultra")).toThrow(
299
+ /Invalid thinkingLevel "ultra"\. Allowed values: off, minimal, low, medium, high, xhigh, max\./,
300
+ );
301
+ });
302
+
303
+ it("THINKING_ORDER SSOT:白名单全集顺序稳定(低→高,含 max)", () => {
304
+ expect(THINKING_ORDER).toEqual(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
305
+ });
306
+ });
@@ -58,7 +58,7 @@ describe("stringifySchemaCached — WeakMap 引用级缓存", () => {
58
58
  }
59
59
  });
60
60
 
61
- it("pretty 缩进锚定:indent=2 与 formatSchemaInstruction 渲染同源", () => {
61
+ it("pretty 缩进锚定:indent=2 与 resolver formatSchemaInstruction 渲染同源", () => {
62
62
  const out = stringifySchemaCached({ type: "object" }, "pretty");
63
63
  expect(out).toBe('{\n "type": "object"\n}');
64
64
  });
@@ -0,0 +1,61 @@
1
+ // src/shared/__tests__/timer-delay.test.ts
2
+ //
3
+ // assertSafeTimerDelay 纯函数契约——三个 timer 挂载入口(budgetTimeMs /
4
+ // XYZ_SUBAGENT_SPAWN_WATCHDOG_MS / idleTimeoutMs)统一在值流入 setTimeout 前调
5
+ // 用本函数 fail-fast,契约由本文件锁定。
6
+ //
7
+ // [F-3 NaN 穿透修复] 旧实现只挡 `> MAX`:NaN 的 `NaN > MAX` 为 false 静默放行,
8
+ // setTimeout(fn, NaN) 被 Node 塌缩为 1ms 立即触发(watchdog 刚启动就误杀)。
9
+ // 非有限数(NaN/±Infinity)现在同样 fail-fast,且错误消息区分两种情况。
10
+ import { describe, expect, it } from "vitest";
11
+
12
+ import { MAX_TIMER_DELAY_MS, assertSafeTimerDelay } from "../timer-delay.ts";
13
+
14
+ describe("assertSafeTimerDelay", () => {
15
+ it("安全域内的有限值放行(0 与上限值不抛)", () => {
16
+ expect(() => assertSafeTimerDelay(0, "t")).not.toThrow();
17
+ expect(() => assertSafeTimerDelay(1000, "t")).not.toThrow();
18
+ expect(() => assertSafeTimerDelay(MAX_TIMER_DELAY_MS, "t")).not.toThrow();
19
+ });
20
+
21
+ it("[F-3] NaN → fail-fast throw(旧实现 NaN > MAX 为 false 静默放行)", () => {
22
+ expect(() => assertSafeTimerDelay(Number.NaN, "budgetTimeMs")).toThrowError(/NaN/);
23
+ expect(() => assertSafeTimerDelay(Number.NaN, "budgetTimeMs")).toThrowError(/not a finite number/);
24
+ });
25
+
26
+ it("[F-3] ±Infinity → fail-fast throw", () => {
27
+ expect(() => assertSafeTimerDelay(Number.POSITIVE_INFINITY, "t")).toThrowError(/not a finite number/);
28
+ expect(() => assertSafeTimerDelay(Number.NEGATIVE_INFINITY, "t")).toThrowError(/not a finite number/);
29
+ });
30
+
31
+ it("非有限值错误消息含来源标识与上游修复指引(非 clamp 指引)", () => {
32
+ expect(() => assertSafeTimerDelay(Number.NaN, "idleTimeoutMs")).toThrowError(/idleTimeoutMs/);
33
+ expect(() => assertSafeTimerDelay(Number.NaN, "idleTimeoutMs")).toThrowError(/fix the upstream computation/);
34
+ });
35
+
36
+ it("超出上限 → fail-fast throw,消息含上限值与 clamp 恢复指引(原语义不变)", () => {
37
+ expect(() => assertSafeTimerDelay(MAX_TIMER_DELAY_MS + 1, "budgetTimeMs")).toThrowError(/2147483647/);
38
+ expect(() => assertSafeTimerDelay(3_000_000_000, "budgetTimeMs")).toThrowError(/Recovery: clamp/);
39
+ });
40
+
41
+ it("两种错误可区分:非有限值消息不含 clamp 指引,溢出消息不含 upstream 指引", () => {
42
+ const nonFiniteMsg = (() => {
43
+ try {
44
+ assertSafeTimerDelay(Number.NaN, "t");
45
+ return "";
46
+ } catch (err) {
47
+ return (err as Error).message;
48
+ }
49
+ })();
50
+ const overflowMsg = (() => {
51
+ try {
52
+ assertSafeTimerDelay(MAX_TIMER_DELAY_MS + 1, "t");
53
+ return "";
54
+ } catch (err) {
55
+ return (err as Error).message;
56
+ }
57
+ })();
58
+ expect(nonFiniteMsg).not.toContain("clamp");
59
+ expect(overflowMsg).not.toContain("fix the upstream computation");
60
+ });
61
+ });
@@ -0,0 +1,286 @@
1
+ // src/shared/model-ref.ts
2
+ //
3
+ // [U1 ModelRef 全等裁决] 模型身份的唯一裁决入口(设计 docs/design/subagent-dispatch-reliability.md D1/D2)。
4
+ //
5
+ // 零宽容原则:除「缺省继承主 agent 模型」外,只有与 registry 条目**全等精确匹配(含大小写)**
6
+ // 的模型串可放行;模糊匹配(case variant / 包含关系 / provider 相似度)只用于生成报错里的
7
+ // 纠错候选,永不参与采纳。系统绝不代改输入——恢复动作始终是「重发修正后的参数」。
8
+ //
9
+ // 裁决发生在 start 工具调用的同步期(spawn 之前):放行返回 {provider, id} 供
10
+ // `${provider}/${id}` 拼接,未命中/孪生歧义同步抛错。
11
+ //
12
+ // 背景(D1 证据):pi CLI 的 tryMatchModel 是 pattern 模糊引擎(id 匹配用 toLowerCase()),
13
+ // registry 存在大小写孪生时 canonical 串亦被判歧义作废、落入模糊分支 localeCompare 取最大——
14
+ // 因此「扩展侧全等放行」不能独立保证「子进程按此名执行」,孪生守卫必须内建(规则④)。
15
+
16
+ // ============================================================
17
+ // 类型
18
+ // ============================================================
19
+
20
+ /** 裁决产物:registry 全等条目的 (provider, id),供 `${provider}/${id}` 拼接。 */
21
+ export interface ModelRef {
22
+ provider: string;
23
+ id: string;
24
+ }
25
+
26
+ /**
27
+ * 模型清单源的最小 duck 接口(只读 getAvailable)。
28
+ * execution/model-resolver.ts 的 ModelRegistryLike 结构兼容(getAvailable 返回 ModelInfo 超集)。
29
+ */
30
+ export interface ModelRefSource {
31
+ getAvailable(): ReadonlyArray<{ provider: string; id: string }>;
32
+ }
33
+
34
+ // ============================================================
35
+ // thinking level 白名单(SSOT:原 execution/model-resolver.ts 常量迁入,
36
+ // model-resolver re-export 保持既有 import 路径不变)
37
+ // ============================================================
38
+
39
+ /** thinking level 支持顺序(低→高)。spawn 侧 `:level` 后缀仅接受本白名单值。 */
40
+ export const THINKING_ORDER = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
41
+
42
+ /** 合法 thinking level 字面量联合(类型层面收窄,裸字符串不可达 spawn 拼接)。 */
43
+ export type ThinkingLevel = (typeof THINKING_ORDER)[number];
44
+
45
+ /** 报错信息中列出的候选/全集模型上限(防超长错误信息)。 */
46
+ const MODEL_LIST_LIMIT = 20;
47
+
48
+ /**
49
+ * 校验 thinkingLevel 属于 THINKING_ORDER 白名单,返回窄化类型。
50
+ *
51
+ * buildSpawnArgs 的 thinkingLevel 参数类型为 ThinkingLevel(白名单联合)——TS 调用方
52
+ * 传非法值编译期即报错;本断言是运行时防线(防 JS 调用方/动态数据绕过类型)。
53
+ * undefined 透传(无显式 level 语义)。
54
+ */
55
+ export function assertThinkingLevel(level: string | undefined): ThinkingLevel | undefined {
56
+ if (level === undefined) return undefined;
57
+ const hit = THINKING_ORDER.find((l) => l === level);
58
+ if (hit === undefined) {
59
+ throw new Error(
60
+ `Invalid thinkingLevel "${level}". Allowed values: ${THINKING_ORDER.join(", ")}. ` +
61
+ `Retry with one of the allowed values, or omit the param.`,
62
+ );
63
+ }
64
+ return hit;
65
+ }
66
+
67
+ // ============================================================
68
+ // 规则①:strip 合法 thinking 后缀
69
+ // ============================================================
70
+
71
+ /**
72
+ * 剥离模型字符串尾部 ":thinkingLevel" 后缀(如 "ds-pro:xhigh" → "ds-pro")。
73
+ * 仅匹配合法 thinking level(THINKING_ORDER 白名单),避免误剥 "foo:bar" 这类无关冒号。
74
+ */
75
+ export function stripThinkingSuffix(modelStr: string): string {
76
+ // 按长度降序拼正则避免短串误匹配(如 "off" 先于 "o"——白名单无单字符,防御性保留)
77
+ const alt = THINKING_ORDER.slice().sort((a, b) => b.length - a.length).join("|");
78
+ return modelStr.replace(new RegExp(`:(${alt})$`), "");
79
+ }
80
+
81
+ // ============================================================
82
+ // 规则④:孪生守卫(两条路径共用)
83
+ // ============================================================
84
+
85
+ /**
86
+ * 收集 registry 中与 (provider, id) case-insensitive 相等但非全等的其他条目
87
+ * (大小写孪生)。判定粒度对齐 pi findExactModelReferenceMatch:provider 精确相等 +
88
+ * id toLowerCase 相等。返回孪生条目的 "provider/id" 全串列表。
89
+ */
90
+ function collectCaseVariants(
91
+ provider: string,
92
+ id: string,
93
+ source: ModelRefSource,
94
+ ): string[] {
95
+ const lowerId = id.toLowerCase();
96
+ return source
97
+ .getAvailable()
98
+ .filter((m) => m.provider === provider && m.id !== id && m.id.toLowerCase() === lowerId)
99
+ .map((m) => `${m.provider}/${m.id}`);
100
+ }
101
+
102
+ /**
103
+ * 规则④孪生守卫错误(D1 文案)。命中全等但 registry 自身含大小写歧义 → 拒绝放行,
104
+ * 恢复动作 = 清理重复条目后重试(输入侧不可控维度,系统不代改 registry)。
105
+ */
106
+ function ambiguousVariantError(ref: string, variants: string[]): Error {
107
+ return new Error(
108
+ `Model "${ref}" matches a registry entry exactly, but registry contains ambiguous case variants ` +
109
+ `for ${ref}: [${variants.join(", ")}].\n` +
110
+ `Recovery: remove the duplicate case variant from models.json (or the models-store cache) ` +
111
+ `so exactly one case form remains, then retry with the exact registry string.`,
112
+ );
113
+ }
114
+
115
+ // ============================================================
116
+ // 继承路径(D2 豁免口径):已验证 ModelInfo → ModelRef 包装
117
+ // ============================================================
118
+
119
+ /**
120
+ * ctxModel 继承路径的 ModelRef 包装(D2 豁免口径)。
121
+ *
122
+ * ctxModel 是运行时已验证的 ModelInfo 对象(主 agent 在用),豁免 registry 存在性复查
123
+ * 与 auth 校验——「缺省继承」是输入缺省而非变体放行;但继承产出的 canonical 串与显式
124
+ * 入参走同一个 pi pattern 引擎,**孪生守卫同等适用**(registry 含大小写孪生时拒绝放行)。
125
+ *
126
+ * @throws 孪生歧义时同步抛错(ambiguousVariantError 文案)
127
+ */
128
+ export function modelRefFromVerified(
129
+ info: { provider: string; id: string },
130
+ source: ModelRefSource,
131
+ ): ModelRef {
132
+ const twins = collectCaseVariants(info.provider, info.id, source);
133
+ if (twins.length > 0) {
134
+ throw ambiguousVariantError(`${info.provider}/${info.id}`, [`${info.provider}/${info.id}`, ...twins]);
135
+ }
136
+ return { provider: info.provider, id: info.id };
137
+ }
138
+
139
+ // ============================================================
140
+ // 规则⑤:未命中错误(模糊匹配只做建议,绝不采纳)
141
+ // ============================================================
142
+
143
+ /**
144
+ * case variant 候选:provider 精确相等 + id case-insensitive 相等(含跨 registry 的
145
+ * 显式大小写差异)。这是最高置信建议,排首位并标注。
146
+ */
147
+ function findCaseVariantSuggestions(
148
+ provider: string,
149
+ id: string,
150
+ source: ModelRefSource,
151
+ ): string[] {
152
+ const lowerId = id.toLowerCase();
153
+ return source
154
+ .getAvailable()
155
+ .filter((m) => m.provider === provider && m.id.toLowerCase() === lowerId)
156
+ .map((m) => `${m.provider}/${m.id}`);
157
+ }
158
+
159
+ /**
160
+ * 一般模糊候选:id 双向包含 或 provider case-insensitive 双向包含(provider 相似度)。
161
+ * 排除已列入 case variant 的条目。
162
+ */
163
+ function findSimilarSuggestions(
164
+ provider: string,
165
+ id: string,
166
+ source: ModelRefSource,
167
+ exclude: ReadonlySet<string>,
168
+ ): string[] {
169
+ const lowerId = id.toLowerCase();
170
+ const lowerProvider = provider.toLowerCase();
171
+ return source
172
+ .getAvailable()
173
+ .map((m) => `${m.provider}/${m.id}`)
174
+ .filter((full) => {
175
+ if (exclude.has(full)) return false;
176
+ const slashIdx = full.indexOf("/");
177
+ const mProvider = full.slice(0, slashIdx);
178
+ const mId = full.slice(slashIdx + 1);
179
+ const lowerMId = mId.toLowerCase();
180
+ const lowerMProvider = mProvider.toLowerCase();
181
+ return (
182
+ lowerMId.includes(lowerId) ||
183
+ lowerId.includes(lowerMId) ||
184
+ lowerMProvider.includes(lowerProvider) ||
185
+ lowerProvider.includes(lowerMProvider)
186
+ );
187
+ })
188
+ .slice(0, MODEL_LIST_LIMIT);
189
+ }
190
+
191
+ /** 规则⑤未命中错误:问句候选 + 合法串全集(无候选时)+ 继承指引。 */
192
+ function notFoundError(
193
+ input: string,
194
+ prefix: string,
195
+ provider: string,
196
+ id: string,
197
+ source: ModelRefSource,
198
+ ): Error {
199
+ const lines = [
200
+ `Model "${input}"${prefix} is not a registry entry. ` +
201
+ `Registry match is case-sensitive — the string must equal a registry entry exactly, including letter case.`,
202
+ ];
203
+
204
+ const caseVariants = id.length > 0 ? findCaseVariantSuggestions(provider, id, source) : [];
205
+ if (caseVariants.length > 0) {
206
+ lines.push(`Did you mean one of these?`);
207
+ for (const full of caseVariants) {
208
+ lines.push(` ${full} ← case variant of "${id}"`);
209
+ }
210
+ const similar = findSimilarSuggestions(provider, id, source, new Set(caseVariants));
211
+ if (similar.length > 0) {
212
+ lines.push(`Other models you may have meant (similar id/provider):`);
213
+ for (const full of similar) lines.push(` ${full}`);
214
+ }
215
+ } else {
216
+ const available = source.getAvailable().map((m) => `${m.provider}/${m.id}`);
217
+ if (available.length === 0) {
218
+ lines.push(`Registry has no available models.`);
219
+ } else {
220
+ const similar = findSimilarSuggestions(provider, id, source, new Set());
221
+ if (similar.length > 0) {
222
+ lines.push(`Other models you may have meant (similar id/provider):`);
223
+ for (const full of similar) lines.push(` ${full}`);
224
+ } else {
225
+ lines.push(`No similar models found.`);
226
+ lines.push(`Available models:`);
227
+ for (const full of available.slice(0, MODEL_LIST_LIMIT)) lines.push(` ${full}`);
228
+ }
229
+ }
230
+ }
231
+
232
+ lines.push(`Or omit the \`model\` param to inherit the main agent model.`);
233
+ return new Error(lines.join("\n"));
234
+ }
235
+
236
+ // ============================================================
237
+ // 单一裁决入口(规则①→⑤)
238
+ // ============================================================
239
+
240
+ /**
241
+ * 模型串 → ModelRef 的唯一裁决入口(D1)。
242
+ *
243
+ * ① strip 合法 thinking 后缀(THINKING_ORDER 白名单);
244
+ * ② provider 精确匹配(区分大小写);
245
+ * ③ modelId 与 registry 条目全等精确匹配(含大小写);
246
+ * ④ 孪生守卫——全等命中后 case-insensitive 复扫 registry,存在孪生条目即拒绝放行;
247
+ * ⑤ 未命中 → 同步抛错,错误含 "Did you mean" 问句候选(case variant 排首位并标注)+
248
+ * 合法串全集(无候选时)+ 「省略 model 继承主 agent」指引。
249
+ *
250
+ * 系统绝不代改输入:不自动纠正、不放行变体、不重试。
251
+ *
252
+ * @param input 调用方原始模型串("provider/modelId[:thinkingLevel]")
253
+ * @param source 模型清单源(registry 快照)
254
+ * @param opts.source 可选来源标签("paramOverride" / "agentConfig"),进错误首行辅助定位
255
+ * @returns 全等 ModelRef(放行即与 registry 条目全等,`${provider}/${id}` 可直接拼接)
256
+ * @throws 未命中 / 孪生歧义时同步抛错(start 工具调用同步期完成裁决)
257
+ */
258
+ export function assertCanonicalModelRef(
259
+ input: string,
260
+ source: ModelRefSource,
261
+ opts: { source?: string } = {},
262
+ ): ModelRef {
263
+ const prefix = opts.source ? ` (${opts.source})` : "";
264
+ const clean = stripThinkingSuffix(input);
265
+ const slashIdx = clean.indexOf("/");
266
+ const provider = slashIdx > 0 ? clean.slice(0, slashIdx) : "";
267
+ const id = slashIdx > 0 ? clean.slice(slashIdx + 1) : "";
268
+
269
+ if (provider.length > 0 && id.length > 0) {
270
+ const exact = source
271
+ .getAvailable()
272
+ .find((m) => m.provider === provider && m.id === id);
273
+ if (exact) {
274
+ const twins = collectCaseVariants(exact.provider, exact.id, source);
275
+ if (twins.length > 0) {
276
+ throw ambiguousVariantError(`${exact.provider}/${exact.id}`, [
277
+ `${exact.provider}/${exact.id}`,
278
+ ...twins,
279
+ ]);
280
+ }
281
+ return { provider: exact.provider, id: exact.id };
282
+ }
283
+ }
284
+
285
+ throw notFoundError(input, prefix, provider, id, source);
286
+ }