@njuptlzf/agent-chat-server 0.3.0 → 0.4.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 (46) hide show
  1. package/dist/checkpoint-store.d.ts +78 -0
  2. package/dist/checkpoint-store.js +52 -0
  3. package/dist/components.d.ts +15 -0
  4. package/dist/components.js +50 -0
  5. package/dist/extension-admission.d.ts +32 -0
  6. package/dist/extension-admission.js +155 -0
  7. package/dist/flows.d.ts +49 -0
  8. package/dist/flows.js +208 -0
  9. package/dist/ledger.d.ts +90 -0
  10. package/dist/ledger.js +115 -0
  11. package/dist/main.js +14 -2
  12. package/dist/manifest.js +14 -1
  13. package/dist/orchestrator/engine.d.ts +132 -0
  14. package/dist/orchestrator/engine.js +1 -0
  15. package/dist/orchestrator/engines/fake.d.ts +14 -0
  16. package/dist/orchestrator/engines/fake.js +282 -0
  17. package/dist/orchestrator/engines/taskflow.d.ts +4 -0
  18. package/dist/orchestrator/engines/taskflow.js +541 -0
  19. package/dist/orchestrator/run-spec.d.ts +154 -0
  20. package/dist/orchestrator/run-spec.js +11 -0
  21. package/dist/server.d.ts +21 -2
  22. package/dist/server.js +543 -187
  23. package/dist/sqlite-stores.d.ts +46 -6
  24. package/dist/sqlite-stores.js +292 -33
  25. package/dist/stores.d.ts +0 -36
  26. package/dist/stores.js +0 -27
  27. package/dist/testing.d.ts +5 -4
  28. package/dist/testing.js +5 -4
  29. package/package.json +7 -6
  30. package/scripts/agentchat-integrate.mjs +853 -853
  31. package/src/checkpoint-store.ts +122 -0
  32. package/src/components.ts +66 -0
  33. package/src/extension-admission.ts +131 -0
  34. package/src/flows.ts +244 -0
  35. package/src/ledger.ts +171 -0
  36. package/src/main.ts +16 -2
  37. package/src/manifest.ts +14 -1
  38. package/src/orchestrator/engine.ts +134 -0
  39. package/src/orchestrator/engines/fake.ts +330 -0
  40. package/src/orchestrator/engines/taskflow.ts +626 -0
  41. package/src/orchestrator/run-spec.ts +171 -0
  42. package/src/server.ts +553 -183
  43. package/src/session.ts +689 -689
  44. package/src/sqlite-stores.ts +343 -35
  45. package/src/stores.ts +0 -41
  46. package/src/testing.ts +4 -4
@@ -0,0 +1,541 @@
1
+ import { executeTaskflow } from "taskflow-core/runtime";
2
+ import { validateTaskflow } from "taskflow-core/schema";
3
+ import { PHASE_KINDS } from "../run-spec.js";
4
+ const KINDS = new Set(PHASE_KINDS);
5
+ /** 分支后缀分隔符。见文件头「phase → agent 名」一节。 */
6
+ const BRANCH_SEP = "~";
7
+ function emptyUsage() {
8
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 };
9
+ }
10
+ /** phase 在 taskflow 里的 agent 名(不含分支后缀)。 */
11
+ function agentNameOf(phaseId) {
12
+ return phaseId;
13
+ }
14
+ /** parallel 分支的 agent 名。 */
15
+ function branchAgentName(phaseId, index) {
16
+ return `${phaseId}${BRANCH_SEP}${index}`;
17
+ }
18
+ /**
19
+ * 从 agent 名还原 phase id(去掉分支后缀)。查不到就返回 `undefined`——
20
+ * 调用方会 fail-closed 而不是猜一个。
21
+ */
22
+ function phaseIdOf(agentName) {
23
+ const cut = agentName.indexOf(BRANCH_SEP);
24
+ return cut === -1 ? agentName : agentName.slice(0, cut);
25
+ }
26
+ /** 一个 phase 会派发几个子会话(0 = 不派发,如未启用的 gate)。 */
27
+ function fanOutOf(phase) {
28
+ if (phase.kind === "parallel")
29
+ return phase.branches?.length ?? 0;
30
+ if (phase.kind === "gate")
31
+ return 0;
32
+ return phase.job ? 1 : 0;
33
+ }
34
+ /** 只做本仓允许的四类;其余(approval / script / tournament…)在 validate 拒。 */
35
+ function toPhase(spec) {
36
+ const base = { id: spec.id, type: spec.kind };
37
+ if (spec.dependsOn !== undefined && spec.dependsOn.length > 0)
38
+ base.dependsOn = [...spec.dependsOn];
39
+ if (spec.final === true)
40
+ base.final = true;
41
+ switch (spec.kind) {
42
+ case "agent":
43
+ case "reduce": {
44
+ if (spec.job) {
45
+ base.agent = agentNameOf(spec.id);
46
+ base.task = spec.job.task;
47
+ if (spec.job.timeoutMs !== undefined)
48
+ base.timeout = spec.job.timeoutMs;
49
+ }
50
+ if (spec.kind === "reduce") {
51
+ // reduce 的输入来自 from[];`{previous.output}` 是 taskflow 的聚合占位符
52
+ // (one → 原文,many → `### <id>\n\n<output>` 用 `---` 连接)。实测过这个格式。
53
+ if (spec.from !== undefined)
54
+ base.from = [...spec.from];
55
+ }
56
+ break;
57
+ }
58
+ case "parallel": {
59
+ base.branches = (spec.branches ?? []).map((b, i) => ({
60
+ agent: branchAgentName(spec.id, i),
61
+ task: b.task,
62
+ }));
63
+ break;
64
+ }
65
+ case "gate":
66
+ // validate 已拒,这里不会走到;留着是为了 switch 穷尽。
67
+ break;
68
+ }
69
+ return base;
70
+ }
71
+ function toDef(spec) {
72
+ const def = {
73
+ name: spec.runId,
74
+ phases: spec.phases.map(toPhase),
75
+ };
76
+ if (spec.concurrency !== undefined)
77
+ def.concurrency = spec.concurrency;
78
+ if (spec.budget?.maxTokens !== undefined) {
79
+ def.budget = { maxTokens: spec.budget.maxTokens };
80
+ }
81
+ return def;
82
+ }
83
+ function buildAgentTable(spec) {
84
+ const agents = [];
85
+ const byName = new Map();
86
+ const add = (name, persona, phase, job) => {
87
+ if (byName.has(name))
88
+ return;
89
+ byName.set(name, { phase, job });
90
+ agents.push({
91
+ name,
92
+ description: name,
93
+ // 本仓的 prompt / 工具白名单由 createProductSession 决定,这里只是占位:
94
+ // taskflow 不读它(runTask 被我们完全接管),但类型要求它存在。
95
+ systemPrompt: "",
96
+ source: "project",
97
+ // 合成值:本仓的 persona 不是磁盘上的 agent 定义文件,没有真实路径。
98
+ filePath: `<persona:${persona}>`,
99
+ });
100
+ };
101
+ for (const phase of spec.phases) {
102
+ if (phase.kind === "parallel") {
103
+ for (const [i, branch] of (phase.branches ?? []).entries()) {
104
+ add(branchAgentName(phase.id, i), branch.persona, phase, branch);
105
+ }
106
+ continue;
107
+ }
108
+ if (phase.job)
109
+ add(agentNameOf(phase.id), phase.job.persona, phase, phase.job);
110
+ }
111
+ return { agents, byName };
112
+ }
113
+ function toUsage(u) {
114
+ if (!u)
115
+ return emptyUsage();
116
+ const input = u.input ?? 0;
117
+ const output = u.output ?? 0;
118
+ return {
119
+ input,
120
+ output,
121
+ cacheRead: u.cacheRead ?? 0,
122
+ cacheWrite: u.cacheWrite ?? 0,
123
+ total: input + output,
124
+ costUsd: u.cost ?? 0,
125
+ };
126
+ }
127
+ function toJobState(raw) {
128
+ switch (raw) {
129
+ // taskflow 的 PhaseStatus 是 pending/running/done/failed/skipped——
130
+ // 注意是 `done` 不是 `completed`(用松散类型猜过一次,踩到了)。
131
+ case "done":
132
+ return "completed";
133
+ case "failed":
134
+ return "failed";
135
+ case "running":
136
+ return "running";
137
+ case "pending":
138
+ return "queued";
139
+ case "skipped":
140
+ // gate 未通过 / 预算耗尽跳过的 phase:对用户是「没跑」,归 stopped。
141
+ return "stopped";
142
+ default:
143
+ return "stopped";
144
+ }
145
+ }
146
+ /**
147
+ * `runTask` 是我们与 taskflow 的唯一执行通道:它把一个 phase 交给我们,
148
+ * 我们交给宿主注入的 `deps.runJob`(背后是 pi 会话)。**不 spawn、不落盘。**
149
+ *
150
+ * **单 phase 不发事件**:`RunSpec.phases.length === 1` 时一个都不 emit,
151
+ * 且 `onDelta` 也不接。这是 I8 的硬要求——档 1(单 phase)的 SSE 字节流必须与
152
+ * 接入编排层之前完全一致,多出来的 `phase_started` / `member_started` 会改变
153
+ * 前端收到的事件序列(`wire-baseline.test.ts` 逐字节钉住)。
154
+ */
155
+ function makeRunTask(spec, deps, table) {
156
+ const multiPhase = spec.phases.length > 1;
157
+ const emit = multiPhase ? deps.emit : undefined;
158
+ return async (_defaultCwd, _agents, agentName, task, opts) => {
159
+ // 反查表命中不了 = 适配器自己的 bug(agents 数组就是从这里生成的)。
160
+ // 不抛异常而是回一个失败结果:抛出去会被 taskflow 当宿主崩,错误信息反而丢。
161
+ const hit = table.byName.get(agentName);
162
+ const phaseId = hit?.phase.id ?? phaseIdOf(agentName) ?? agentName;
163
+ const jobSpec = hit?.job;
164
+ if (!jobSpec) {
165
+ const err = `orchestrator: no JobSpec for agent "${agentName}" (adapter bug)`;
166
+ return {
167
+ agent: agentName,
168
+ task,
169
+ exitCode: 1,
170
+ output: "",
171
+ stderr: err,
172
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
173
+ stopReason: "error",
174
+ errorMessage: err,
175
+ };
176
+ }
177
+ const isParallelBranch = hit.phase.kind === "parallel";
178
+ // parallel 的分支各自是独立成员;jobId 带分支后缀才不撞。
179
+ const jobId = isParallelBranch ? `${spec.runId}:${agentName}` : `${spec.runId}:${phaseId}`;
180
+ // `memberId` 对用户就是「哪个成员在干活」:并行分支同 persona 时也算同一个成员,
181
+ // 所以用 persona 而不是 agent 名——前端要按人归组,不是按分支归组。
182
+ const memberId = jobSpec.persona;
183
+ emit?.({ type: "phase_started", phaseId, jobId });
184
+ emit?.({ type: "member_started", phaseId, memberId, jobId, task });
185
+ const controller = new AbortController();
186
+ const forward = () => controller.abort();
187
+ if (opts?.signal) {
188
+ if (opts.signal.aborted)
189
+ controller.abort();
190
+ else
191
+ opts.signal.addEventListener("abort", forward, { once: true });
192
+ }
193
+ let result;
194
+ try {
195
+ result = await deps.runJob(jobSpec, {
196
+ signal: controller.signal,
197
+ jobId,
198
+ phaseId,
199
+ memberId,
200
+ // 单 phase 一律不给 delta 通道:那一路的文本走 text_delta(I8)。
201
+ ...(multiPhase ? { onDelta: (delta) => deps.emit?.({ type: "member_delta", phaseId, memberId, delta }) } : {}),
202
+ });
203
+ }
204
+ catch (err) {
205
+ result = {
206
+ output: "",
207
+ ok: false,
208
+ stopReason: "error",
209
+ error: err instanceof Error ? err.message : String(err),
210
+ };
211
+ }
212
+ finally {
213
+ opts?.signal?.removeEventListener("abort", forward);
214
+ }
215
+ const usage = result.usage;
216
+ const state = result.ok ? "completed" : "failed";
217
+ emit?.({
218
+ type: "member_done",
219
+ phaseId,
220
+ memberId,
221
+ jobId,
222
+ state,
223
+ usage: {
224
+ input: usage?.input ?? 0,
225
+ output: usage?.output ?? 0,
226
+ cacheRead: usage?.cacheRead ?? 0,
227
+ cacheWrite: usage?.cacheWrite ?? 0,
228
+ total: usage?.total ?? 0,
229
+ costUsd: usage?.costUsd ?? 0,
230
+ },
231
+ });
232
+ emit?.({ type: "phase_settled", phaseId, jobId, state });
233
+ return {
234
+ agent: agentName,
235
+ task,
236
+ exitCode: result.ok ? 0 : 1,
237
+ output: result.output,
238
+ stderr: result.error ?? "",
239
+ usage: {
240
+ input: usage?.input ?? 0,
241
+ output: usage?.output ?? 0,
242
+ cacheRead: usage?.cacheRead ?? 0,
243
+ cacheWrite: usage?.cacheWrite ?? 0,
244
+ cost: usage?.costUsd ?? 0,
245
+ contextTokens: 0,
246
+ turns: 0,
247
+ },
248
+ stopReason: result.stopReason ?? (result.ok ? "end_turn" : "error"),
249
+ ...(result.error !== undefined ? { errorMessage: result.error } : {}),
250
+ ...(result.attempts !== undefined ? { attempts: result.attempts } : {}),
251
+ };
252
+ };
253
+ }
254
+ function initialState(spec, def, cwd, now) {
255
+ return {
256
+ runId: spec.runId,
257
+ flowName: def.name,
258
+ def,
259
+ args: {},
260
+ status: "running",
261
+ phases: {},
262
+ createdAt: now,
263
+ updatedAt: now,
264
+ cwd,
265
+ };
266
+ }
267
+ /**
268
+ * resume 的短路通道。
269
+ *
270
+ * **为什么要按 phase 而分支去重**:`runTask` 是**每个子会话**回调一次,而
271
+ * `PhaseCheckpoint` 是**每个 phase 一份**。parallel phase 有 N 个分支,
272
+ * 若每个分支都返回整份 checkpoint(含 usage),phase 的 usage 会被放大 N 倍
273
+ * (实测踩到:4 个子会话的 diamond 续跑后总量 30 而不是 20)。
274
+ *
275
+ * 所以:**产物只在第一个分支返回**(拼接后正好等于原 phase 产物),
276
+ * **usage 一律返回 0**,由调用方按 phase 粒度从 checkpoint 补回(见 execute 的 total 计算)。
277
+ */
278
+ class ResumeLedger {
279
+ byPhase;
280
+ emitted = new Set();
281
+ constructor(byPhase) {
282
+ this.byPhase = byPhase;
283
+ }
284
+ /** 这个 agent 对应的 phase 是否有断点。 */
285
+ hit(agentName) {
286
+ return this.byPhase[phaseIdOf(agentName) ?? agentName];
287
+ }
288
+ /** 该 phase 是否已经吐过产物(parallel 的后续分支要回空)。 */
289
+ claimOutput(phaseId) {
290
+ if (this.emitted.has(phaseId))
291
+ return false;
292
+ this.emitted.add(phaseId);
293
+ return true;
294
+ }
295
+ }
296
+ function resumedUsageOf(phaseId, resumeFrom) {
297
+ return resumeFrom?.[phaseId]?.usage;
298
+ }
299
+ function checkpointOf(phase, state, now) {
300
+ if (!state || state.status !== "done")
301
+ return undefined;
302
+ return {
303
+ phaseId: phase.id,
304
+ output: state.output ?? "",
305
+ usage: toUsage(state.usage),
306
+ at: now,
307
+ };
308
+ }
309
+ export function createTaskflowEngine(options) {
310
+ const cwdOf = () => options?.cwd ?? process.cwd();
311
+ return {
312
+ name: "taskflow",
313
+ validate(spec, parentTools) {
314
+ const errors = [];
315
+ // ---- 平台自己的检查(不依赖引擎库的报错文案)----
316
+ const ids = new Set();
317
+ for (const phase of spec.phases) {
318
+ if (ids.has(phase.id))
319
+ errors.push(`duplicate phase id: ${phase.id}`);
320
+ ids.add(phase.id);
321
+ if (!KINDS.has(phase.kind))
322
+ errors.push(`unsupported phase kind: ${String(phase.kind)}`);
323
+ switch (phase.kind) {
324
+ case "agent":
325
+ if (!phase.job)
326
+ errors.push(`phase "${phase.id}": agent phase requires job`);
327
+ if (phase.branches)
328
+ errors.push(`phase "${phase.id}": agent phase does not take branches`);
329
+ if (phase.from)
330
+ errors.push(`phase "${phase.id}": agent phase does not take from`);
331
+ break;
332
+ case "parallel":
333
+ if (!phase.branches || phase.branches.length === 0) {
334
+ errors.push(`phase "${phase.id}": parallel phase requires at least one branch`);
335
+ }
336
+ if (phase.job)
337
+ errors.push(`phase "${phase.id}": parallel phase takes branches, not job`);
338
+ break;
339
+ case "reduce":
340
+ if (!phase.job)
341
+ errors.push(`phase "${phase.id}": reduce phase requires job (who summarizes)`);
342
+ if (!phase.from || phase.from.length === 0) {
343
+ errors.push(`phase "${phase.id}": reduce phase requires from[] (inputs to aggregate)`);
344
+ }
345
+ break;
346
+ case "gate":
347
+ // 刻意恒拒:gate 要的是「算通过吗」的判定规则,那是产品业务语义。
348
+ // 与其猜一套再改,不如 fail-closed——真实需求来了再按需求定形状。
349
+ errors.push(`phase "${phase.id}": gate phase needs a verdict rule, not modeled yet`);
350
+ break;
351
+ }
352
+ // I2:子能力只收窄。越界即拒,不等到执行期。
353
+ for (const job of jobsOf(phase)) {
354
+ if (parentTools === undefined || job.tools === undefined)
355
+ continue;
356
+ const allow = new Set(parentTools);
357
+ for (const tool of job.tools) {
358
+ if (!allow.has(tool)) {
359
+ errors.push(`phase "${phase.id}": tool "${tool}" exceeds parent allowTools`);
360
+ }
361
+ }
362
+ }
363
+ }
364
+ // reduce 的 from[] 必须指向存在的 phase,且不能指向自己。
365
+ for (const phase of spec.phases) {
366
+ if (phase.kind !== "reduce" || !phase.from)
367
+ continue;
368
+ for (const src of phase.from) {
369
+ if (!ids.has(src))
370
+ errors.push(`phase "${phase.id}": from unknown phase "${src}"`);
371
+ if (src === phase.id)
372
+ errors.push(`phase "${phase.id}": from cannot reference itself`);
373
+ }
374
+ }
375
+ // resumeFrom 的键必须是本次声明里存在的 phase(否则是宿主喂错了数据)。
376
+ if (spec.resumeFrom) {
377
+ for (const key of Object.keys(spec.resumeFrom)) {
378
+ if (!ids.has(key))
379
+ errors.push(`resumeFrom references unknown phase "${key}"`);
380
+ }
381
+ }
382
+ if (spec.budget?.maxTokens !== undefined && spec.budget.maxTokens <= 0) {
383
+ errors.push("budget.maxTokens must be positive");
384
+ }
385
+ if (spec.budget?.maxCostCents !== undefined && spec.budget.maxCostCents <= 0) {
386
+ errors.push("budget.maxCostCents must be positive");
387
+ }
388
+ if (spec.phases.length === 0)
389
+ errors.push("run has no phases");
390
+ // ---- 引擎自己的检查(环 / 悬空依赖 / 重复 id 的权威判定)----
391
+ if (errors.length === 0) {
392
+ const report = validateTaskflow(toDef(spec));
393
+ if (!report.ok)
394
+ errors.push(...report.errors);
395
+ }
396
+ return { ok: errors.length === 0, errors };
397
+ },
398
+ async execute(spec, deps) {
399
+ const report = this.validate(spec);
400
+ if (!report.ok) {
401
+ // I1:验证不过 → 零 token、零派发
402
+ return {
403
+ runId: spec.runId,
404
+ state: "failed",
405
+ output: "",
406
+ usage: emptyUsage(),
407
+ jobs: [],
408
+ error: report.errors.join("; "),
409
+ };
410
+ }
411
+ const def = toDef(spec);
412
+ const now = deps.now ?? Date.now;
413
+ const state = initialState(spec, def, cwdOf(), now());
414
+ const table = buildAgentTable(spec);
415
+ // resume:已完成 phase 不进 runJob(I7)。
416
+ // 做法是**在 runTask 里短路**,而不是伪造 taskflow 的内部 inputHash——
417
+ // 后者是引擎私有算法,伪错了就会静默全量重跑(= 白花钱,且没人发现)。
418
+ const ledger = new ResumeLedger(spec.resumeFrom ?? {});
419
+ const multiPhase = spec.phases.length > 1;
420
+ const emit = multiPhase ? deps.emit : undefined;
421
+ const baseRunTask = makeRunTask(spec, deps, table);
422
+ const runTask = async (cwd, agents, agentName, task, opts) => {
423
+ const cp = ledger.hit(agentName);
424
+ if (cp) {
425
+ const phaseId = phaseIdOf(agentName) ?? agentName;
426
+ // 产物只给第一个分支(拼接后等于原 phase 产物);usage 恒 0(见 ResumeLedger 注释)。
427
+ const output = ledger.claimOutput(phaseId) ? cp.output : "";
428
+ // 不发 member_* 事件——这个成员这次根本没跑,给前端发一个「开始又结束」
429
+ // 会让人以为它重跑了一遍。`run_done` 的 usage 里仍含它(I3 要加总)。
430
+ return {
431
+ agent: agentName,
432
+ task,
433
+ exitCode: 0,
434
+ output,
435
+ stderr: "",
436
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
437
+ stopReason: "resumed",
438
+ };
439
+ }
440
+ return baseRunTask(cwd, agents, agentName, task, opts);
441
+ };
442
+ const result = await executeTaskflow(state, {
443
+ cwd: cwdOf(),
444
+ agents: table.agents,
445
+ // 我们真报 usage;不声明会让带 budget 的 flow 被它拒。
446
+ usageAccounting: "available",
447
+ signal: deps.signal,
448
+ runTask,
449
+ ...(deps.persist
450
+ ? {
451
+ persist: () => {
452
+ // 中途 checkpoint 由引擎自己按 phase 产(见下方 outcome.checkpoints)。
453
+ // 这里刻意不逐阶段写:W4 的 checkpoint 粒度是「Run 收口时落全部已完成
454
+ // phase」,因为中断(进程被杀)时我们拿不到 last-will 回调;靠
455
+ // `run_jobs` 的 state 兜住「跑到哪了」,见 checkpoint-store.ts。
456
+ },
457
+ }
458
+ : {}),
459
+ });
460
+ const phases = (result.state?.phases ?? {});
461
+ const nowMs = now();
462
+ const jobs = [];
463
+ const checkpoints = [];
464
+ for (const phase of spec.phases) {
465
+ const raw = phases[phase.id];
466
+ const stateOf = toJobState(raw?.status);
467
+ if (phase.kind === "parallel") {
468
+ // parallel 是一个 phase 多个成员:每个分支各记一行 job,方便 run_jobs 对账。
469
+ // taskflow 只给 phase 级聚合状态,分支级细节拿不到——这里按 phase 状态铺开,
470
+ // 产物留空(真实分支产物在 phase 的聚合 output 里,见 cp.output)。
471
+ for (const [i, branch] of (phase.branches ?? []).entries()) {
472
+ const name = branchAgentName(phase.id, i);
473
+ jobs.push({
474
+ jobId: `${spec.runId}:${name}`,
475
+ phaseId: phase.id,
476
+ state: stateOf,
477
+ output: "",
478
+ usage: emptyUsage(),
479
+ stopReason: raw?.status ?? "unknown",
480
+ });
481
+ }
482
+ }
483
+ else if (fanOutOf(phase) > 0) {
484
+ jobs.push({
485
+ jobId: `${spec.runId}:${phase.id}`,
486
+ phaseId: phase.id,
487
+ state: stateOf,
488
+ output: raw?.output ?? "",
489
+ usage: toUsage(raw?.usage),
490
+ stopReason: raw?.status ?? "unknown",
491
+ ...(raw?.error !== undefined ? { error: raw.error } : {}),
492
+ });
493
+ }
494
+ const cp = checkpointOf(phase, raw, nowMs);
495
+ if (cp)
496
+ checkpoints.push(cp);
497
+ }
498
+ // I3:usage 必须覆盖**所有**已完成的 phase,含从断点恢复的那些。
499
+ // 用 phase 状态聚合而不是 jobs 求和——parallel 的 phase 只有一行真实 usage。
500
+ // 恢复的 phase 在引擎里 usage 恒 0(见 ResumeLedger),所以这里按 checkpoint 补回。
501
+ const total = spec.phases.reduce((acc, phase) => {
502
+ const observed = toUsage(phases[phase.id]?.usage);
503
+ const resumedUsage = phases[phase.id]?.status === "done" ? resumedUsageOf(phase.id, spec.resumeFrom) : undefined;
504
+ const u = resumedUsage === undefined ? observed : {
505
+ input: observed.input + resumedUsage.input,
506
+ output: observed.output + resumedUsage.output,
507
+ cacheRead: observed.cacheRead + resumedUsage.cacheRead,
508
+ cacheWrite: observed.cacheWrite + resumedUsage.cacheWrite,
509
+ total: observed.total + resumedUsage.total,
510
+ costUsd: observed.costUsd + resumedUsage.costUsd,
511
+ };
512
+ return {
513
+ input: acc.input + u.input,
514
+ output: acc.output + u.output,
515
+ cacheRead: acc.cacheRead + u.cacheRead,
516
+ cacheWrite: acc.cacheWrite + u.cacheWrite,
517
+ total: acc.total + u.total,
518
+ costUsd: acc.costUsd + u.costUsd,
519
+ };
520
+ }, emptyUsage());
521
+ const failedPhase = spec.phases.find((p) => phases[p.id]?.status === "failed");
522
+ const outcome = {
523
+ runId: spec.runId,
524
+ state: result.ok ? "completed" : failedPhase ? "failed" : "stopped",
525
+ output: result.finalOutput ?? "",
526
+ usage: total,
527
+ jobs,
528
+ checkpoints,
529
+ ...(result.ok ? {} : { error: failedPhase ? (phases[failedPhase.id]?.error ?? "phase failed") : "run did not complete" }),
530
+ };
531
+ deps.persist?.(outcome);
532
+ return outcome;
533
+ },
534
+ };
535
+ }
536
+ /** phase 会派发的全部 job 声明(parallel 展开多份)。供 I2 的工具校验遍历。 */
537
+ function jobsOf(phase) {
538
+ if (phase.kind === "parallel")
539
+ return phase.branches ?? [];
540
+ return phase.job ? [phase.job] : [];
541
+ }