pi-web-ui 0.119.0 → 0.120.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 (136) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +803 -106
  6. package/dist/server/atomic-file.js +130 -5
  7. package/dist/server/bash-timeout.js +15 -0
  8. package/dist/server/bash-tool.js +68 -4
  9. package/dist/server/bg-servers.js +19 -13
  10. package/dist/server/canvas/canvas-dispatch.js +12 -1
  11. package/dist/server/client-state.js +56 -14
  12. package/dist/server/conversation-tool.js +3 -2
  13. package/dist/server/delegate-task.js +8 -8
  14. package/dist/server/device-center/group-router-runtime.js +2 -0
  15. package/dist/server/device-center/hub-upgrade.js +5 -10
  16. package/dist/server/dispatch-domain-handlers.js +96 -22
  17. package/dist/server/dispatch-plugin-handlers.js +10 -0
  18. package/dist/server/dsh/dsh-agent-service.js +9 -9
  19. package/dist/server/durable/durable-agent-service.js +1 -1
  20. package/dist/server/files-service.js +41 -19
  21. package/dist/server/fs-copy.js +93 -0
  22. package/dist/server/goal-review-gate.js +2 -2
  23. package/dist/server/index.js +15 -0
  24. package/dist/server/job-runner.js +345 -0
  25. package/dist/server/marker-service.js +42 -26
  26. package/dist/server/model-session.js +16 -0
  27. package/dist/server/phone-tool.js +167 -0
  28. package/dist/server/plan-mode.js +2 -2
  29. package/dist/server/plugin-api-catalog.js +1 -1
  30. package/dist/server/plugin-bundled.js +35 -28
  31. package/dist/server/plugin-installer.js +15 -0
  32. package/dist/server/plugin-manifest-validate.js +10 -0
  33. package/dist/server/plugin-materialize.js +161 -0
  34. package/dist/server/plugin-paths.js +60 -0
  35. package/dist/server/plugin-removal.js +16 -3
  36. package/dist/server/plugin-schedule.js +8 -7
  37. package/dist/server/plugin-secrets.js +7 -3
  38. package/dist/server/plugin-updater.js +2 -4
  39. package/dist/server/plugins.js +74 -38
  40. package/dist/server/preset-fields.js +9 -9
  41. package/dist/server/process-utils.js +11 -0
  42. package/dist/server/project-scripts.js +38 -0
  43. package/dist/server/prompt-composer.js +40 -21
  44. package/dist/server/protocol-version.js +1 -1
  45. package/dist/server/quick-ask.js +3 -0
  46. package/dist/server/remote-ssh-service.js +39 -0
  47. package/dist/server/scm-commitmsg.js +2 -1
  48. package/dist/server/serialize.js +8 -0
  49. package/dist/server/session-list-index.js +246 -0
  50. package/dist/server/session-list-scan.js +5 -0
  51. package/dist/server/session-parser.js +16 -0
  52. package/dist/server/settings-service.js +39 -6
  53. package/dist/server/subagent-budget.js +68 -0
  54. package/dist/server/subagent-evidence.js +297 -0
  55. package/dist/server/subagent-helpers.js +12 -0
  56. package/dist/server/subagent-ledger.js +401 -0
  57. package/dist/server/subagent-notify.js +6 -2
  58. package/dist/server/subagent-security-gate.js +2 -2
  59. package/dist/server/subagent-settle.js +71 -0
  60. package/dist/server/subagents.js +497 -79
  61. package/dist/server/tabs.js +8 -1
  62. package/dist/server/terminals.js +0 -1
  63. package/dist/server/tool-manager.js +90 -16
  64. package/dist/server/tool-prompts.js +5 -1
  65. package/dist/server/universal/universal-service.js +1 -1
  66. package/dist/server/universal/universal-session.js +45 -7
  67. package/dist/server/vision-bridge.js +2 -0
  68. package/dist/server/workspace-handle.js +119 -17
  69. package/dist/server/workspace-queue.js +37 -0
  70. package/docs/README.md +25 -23
  71. package/docs/architecture-plugins.md +23 -3
  72. package/docs/device-center.md +1 -1
  73. package/package.json +15 -3
  74. package/plugins/catalog.json +13 -2
  75. package/themes/bases/flow-base.css +7 -16
  76. package/web/dist/.build-assets.json +1 -1
  77. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  78. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  79. package/web/dist/assets/{CanvasStudio-2ydYbnpW.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  80. package/web/dist/assets/{CanvasStudio-DizWvRjn.js → CanvasStudio-DU6O3N4u.js} +3 -3
  81. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  82. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  83. package/web/dist/assets/{DeviceExecutionSettings-B7R9ONaq.js → DeviceExecutionSettings-qJzbI0Cf.js} +1 -1
  84. package/web/dist/assets/{DeviceGroups-DFU4cv5b.js → DeviceGroups-DPrQxW6B.js} +1 -1
  85. package/web/dist/assets/{DeviceGroups-DoaQcxKj.js → DeviceGroups-DoucyUjI.js} +1 -1
  86. package/web/dist/assets/{Dropdown-Btjt6Dzh.js → Dropdown-kj_NIj6e.js} +1 -1
  87. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  88. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  89. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  90. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  91. package/web/dist/assets/{GroupConversation-DwZZrMuE.js → GroupConversation-1-lsPO1f.js} +3 -3
  92. package/web/dist/assets/{GroupConversation-KOi8sa5b.js → GroupConversation-HeiyW_O_.js} +3 -3
  93. package/web/dist/assets/{GroupWorkItems-FqAL74bC.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  94. package/web/dist/assets/{HintTip-BOwPzBGR.js → HintTip-DFhoclDw.js} +1 -1
  95. package/web/dist/assets/{ModelConfigModal-DLIfWKdB.js → ModelConfigModal-D2Ro-jUZ.js} +2 -2
  96. package/web/dist/assets/{ModelConfigModal-B140kWrs.js → ModelConfigModal-DPc9R1pq.js} +2 -2
  97. package/web/dist/assets/{NativeCliPanel-BwiLazSq.js → NativeCliPanel-B108d697.js} +3 -3
  98. package/web/dist/assets/{NativeCliPanel-U0F_EfAU.js → NativeCliPanel-DupvGwQM.js} +3 -3
  99. package/web/dist/assets/{PiSetupModal-Dc7EQ4L3.js → PiSetupModal-D0HitBfd.js} +1 -1
  100. package/web/dist/assets/{ProviderOAuthControls-C3opmPhu.js → ProviderOAuthControls-BLKUEDde.js} +1 -1
  101. package/web/dist/assets/{SCMPanel-BBxQfmq9.js → SCMPanel-DDbWrUHR.js} +1 -1
  102. package/web/dist/assets/{SCMPanel-D2t97Vvr.js → SCMPanel-DluNcd2-.js} +1 -1
  103. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  104. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  105. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  106. package/web/dist/assets/{TermXterm-B6nCtO2b.js → TermXterm-SYc-MUk2.js} +1 -1
  107. package/web/dist/assets/{TerminalPanel-BWB3iSeN.js → TerminalPanel-CgA_lhVT.js} +1 -1
  108. package/web/dist/assets/{TerminalPanel-CAV2SosY.js → TerminalPanel-vdSIOPjD.js} +1 -1
  109. package/web/dist/assets/{TuiOverlayModal-B0jBPOMc.js → TuiOverlayModal-Cy1jYYIw.js} +1 -1
  110. package/web/dist/assets/{TuiOverlayModal-DGd6fzU6.js → TuiOverlayModal-kXY_4hV8.js} +1 -1
  111. package/web/dist/assets/{app-globals-CR8Ls9nE.js → app-globals-CBEscsYP.js} +9 -9
  112. package/web/dist/assets/{canvas-client-B0lkqTtF.js → canvas-client-Clsypfs6.js} +1 -1
  113. package/web/dist/assets/{desktop-BME3DkyE.js → desktop-C6D9a8HZ.js} +1 -1
  114. package/web/dist/assets/index-BD29OL9L.js +404 -0
  115. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  116. package/web/dist/assets/index-DB55rbKC.css +1 -0
  117. package/web/dist/assets/{plugin-host-CVgcdBOk.js → plugin-host-VWBcq-LQ.js} +1 -1
  118. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  119. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  120. package/web/dist/index.html +10 -10
  121. package/web/dist/sw.js +1 -1
  122. package/web/dist/assets/BgTasksModal-CVHW1lRA.js +0 -1
  123. package/web/dist/assets/BgTasksModal-t5hxW1H6.js +0 -1
  124. package/web/dist/assets/DeviceCenter-CPaZNBJE.js +0 -3
  125. package/web/dist/assets/DeviceCenter-DsVakAYR.js +0 -3
  126. package/web/dist/assets/FilePreview-QGQfD2lV.js +0 -2
  127. package/web/dist/assets/FilePreview-qez9walH.js +0 -2
  128. package/web/dist/assets/GlobalSearchModal-B-cnTDJ5.js +0 -1
  129. package/web/dist/assets/GlobalSearchModal-BvbafjdU.js +0 -1
  130. package/web/dist/assets/SettingsModal-BqPQNUwF.js +0 -34
  131. package/web/dist/assets/SettingsModal-l7eeV-Rq.js +0 -34
  132. package/web/dist/assets/index-BBAQNi6v.js +0 -404
  133. package/web/dist/assets/index-BYW9d61A.js +0 -404
  134. package/web/dist/assets/index-BYWs88H2.css +0 -1
  135. package/web/dist/assets/remote-ssh-client-DEpvwgqG.js +0 -1
  136. package/web/dist/assets/theme-DVa7Z5Zu.js +0 -1
@@ -0,0 +1,401 @@
1
+ /**
2
+ * 子代理运行账本(run ledger):把每次派发的生命周期落到 `<dataDir>/subagent-runs/<runId>/`,
3
+ * 让「工作不会因为重启就消失」——重启后仍能列出、取回证据与结果尾部,并据此续跑。
4
+ *
5
+ * 两层文件,职责不重叠:
6
+ * · `status.json` —— 机器可读的当前状态(原子替换,最后写者胜)。
7
+ * · `events.jsonl` —— 追加式生命周期流水(有字节上限,截断后打一条标记就不再写)。
8
+ *
9
+ * 三条硬约束:
10
+ * 1. **不阻塞热路径**:所有写入进每个 run 的串行队列,调用方 fire-and-forget;失败只记 `lastError`,
11
+ * 绝不让账本问题打断派发或回合结束。
12
+ * 2. **有界**:run 目录数(默认 200)、单条 run 的事件字节(256KB)、prompt/输出尾部都有上限。
13
+ * 3. **重启可辨别**:每条记录带本进程 `bootId`;`recover()` 只把「别的 boot 留下的 running」判为
14
+ * interrupted,绝不猜活着的运行。
15
+ *
16
+ * 续跑语义见 `resumeLedgerRun`:进程内子代理会话不落盘,因此续跑是「带上下文重派」(relaunch),
17
+ * 不是假装接上原转录;落盘的持久化子代理仍在历史里可回看,账本给出 sessionFile。
18
+ */
19
+ import { mkdir, readFile, readdir, rm, stat, appendFile } from "node:fs/promises";
20
+ import { randomUUID } from "node:crypto";
21
+ import { join } from "node:path";
22
+ import { writeAtomic } from "./atomic-file.js";
23
+ export const LEDGER_DEFAULT_MAX_RUNS = 200;
24
+ export const LEDGER_EVENT_BYTES_CAP = 256 * 1024;
25
+ export const LEDGER_PROMPT_CAP = 8 * 1024;
26
+ export const LEDGER_OUTPUT_CAP = 4 * 1024;
27
+ export const LEDGER_EVIDENCE_ITEMS_CAP = 5;
28
+ /** 本进程身份:只用于区分「这群 running 是上一次进程留下的」。 */
29
+ const BOOT_ID = randomUUID();
30
+ export function ledgerBootId() {
31
+ return BOOT_ID;
32
+ }
33
+ export function ledgerMaxRunsFromEnv(env = process.env) {
34
+ const raw = Number(env.PI_WEB_SUBAGENT_LEDGER_MAX_RUNS);
35
+ if (!Number.isFinite(raw) || raw < 0)
36
+ return LEDGER_DEFAULT_MAX_RUNS;
37
+ return Math.floor(raw);
38
+ }
39
+ export function boundText(value, cap) {
40
+ if (typeof value !== "string")
41
+ return undefined;
42
+ const text = value.trim();
43
+ if (!text)
44
+ return undefined;
45
+ return text.length > cap ? `${text.slice(0, cap)}…` : text;
46
+ }
47
+ export function toLedgerEvidence(evidence) {
48
+ if (!evidence)
49
+ return undefined;
50
+ return {
51
+ verdict: evidence.verdict,
52
+ matchedFiles: evidence.matchedFiles,
53
+ files: evidence.files.length,
54
+ matchedCommands: evidence.matchedCommands,
55
+ commands: evidence.commands.length,
56
+ none: evidence.none,
57
+ blocked: evidence.blocked,
58
+ issues: evidence.issues.slice(0, LEDGER_EVIDENCE_ITEMS_CAP),
59
+ warnings: evidence.warnings.slice(0, LEDGER_EVIDENCE_ITEMS_CAP),
60
+ };
61
+ }
62
+ function safeSegment(runId) {
63
+ const cleaned = runId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
64
+ return cleaned.length > 0 ? cleaned : "run";
65
+ }
66
+ function isRecord(value) {
67
+ return typeof value === "object" && value !== null;
68
+ }
69
+ function normalizeRecord(raw) {
70
+ if (!isRecord(raw))
71
+ return undefined;
72
+ const runId = typeof raw.runId === "string" ? raw.runId : "";
73
+ if (!runId)
74
+ return undefined;
75
+ const state = raw.state;
76
+ const states = ["running", "done", "blocked", "failed", "canceled", "interrupted", "dismissed"];
77
+ return {
78
+ runId,
79
+ parentRunId: typeof raw.parentRunId === "string" ? raw.parentRunId : undefined,
80
+ parentSessionFile: typeof raw.parentSessionFile === "string" ? raw.parentSessionFile : undefined,
81
+ cwd: typeof raw.cwd === "string" ? raw.cwd : "",
82
+ type: typeof raw.type === "string" ? raw.type : "general",
83
+ title: typeof raw.title === "string" ? raw.title : "",
84
+ template: typeof raw.template === "string" ? raw.template : undefined,
85
+ model: typeof raw.model === "string" ? raw.model : undefined,
86
+ thinking: typeof raw.thinking === "string" ? raw.thinking : undefined,
87
+ prompt: typeof raw.prompt === "string" ? raw.prompt : "",
88
+ state: typeof state === "string" && states.includes(state) ? state : "interrupted",
89
+ bootId: typeof raw.bootId === "string" ? raw.bootId : "",
90
+ createdAt: typeof raw.createdAt === "number" ? raw.createdAt : 0,
91
+ updatedAt: typeof raw.updatedAt === "number" ? raw.updatedAt : 0,
92
+ finishedAt: typeof raw.finishedAt === "number" ? raw.finishedAt : undefined,
93
+ sessionFile: typeof raw.sessionFile === "string" ? raw.sessionFile : undefined,
94
+ persisted: raw.persisted === true,
95
+ worktree: isRecord(raw.worktree)
96
+ ? {
97
+ path: typeof raw.worktree.path === "string" ? raw.worktree.path : "",
98
+ branch: typeof raw.worktree.branch === "string" ? raw.worktree.branch : "",
99
+ cleanedUp: raw.worktree.cleanedUp === true,
100
+ }
101
+ : undefined,
102
+ evidence: isRecord(raw.evidence)
103
+ ? {
104
+ verdict: (typeof raw.evidence.verdict === "string"
105
+ ? raw.evidence.verdict
106
+ : "unverified"),
107
+ matchedFiles: Number(raw.evidence.matchedFiles) || 0,
108
+ files: Number(raw.evidence.files) || 0,
109
+ matchedCommands: Number(raw.evidence.matchedCommands) || 0,
110
+ commands: Number(raw.evidence.commands) || 0,
111
+ none: raw.evidence.none === true,
112
+ blocked: typeof raw.evidence.blocked === "string" ? raw.evidence.blocked : undefined,
113
+ issues: Array.isArray(raw.evidence.issues)
114
+ ? raw.evidence.issues.filter((x) => typeof x === "string")
115
+ : [],
116
+ warnings: Array.isArray(raw.evidence.warnings)
117
+ ? raw.evidence.warnings.filter((x) => typeof x === "string")
118
+ : [],
119
+ }
120
+ : undefined,
121
+ error: typeof raw.error === "string" ? raw.error : undefined,
122
+ outputTail: typeof raw.outputTail === "string" ? raw.outputTail : undefined,
123
+ resumedFrom: typeof raw.resumedFrom === "string" ? raw.resumedFrom : undefined,
124
+ resumedBy: typeof raw.resumedBy === "string" ? raw.resumedBy : undefined,
125
+ eventsTruncated: raw.eventsTruncated === true,
126
+ };
127
+ }
128
+ /**
129
+ * 单进程、单 dataDir 一份实例(`getSubagentLedger()` 缓存)。多 ClientSession 共享同一份运行账本。
130
+ */
131
+ export class SubagentLedger {
132
+ root;
133
+ maxRuns;
134
+ now;
135
+ eventBytesCap;
136
+ records = new Map();
137
+ eventBytes = new Map();
138
+ queues = new Map();
139
+ readyPromise;
140
+ lastErrorValue;
141
+ constructor(dataDir, opts = {}) {
142
+ this.root = join(dataDir, "subagent-runs");
143
+ this.maxRuns = opts.maxRuns ?? ledgerMaxRunsFromEnv();
144
+ this.now = opts.now ?? (() => Date.now());
145
+ this.eventBytesCap = Math.max(0, opts.eventBytesCap ?? LEDGER_EVENT_BYTES_CAP);
146
+ }
147
+ get enabled() {
148
+ return this.maxRuns > 0;
149
+ }
150
+ lastError() {
151
+ return this.lastErrorValue;
152
+ }
153
+ runDir(runId) {
154
+ return join(this.root, safeSegment(runId));
155
+ }
156
+ statusPath(runId) {
157
+ return join(this.runDir(runId), "status.json");
158
+ }
159
+ eventsPath(runId) {
160
+ return join(this.runDir(runId), "events.jsonl");
161
+ }
162
+ /** 首次读取时把磁盘上的记录装进内存;后续读走内存,写走串行队列。 */
163
+ ready() {
164
+ if (!this.enabled)
165
+ return Promise.resolve();
166
+ this.readyPromise ??= this.load();
167
+ return this.readyPromise;
168
+ }
169
+ async load() {
170
+ let entries = [];
171
+ try {
172
+ entries = await readdir(this.root);
173
+ }
174
+ catch {
175
+ return;
176
+ }
177
+ for (const entry of entries) {
178
+ const dir = join(this.root, entry);
179
+ try {
180
+ const [raw, size] = await Promise.all([readFile(join(dir, "status.json"), "utf8"), this.eventsSize(dir)]);
181
+ const record = normalizeRecord(JSON.parse(raw));
182
+ if (!record)
183
+ continue;
184
+ this.records.set(record.runId, record);
185
+ this.eventBytes.set(record.runId, size);
186
+ }
187
+ catch {
188
+ // 半写的目录/损坏的 status:跳过,不影响其它 run。
189
+ }
190
+ }
191
+ }
192
+ async eventsSize(dir) {
193
+ try {
194
+ return (await stat(join(dir, "events.jsonl"))).size;
195
+ }
196
+ catch {
197
+ return 0;
198
+ }
199
+ }
200
+ enqueue(runId, task) {
201
+ const prev = this.queues.get(runId) ?? Promise.resolve();
202
+ const next = prev.then(task).catch((error) => {
203
+ this.lastErrorValue = error instanceof Error ? error.message : String(error);
204
+ });
205
+ this.queues.set(runId, next);
206
+ void next.then(() => {
207
+ if (this.queues.get(runId) === next)
208
+ this.queues.delete(runId);
209
+ });
210
+ }
211
+ /** 写入/更新一条运行记录(与已有记录字段合并)。 */
212
+ upsert(patch) {
213
+ if (!this.enabled || !patch.runId)
214
+ return;
215
+ const previous = this.records.get(patch.runId);
216
+ const next = {
217
+ ...previous,
218
+ ...patch,
219
+ prompt: boundText(patch.prompt || previous?.prompt, LEDGER_PROMPT_CAP) ?? "",
220
+ outputTail: boundText(patch.outputTail ?? previous?.outputTail, LEDGER_OUTPUT_CAP),
221
+ createdAt: previous?.createdAt ?? patch.createdAt ?? this.now(),
222
+ updatedAt: patch.updatedAt ?? this.now(),
223
+ bootId: patch.bootId || previous?.bootId || BOOT_ID,
224
+ };
225
+ this.records.set(next.runId, next);
226
+ this.enqueue(next.runId, async () => {
227
+ await mkdir(this.runDir(next.runId), { recursive: true });
228
+ await writeAtomic(this.statusPath(next.runId), `${JSON.stringify(next, null, 2)}\n`);
229
+ });
230
+ void this.ready().then(() => this.prune());
231
+ }
232
+ /** 追加一条生命周期事件;超过字节上限后只打一条截断标记。 */
233
+ event(runId, event, detail) {
234
+ if (!this.enabled || !runId)
235
+ return;
236
+ const record = this.records.get(runId);
237
+ if (record?.eventsTruncated)
238
+ return;
239
+ const bytes = this.eventBytes.get(runId) ?? 0;
240
+ if (bytes >= this.eventBytesCap) {
241
+ this.records.set(runId, { ...record, eventsTruncated: true, runId });
242
+ this.enqueue(runId, async () => {
243
+ await mkdir(this.runDir(runId), { recursive: true });
244
+ await appendFile(this.eventsPath(runId), `${JSON.stringify({ ts: this.now(), event: "events_truncated" })}\n`);
245
+ });
246
+ return;
247
+ }
248
+ const line = `${JSON.stringify({ ts: this.now(), event, ...(detail ? { detail } : {}) })}\n`;
249
+ this.eventBytes.set(runId, bytes + line.length);
250
+ this.enqueue(runId, async () => {
251
+ await mkdir(this.runDir(runId), { recursive: true });
252
+ await appendFile(this.eventsPath(runId), line);
253
+ });
254
+ }
255
+ /** 读某个 run 的最近事件(尾部),给 get_result 的账本回落做生命周期回放。 */
256
+ async events(runId, limit = 8) {
257
+ if (!this.enabled)
258
+ return [];
259
+ await this.ready();
260
+ const cap = Math.max(1, Math.min(limit, 50));
261
+ try {
262
+ const raw = await readFile(this.eventsPath(runId), "utf8");
263
+ const lines = raw
264
+ .trim()
265
+ .split("\n")
266
+ .filter((line) => line.length > 0)
267
+ .slice(-cap);
268
+ const out = [];
269
+ for (const line of lines) {
270
+ try {
271
+ const parsed = JSON.parse(line);
272
+ if (parsed && typeof parsed.event === "string")
273
+ out.push(parsed);
274
+ }
275
+ catch {
276
+ // 半写的行直接跳过。
277
+ }
278
+ }
279
+ return out;
280
+ }
281
+ catch {
282
+ return [];
283
+ }
284
+ }
285
+ read(runId) {
286
+ return this.records.get(runId);
287
+ }
288
+ list(filter = {}) {
289
+ if (!this.enabled)
290
+ return [];
291
+ const out = [];
292
+ for (const record of this.records.values()) {
293
+ if (filter.parentRunId && record.parentRunId !== filter.parentRunId)
294
+ continue;
295
+ if (filter.live === true && record.state !== "running")
296
+ continue;
297
+ out.push(record);
298
+ }
299
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
300
+ }
301
+ /** 重启对账:别的 boot 留下的 running 一律判 interrupted(本 boot 的活运行不动)。 */
302
+ async recover() {
303
+ if (!this.enabled)
304
+ return [];
305
+ await this.ready();
306
+ const recovered = [];
307
+ for (const record of [...this.records.values()]) {
308
+ if (record.state !== "running" || record.bootId === BOOT_ID)
309
+ continue;
310
+ const next = { ...record, state: "interrupted", updatedAt: this.now() };
311
+ this.records.set(next.runId, next);
312
+ recovered.push(next);
313
+ this.event(next.runId, "interrupted", { bootId: record.bootId });
314
+ this.upsert(next);
315
+ }
316
+ await this.flush();
317
+ return recovered;
318
+ }
319
+ /** 标记某个 run 已被续跑(记录新 run 身份,避免重复续跑)。 */
320
+ markResumed(runId, newRunId) {
321
+ const record = this.records.get(runId);
322
+ if (!record)
323
+ return;
324
+ // 还在 running 却没活着的运行(例如上次进程没来得及收口):续跑即视为中断后重派。
325
+ const state = record.state === "running" ? "interrupted" : record.state;
326
+ this.upsert({ ...record, state, resumedBy: newRunId, updatedAt: this.now() });
327
+ this.event(runId, "resumed", { runId: newRunId });
328
+ }
329
+ flush() {
330
+ return Promise.all([...this.queues.values()]).then(() => undefined);
331
+ }
332
+ /** 只保留最近 maxRuns 个 run 目录(活运行最后才考虑)。 */
333
+ async prune() {
334
+ if (this.records.size <= this.maxRuns)
335
+ return;
336
+ const candidates = [...this.records.values()]
337
+ .filter((record) => record.state !== "running")
338
+ .sort((a, b) => a.updatedAt - b.updatedAt);
339
+ for (const record of candidates) {
340
+ if (this.records.size <= this.maxRuns)
341
+ return;
342
+ this.records.delete(record.runId);
343
+ this.eventBytes.delete(record.runId);
344
+ // 先等这个 run 的写队列排空,否则排队中的 mkdir 会在 rm 之后把目录又建回来。
345
+ await (this.queues.get(record.runId) ?? Promise.resolve()).catch(() => { });
346
+ try {
347
+ await rm(this.runDir(record.runId), { recursive: true, force: true });
348
+ }
349
+ catch {
350
+ // 删不掉就下次再删;账本不能因此报错给用户。
351
+ }
352
+ }
353
+ }
354
+ }
355
+ /**
356
+ * 续跑提示词:子代理会话在进程内,重启后接不上原转录,所以把「原任务 + 已知进度 + 证据 + 工作树」
357
+ * 原样交给新的一次运行,并要求它别重做已完成的部分。
358
+ */
359
+ export function buildResumePrompt(record, extra) {
360
+ const parts = [
361
+ `[Resume] An earlier run of this task was interrupted (runId=${record.runId}, state=${record.state}).`,
362
+ "Original task:",
363
+ record.prompt || "(the original prompt was not recorded)",
364
+ ];
365
+ if (record.outputTail)
366
+ parts.push("Last output before the interruption (tail):", record.outputTail);
367
+ if (record.evidence) {
368
+ const ev = record.evidence;
369
+ parts.push(`Evidence on record: ${ev.verdict} (files ${ev.matchedFiles}/${ev.files}, commands ${ev.matchedCommands}/${ev.commands}).`);
370
+ }
371
+ if (record.worktree && !record.worktree.cleanedUp) {
372
+ parts.push(`Worktree kept at ${record.worktree.path} (branch ${record.worktree.branch}); reuse it instead of creating a new one.`);
373
+ }
374
+ if (record.sessionFile) {
375
+ parts.push(`The old transcript is at ${record.sessionFile} — read it if you need the details.`);
376
+ }
377
+ if (extra && extra.trim())
378
+ parts.push("Additional instruction from the supervisor:", extra.trim());
379
+ parts.push('Continue from there: do not redo finished work, re-verify what you keep, and finish with conversation(action="complete", summary, evidence).');
380
+ return parts.join("\n");
381
+ }
382
+ const ledgers = new Map();
383
+ /** dataDir 级单例:同一进程里所有 ClientSession 共用一份账本。 */
384
+ export function getSubagentLedger(dataDir, opts) {
385
+ const key = dataDir;
386
+ const existing = ledgers.get(key);
387
+ if (existing)
388
+ return existing;
389
+ const created = new SubagentLedger(dataDir, opts);
390
+ ledgers.set(key, created);
391
+ return created;
392
+ }
393
+ let disabledLedger;
394
+ /** 没有 dataDir 的宿主(测试假体、纯内存引擎)用它:整本账禁用,绝不落盘。 */
395
+ export function disabledSubagentLedger() {
396
+ return (disabledLedger ??= new SubagentLedger("", { maxRuns: 0 }));
397
+ }
398
+ /** 测试用:清掉单例缓存,避免跨用例共享账本。 */
399
+ export function resetSubagentLedgersForTests() {
400
+ ledgers.clear();
401
+ }
@@ -1,5 +1,6 @@
1
1
  import { pick } from "./i18n.js";
2
2
  import { subagentRunOutcome } from "./subagent-helpers.js";
3
+ import { formatEvidenceSummary } from "./subagent-evidence.js";
3
4
  export function extractSubagentConclusion(output, lang = "en") {
4
5
  const trimmed = (output ?? "").trim();
5
6
  if (!trimmed) {
@@ -50,6 +51,9 @@ export function formatSubagentsCompletionNotice(subagents, lang = "en", fallback
50
51
  const manualSummary = !outcome.error && !outcome.canceled && conv.subagentTask?.mode === "manual"
51
52
  ? conv.subagentTask.summary?.trim()
52
53
  : undefined;
54
+ const evidenceLine = conv.subagentEvidence
55
+ ? ` - ${pick(lang, "完成证据", "Evidence", "subagents.notify.evidence")}: ${formatEvidenceSummary(conv.subagentEvidence, lang)}\n`
56
+ : "";
53
57
  const rawOutput = manualSummary || conv.session.getLastAssistantText() || "";
54
58
  const conclusion = extractSubagentConclusion(rawOutput, lang);
55
59
  const indentedConclusion = conclusion
@@ -70,8 +74,8 @@ export function formatSubagentsCompletionNotice(subagents, lang = "en", fallback
70
74
  `\n - ${pick(lang, "工作树路径", "Worktree path", "subagents.notify.worktree.path")}: ${wt.worktreePath}\n`;
71
75
  }
72
76
  }
73
- return `- **${sId}**(${metaTag})— ${statusLabel}\n${taskLine}${wtLine} - ${pick(lang, "产出摘要", "Summary", "subagents.notify.summary")}:\n${indentedConclusion}`;
77
+ return `- **${sId}**(${metaTag})— ${statusLabel}\n${taskLine}${wtLine}${evidenceLine} - ${pick(lang, "产出摘要", "Summary", "subagents.notify.summary")}:\n${indentedConclusion}`;
74
78
  });
75
- const footer = pick(lang, '\n如需调取子代理完整对话转录与工具执行详情,可调用 subagent(action="get_result", runId="<id>")。', '\nFor full transcripts or detailed tool logs, call subagent(action="get_result", runId="<id>").', "subagents.notify.footer");
79
+ const footer = pick(lang, '\n如需调取子代理完整对话转录与工具执行详情,可调用 conversation(action="get_result", runId="<id>")。', '\nFor full transcripts or detailed tool logs, call conversation(action="get_result", runId="<id>").', "subagents.notify.footer");
76
80
  return `${fallbackNote}${titleHeader}\n\n${items.join("\n\n")}${footer}`;
77
81
  }
@@ -191,8 +191,8 @@ export function subagentSecurityDenial(mode, toolName, params, allowedTools) {
191
191
  if (!isReadOnlyConversationAction(act)) {
192
192
  return {
193
193
  kind: "dispatch-tool",
194
- reason: `受限子代理(${mode}):禁止调用 subagent(action="${act || "spawn"}") 派生或操控其他子代理。`,
195
- reasonEn: `Restricted subagent (${mode}): subagent(action="${act || "spawn"}") is blocked in restricted mode.`,
194
+ reason: `受限子代理(${mode}):禁止调用 conversation(action="${act || "spawn"}") 派生或操控其他子代理。`,
195
+ reasonEn: `Restricted subagent (${mode}): conversation(action="${act || "spawn"}") is blocked in restricted mode.`,
196
196
  };
197
197
  }
198
198
  }
@@ -0,0 +1,71 @@
1
+ export class SubagentSettleRegistry {
2
+ perId = new Map();
3
+ global = new Set();
4
+ /** 当前挂起的等待数(测试与诊断用)。 */
5
+ get waiting() {
6
+ return this.global.size;
7
+ }
8
+ /** 某个运行发生变化:只唤醒订阅了它的等待方。 */
9
+ notify(id) {
10
+ if (!id)
11
+ return;
12
+ const set = this.perId.get(id);
13
+ if (!set || set.size === 0)
14
+ return;
15
+ for (const waiter of [...set])
16
+ waiter.fire("changed");
17
+ }
18
+ /** 粗粒度变化(问卷队列、通知投递状态):唤醒全部等待方,让它们各自重新判定。 */
19
+ notifyAll() {
20
+ for (const waiter of [...this.global])
21
+ waiter.fire("changed");
22
+ }
23
+ /** 关闭时把挂起的等待收干净,避免等待方卡到超时。 */
24
+ shutdown() {
25
+ for (const waiter of [...this.global])
26
+ waiter.fire("aborted");
27
+ this.perId.clear();
28
+ this.global.clear();
29
+ }
30
+ waitFor(ids, opts) {
31
+ const unique = [...new Set(ids)].filter((id) => typeof id === "string" && id.length > 0);
32
+ const timeoutMs = Number.isFinite(opts.timeoutMs) ? Math.max(0, Math.floor(opts.timeoutMs)) : 0;
33
+ if (opts.signal?.aborted)
34
+ return Promise.resolve("aborted");
35
+ if (timeoutMs === 0)
36
+ return Promise.resolve("timeout");
37
+ return new Promise((resolve) => {
38
+ let done = false;
39
+ let timer;
40
+ const finish = (reason) => {
41
+ if (done)
42
+ return;
43
+ done = true;
44
+ if (timer)
45
+ clearTimeout(timer);
46
+ this.global.delete(waiter);
47
+ for (const id of unique) {
48
+ const set = this.perId.get(id);
49
+ if (!set)
50
+ continue;
51
+ set.delete(waiter);
52
+ if (set.size === 0)
53
+ this.perId.delete(id);
54
+ }
55
+ opts.signal?.removeEventListener("abort", onAbort);
56
+ resolve(reason);
57
+ };
58
+ const onAbort = () => finish("aborted");
59
+ const waiter = { fire: (reason) => finish(reason) };
60
+ timer = setTimeout(() => finish("timeout"), timeoutMs);
61
+ timer.unref?.();
62
+ this.global.add(waiter);
63
+ for (const id of unique) {
64
+ const set = this.perId.get(id) ?? new Set();
65
+ set.add(waiter);
66
+ this.perId.set(id, set);
67
+ }
68
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
69
+ });
70
+ }
71
+ }