@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.10

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 (186) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +28 -0
  3. package/dist/agent/channel-runner.js +293 -145
  4. package/dist/agent/commands.d.ts +7 -1
  5. package/dist/agent/commands.js +26 -0
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +1 -1
  8. package/dist/agent/job-manager.d.ts +34 -6
  9. package/dist/agent/job-manager.js +73 -7
  10. package/dist/agent/progress-formatter.js +3 -3
  11. package/dist/agent/prompt/sections.js +46 -7
  12. package/dist/agent/prompt/types.d.ts +9 -0
  13. package/dist/agent/run-queue.d.ts +10 -1
  14. package/dist/agent/run-queue.js +19 -2
  15. package/dist/agent/runner-factory.d.ts +16 -4
  16. package/dist/agent/runner-factory.js +9 -23
  17. package/dist/agent/session-events.js +7 -42
  18. package/dist/agent/session-resource-gate.d.ts +17 -0
  19. package/dist/agent/session-resource-gate.js +33 -2
  20. package/dist/agent/status-render.js +1 -3
  21. package/dist/agent/turn-recovery.d.ts +72 -0
  22. package/dist/agent/turn-recovery.js +193 -0
  23. package/dist/agent/types.d.ts +21 -1
  24. package/dist/agent/types.js +3 -16
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +2 -1
  27. package/dist/main.js +2 -1
  28. package/dist/memory/extraction.js +0 -1
  29. package/dist/memory/maintenance-gates.d.ts +1 -1
  30. package/dist/memory/maintenance-jobs.js +2 -3
  31. package/dist/memory/metadata.d.ts +0 -15
  32. package/dist/memory/metadata.js +0 -7
  33. package/dist/memory/probation.d.ts +1 -5
  34. package/dist/memory/probation.js +2 -6
  35. package/dist/memory/review-log.js +0 -0
  36. package/dist/memory/scheduler.d.ts +1 -0
  37. package/dist/memory/scheduler.js +64 -6
  38. package/dist/models/auth-cli.d.ts +1 -1
  39. package/dist/models/auth-cli.js +3 -2
  40. package/dist/paths.d.ts +0 -6
  41. package/dist/paths.js +0 -6
  42. package/dist/playbooks/agent-delegation.md +48 -22
  43. package/dist/playbooks/background-jobs.md +1 -1
  44. package/dist/playbooks/catalog.d.ts +2 -2
  45. package/dist/playbooks/catalog.js +20 -9
  46. package/dist/playbooks/event-scheduling.md +1 -1
  47. package/dist/playbooks/memory-and-learning.md +1 -1
  48. package/dist/playbooks/outbound-media.md +5 -5
  49. package/dist/playbooks/runtime-orientation.md +8 -3
  50. package/dist/playbooks/task-driving.md +1 -1
  51. package/dist/playbooks/task-planning.md +1 -1
  52. package/dist/runtime/active-session-store.d.ts +42 -0
  53. package/dist/runtime/active-session-store.js +100 -0
  54. package/dist/runtime/app-home.d.ts +32 -0
  55. package/dist/runtime/app-home.js +319 -0
  56. package/dist/runtime/bootstrap.d.ts +30 -36
  57. package/dist/runtime/bootstrap.js +359 -473
  58. package/dist/runtime/channel-event.d.ts +41 -0
  59. package/dist/runtime/channel-event.js +1 -0
  60. package/dist/runtime/delivery.d.ts +3 -2
  61. package/dist/runtime/delivery.js +11 -6
  62. package/dist/runtime/dingtalk.d.ts +16 -28
  63. package/dist/runtime/dingtalk.js +6 -10
  64. package/dist/runtime/durable-dispatch.d.ts +8 -2
  65. package/dist/runtime/durable-dispatch.js +52 -25
  66. package/dist/runtime/events.d.ts +3 -2
  67. package/dist/runtime/events.js +2 -3
  68. package/dist/runtime/project-commands.d.ts +16 -0
  69. package/dist/runtime/project-commands.js +112 -0
  70. package/dist/runtime/project-scope-store.d.ts +31 -0
  71. package/dist/runtime/project-scope-store.js +102 -0
  72. package/dist/runtime/store.d.ts +7 -0
  73. package/dist/runtime/subagent-commands.d.ts +17 -0
  74. package/dist/runtime/subagent-commands.js +360 -0
  75. package/dist/runtime/task-commands.js +7 -3
  76. package/dist/runtime/task-driver.d.ts +7 -7
  77. package/dist/runtime/task-driver.js +1 -4
  78. package/dist/runtime/task-migration.js +1 -1
  79. package/dist/runtime/task-wake.d.ts +54 -0
  80. package/dist/runtime/task-wake.js +99 -0
  81. package/dist/security/config.js +10 -0
  82. package/dist/security/logger.js +10 -1
  83. package/dist/security/path-guard.js +34 -9
  84. package/dist/security/project-scope.d.ts +45 -0
  85. package/dist/security/project-scope.js +107 -0
  86. package/dist/security/types.d.ts +37 -3
  87. package/dist/settings.d.ts +0 -106
  88. package/dist/settings.js +0 -224
  89. package/dist/shared/host-process.d.ts +37 -0
  90. package/dist/shared/host-process.js +112 -0
  91. package/dist/shared/jsonl-appender.d.ts +2 -0
  92. package/dist/shared/jsonl-appender.js +25 -13
  93. package/dist/shared/shell-words.d.ts +9 -0
  94. package/dist/shared/shell-words.js +52 -0
  95. package/dist/shared/types.d.ts +1 -0
  96. package/dist/shared/types.js +10 -1
  97. package/dist/shared/wake-claim.d.ts +23 -0
  98. package/dist/shared/wake-claim.js +26 -0
  99. package/dist/shared/with-timeout.d.ts +14 -0
  100. package/dist/shared/with-timeout.js +38 -0
  101. package/dist/subagents/detached-discovery.d.ts +13 -0
  102. package/dist/subagents/detached-discovery.js +17 -0
  103. package/dist/subagents/discovery.d.ts +74 -1
  104. package/dist/subagents/discovery.js +429 -82
  105. package/dist/subagents/external/claude-code.d.ts +2 -0
  106. package/dist/subagents/external/claude-code.js +158 -0
  107. package/dist/subagents/external/codex-cli.d.ts +2 -0
  108. package/dist/subagents/external/codex-cli.js +133 -0
  109. package/dist/subagents/external/exec.d.ts +2 -0
  110. package/dist/subagents/external/exec.js +44 -0
  111. package/dist/subagents/external/harness.d.ts +121 -0
  112. package/dist/subagents/external/harness.js +109 -0
  113. package/dist/subagents/external/registry.d.ts +2 -0
  114. package/dist/subagents/external/registry.js +11 -0
  115. package/dist/subagents/external/run.d.ts +74 -0
  116. package/dist/subagents/external/run.js +286 -0
  117. package/dist/subagents/external/settlement.d.ts +50 -0
  118. package/dist/subagents/external/settlement.js +123 -0
  119. package/dist/subagents/format.d.ts +16 -0
  120. package/dist/subagents/format.js +31 -0
  121. package/dist/subagents/runs.d.ts +342 -0
  122. package/dist/subagents/runs.js +909 -0
  123. package/dist/subagents/tool.d.ts +68 -6
  124. package/dist/subagents/tool.js +547 -206
  125. package/dist/subagents/verification-outcome.d.ts +26 -0
  126. package/dist/subagents/verification-outcome.js +16 -0
  127. package/dist/subagents/workspace-lease.d.ts +45 -0
  128. package/dist/subagents/workspace-lease.js +61 -0
  129. package/dist/tasks/artifact-subject.js +50 -2
  130. package/dist/tasks/control.d.ts +12 -0
  131. package/dist/tasks/control.js +20 -0
  132. package/dist/tasks/ledger.js +1 -1
  133. package/dist/tasks/store.d.ts +21 -0
  134. package/dist/tasks/store.js +80 -0
  135. package/dist/{shared → tasks}/task-schedule.js +1 -1
  136. package/dist/tasks/verification.d.ts +8 -0
  137. package/dist/tasks/verification.js +10 -2
  138. package/dist/tools/bash.js +4 -4
  139. package/dist/tools/edit.js +3 -3
  140. package/dist/tools/event-manage.js +1 -4
  141. package/dist/tools/grep.js +5 -6
  142. package/dist/tools/index.d.ts +4 -1
  143. package/dist/tools/index.js +25 -3
  144. package/dist/tools/job.js +5 -5
  145. package/dist/tools/memory-manage.js +3 -7
  146. package/dist/tools/read.js +3 -3
  147. package/dist/tools/registry.js +2 -1
  148. package/dist/tools/send-media.js +2 -2
  149. package/dist/tools/session-search.js +0 -1
  150. package/dist/tools/skill-manage.js +3 -3
  151. package/dist/tools/subagent-manage.d.ts +37 -0
  152. package/dist/tools/subagent-manage.js +245 -0
  153. package/dist/tools/task-manage/shared.js +2 -2
  154. package/dist/tools/task-manage.js +1 -4
  155. package/dist/tools/tool-details.d.ts +1 -1
  156. package/dist/tools/web-fetch.js +0 -1
  157. package/dist/tools/write-content.js +3 -3
  158. package/dist/tui/app.d.ts +1 -1
  159. package/dist/tui/app.js +55 -6
  160. package/dist/tui/cli.d.ts +1 -1
  161. package/dist/tui/cli.js +1 -1
  162. package/dist/tui/commands.d.ts +2 -0
  163. package/dist/tui/commands.js +4 -0
  164. package/dist/tui/terminal-media-sender.d.ts +1 -1
  165. package/dist/tui/turn-controller.d.ts +2 -0
  166. package/dist/tui/turn-controller.js +2 -0
  167. package/dist/usage/ledger.d.ts +13 -0
  168. package/dist/usage/ledger.js +15 -2
  169. package/dist/usage/render.js +22 -0
  170. package/examples/sub-agents/README.md +75 -14
  171. package/examples/sub-agents/builder-hard.md +46 -0
  172. package/examples/sub-agents/builder.md +42 -0
  173. package/examples/sub-agents/documenter.md +50 -0
  174. package/examples/sub-agents/explorer.md +16 -13
  175. package/examples/sub-agents/git-committer.md +33 -40
  176. package/examples/sub-agents/log-sifter.md +46 -0
  177. package/examples/sub-agents/planner.md +42 -0
  178. package/examples/sub-agents/reviewer.md +31 -41
  179. package/examples/sub-agents/scout.md +30 -0
  180. package/examples/sub-agents/verifier.md +27 -37
  181. package/examples/sub-agents/worker.md +35 -0
  182. package/package.json +1 -1
  183. package/examples/sub-agents/researcher.md +0 -41
  184. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  185. /package/dist/{shared → tasks}/task-events.js +0 -0
  186. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -27,6 +27,13 @@ export interface LoggedSubAgentRun {
27
27
  failureReason?: string;
28
28
  output: string;
29
29
  outputTruncated: boolean;
30
+ /** Spec 040, D7: the run this entry archives, and its lifecycle context. Only set on terminal archiving. */
31
+ runId?: string;
32
+ runtime?: "internal" | "external";
33
+ harness?: "claude-code" | "codex-cli" | "exec";
34
+ status?: "completed" | "failed" | "cancelled" | "lost";
35
+ taskId?: string;
36
+ artifactDir?: string;
30
37
  usage: {
31
38
  input: number;
32
39
  output: number;
@@ -0,0 +1,17 @@
1
+ import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
2
+ /**
3
+ * `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
4
+ * by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
5
+ * bot/event coupling.
6
+ */
7
+ export interface HandleSubagentsCommandOptions {
8
+ args: string;
9
+ channelId: string;
10
+ /** Best-effort role-directory snapshot for `roles` / the overview tail; omitted when no runner
11
+ * is currently active for this channel (mirrors how `/status` degrades without a live runner). */
12
+ discovery?: SubAgentDiscoveryResult;
13
+ /** Fallback used only when `discovery` is absent: resolves the role directory from disk without
14
+ * a live `ChannelRunner` (spec 041). Lazy — never called unless a `roles` view is actually rendered. */
15
+ getDetachedDiscovery?: () => Promise<SubAgentDiscoveryResult>;
16
+ }
17
+ export declare function handleSubagentsCommand(options: HandleSubagentsCommandOptions): Promise<string>;
@@ -0,0 +1,360 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { errorMessage } from "../shared/text-utils.js";
4
+ import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
5
+ import { getSubAgentRunManager } from "../subagents/runs.js";
6
+ function usage() {
7
+ return `# 委派 Run
8
+
9
+ 用法:
10
+
11
+ - \`/subagents\` — 运行中的 run + 最近完成的几条 + 角色目录摘要
12
+ - \`/subagents list [running|failed|all]\` — 按状态筛选
13
+ - \`/subagents show <runId>\` — 单个 run 的完整详情(含实际 argv、stderr 尾部)
14
+ - \`/subagents output <runId>\` — 该 run 的文本产出(output.md 尾部)
15
+ - \`/subagents cancel <runId|all>\` — 直接终止,不经过模型
16
+ - \`/subagents roles [name]\` — 角色目录;带 name 时查看单个角色的详情
17
+
18
+ \`runId\` 支持不带 \`run_\` 前缀的简写,只要能唯一匹配即可,例如 \`show a1b2c3\`。`;
19
+ }
20
+ function parseSubagentsCommand(args) {
21
+ const parts = args.trim().split(/\s+/).filter(Boolean);
22
+ const action = parts[0];
23
+ if (!action || action === "list") {
24
+ const filterArg = parts[1];
25
+ if (!filterArg) {
26
+ if (parts.length > 1)
27
+ throw new Error("用法:/subagents [list] [running|failed|all]");
28
+ return { action: "list", filter: "default" };
29
+ }
30
+ if ((filterArg !== "running" && filterArg !== "failed" && filterArg !== "all") || parts.length > 2) {
31
+ throw new Error("用法:/subagents list [running|failed|all]");
32
+ }
33
+ return { action: "list", filter: filterArg };
34
+ }
35
+ if (action === "show") {
36
+ if (!parts[1] || parts.length > 2)
37
+ throw new Error("用法:/subagents show <runId>");
38
+ return { action: "show", ref: parts[1] };
39
+ }
40
+ if (action === "output") {
41
+ if (!parts[1] || parts.length > 2)
42
+ throw new Error("用法:/subagents output <runId>");
43
+ return { action: "output", ref: parts[1] };
44
+ }
45
+ if (action === "cancel") {
46
+ if (!parts[1] || parts.length > 2)
47
+ throw new Error("用法:/subagents cancel <runId|all>");
48
+ return { action: "cancel", ref: parts[1] };
49
+ }
50
+ if (action === "roles") {
51
+ if (parts.length > 2)
52
+ throw new Error("用法:/subagents roles [name]");
53
+ return { action: "roles", name: parts[1] };
54
+ }
55
+ throw new Error(`未知的 /subagents 子命令:${action}`);
56
+ }
57
+ function statusLabel(status) {
58
+ switch (status) {
59
+ case "running":
60
+ return "运行中";
61
+ case "completed":
62
+ return "已完成";
63
+ case "failed":
64
+ return "失败";
65
+ case "cancelled":
66
+ return "已取消";
67
+ case "lost":
68
+ return "丢失(daemon 重启或无法确认)";
69
+ }
70
+ }
71
+ function formatRunLine(record) {
72
+ const bits = [harnessLabel(record), formatRunDuration(record)];
73
+ if (record.taskId)
74
+ bits.push(`task ${record.taskId}`);
75
+ if (record.leaseKey)
76
+ bits.push("持有写锁");
77
+ const cost = formatCost(record);
78
+ if (cost)
79
+ bits.push(cost);
80
+ const header = `- \`${record.runId}\` ${record.agent} (${bits.join(", ")}) — ${statusLabel(record.status)} — "${record.label}"`;
81
+ if (record.status === "failed" && record.failureReason) {
82
+ return `${header}\n 失败原因:${record.failureReason}`;
83
+ }
84
+ return header;
85
+ }
86
+ async function resolveDiscovery(options) {
87
+ if (options.discovery)
88
+ return options.discovery;
89
+ if (!options.getDetachedDiscovery)
90
+ return undefined;
91
+ try {
92
+ return await options.getDetachedDiscovery();
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ function formatRolesTail(discovery) {
99
+ const unavailable = discovery.agents.filter((agent) => agent.unavailable);
100
+ const available = discovery.agents.length - unavailable.length;
101
+ const parts = [`角色目录:${available} 个可用`];
102
+ if (unavailable.length > 0)
103
+ parts.push(`${unavailable.length} 个不可用`);
104
+ let line = `${parts.join(",")} — 用 /subagents roles 查看`;
105
+ for (const warning of discovery.warnings) {
106
+ line += `\n⚠ discovery: ${warning}`;
107
+ }
108
+ return line;
109
+ }
110
+ const DEFAULT_LIST_COMPLETED_LIMIT = 5;
111
+ /** Spec 042 D9: `running`/`failed`/`all` had no cap at all — a long-lived channel with thousands
112
+ * of historical runs (GC now reclaims them after 7 days, but that is still a lot in a busy week)
113
+ * would otherwise dump an unbounded list into a single reply. */
114
+ const LIST_FILTER_CAP = 50;
115
+ function capListForDisplay(records) {
116
+ if (records.length <= LIST_FILTER_CAP)
117
+ return { shown: records };
118
+ return {
119
+ shown: records.slice(0, LIST_FILTER_CAP),
120
+ truncatedNote: `显示最近 ${LIST_FILTER_CAP} 条,共 ${records.length} 条——用更具体的筛选缩小范围。`,
121
+ };
122
+ }
123
+ async function listRuns(options, filter) {
124
+ const records = getSubAgentRunManager(options.channelId).list();
125
+ if (records.length === 0)
126
+ return "# 委派 Run\n\n没有委派记录。";
127
+ const running = records.filter((record) => record.status === "running").sort((a, b) => b.startedAt - a.startedAt);
128
+ const terminal = records
129
+ .filter((record) => record.status !== "running")
130
+ .sort((a, b) => (b.finishedAt ?? b.startedAt) - (a.finishedAt ?? a.startedAt));
131
+ const sections = [];
132
+ if (filter === "running") {
133
+ const { shown, truncatedNote } = capListForDisplay(running);
134
+ sections.push(shown.length === 0 ? "没有正在运行的 run。" : shown.map(formatRunLine).join("\n"));
135
+ if (truncatedNote)
136
+ sections.push(truncatedNote);
137
+ return `# 委派 Run — 运行中\n\n${sections.join("\n\n")}`;
138
+ }
139
+ if (filter === "failed") {
140
+ const { shown, truncatedNote } = capListForDisplay(terminal.filter((record) => record.status === "failed"));
141
+ sections.push(shown.length === 0 ? "没有失败的 run。" : shown.map(formatRunLine).join("\n"));
142
+ if (truncatedNote)
143
+ sections.push(truncatedNote);
144
+ return `# 委派 Run — 失败\n\n${sections.join("\n\n")}`;
145
+ }
146
+ if (filter === "all") {
147
+ const { shown, truncatedNote } = capListForDisplay([...running, ...terminal]);
148
+ sections.push(shown.map(formatRunLine).join("\n"));
149
+ if (truncatedNote)
150
+ sections.push(truncatedNote);
151
+ return `# 委派 Run — 全部(${records.length})\n\n${sections.join("\n\n")}`;
152
+ }
153
+ // default: an overview — every running run, plus a capped tail of recent completions.
154
+ if (running.length > 0) {
155
+ sections.push(`## 运行中 (${running.length})\n${running.map(formatRunLine).join("\n")}`);
156
+ }
157
+ const shown = terminal.slice(0, DEFAULT_LIST_COMPLETED_LIMIT);
158
+ if (shown.length > 0) {
159
+ const countNote = terminal.length > shown.length ? `显示 ${shown.length} / 共 ${terminal.length}` : `${shown.length}`;
160
+ sections.push(`## 最近完成 (${countNote})\n${shown.map(formatRunLine).join("\n")}`);
161
+ }
162
+ if (sections.length === 0)
163
+ sections.push("没有委派记录。");
164
+ const discovery = await resolveDiscovery(options);
165
+ if (discovery)
166
+ sections.push(formatRolesTail(discovery));
167
+ sections.push("用 `/subagents show <runId>` 看详情,`/subagents output <runId>` 看产出。");
168
+ return `# 委派 Run\n\n${sections.join("\n\n")}`;
169
+ }
170
+ const STDERR_TAIL_CHARS = 2_000;
171
+ const OUTPUT_TAIL_CHARS = 4_000;
172
+ function formatRunResolution(resolution, ref) {
173
+ if (resolution.kind === "not_found")
174
+ return `未找到 run:\`${ref}\``;
175
+ if (resolution.kind === "ambiguous") {
176
+ const candidates = resolution.candidates.map((record) => `\`${record.runId}\` (${record.agent})`).join("、");
177
+ return `"${ref}" 匹配到多个 run:${candidates}。请提供更完整的 runId。`;
178
+ }
179
+ return undefined;
180
+ }
181
+ async function showRun(channelId, ref) {
182
+ const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
183
+ const error = formatRunResolution(resolution, ref);
184
+ if (error || resolution.kind !== "found")
185
+ return error ?? `未找到 run:\`${ref}\``;
186
+ const record = resolution.record;
187
+ const lines = [
188
+ `# Run \`${record.runId}\``,
189
+ "",
190
+ `角色:${record.agent} (${harnessLabel(record)}, ${record.source})`,
191
+ `标签:${record.label}`,
192
+ `状态:${statusLabel(record.status)}(耗时 ${formatRunDuration(record)})`,
193
+ ];
194
+ if (record.failureReason)
195
+ lines.push(`失败原因:${record.failureReason}`);
196
+ if (record.verificationVerdict) {
197
+ lines.push(`验收结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? "(advisory)" : ""}`);
198
+ }
199
+ lines.push(`开始:${new Date(record.startedAt).toLocaleString()}`);
200
+ if (record.finishedAt)
201
+ lines.push(`结束:${new Date(record.finishedAt).toLocaleString()}`);
202
+ lines.push(`purpose:${record.purpose}`, `工作目录:\`${record.workingDirectory}\``, `产物目录:\`${record.artifactDir}\``);
203
+ if (record.taskId)
204
+ lines.push(`所属任务:${record.taskId}`);
205
+ if (record.leaseKey)
206
+ lines.push("持有写锁:是");
207
+ if (record.model)
208
+ lines.push(`模型:${record.model}`);
209
+ const cost = formatCost(record);
210
+ lines.push(`usage:input=${record.usage.input} output=${record.usage.output}${cost ? ` cost=${cost}` : record.costKnown ? "" : "(cost 未知)"}`);
211
+ if (record.argv)
212
+ lines.push("", "实际 argv:", "```", JSON.stringify(record.argv), "```");
213
+ if (record.parserVersion !== undefined || record.cliVersion) {
214
+ // Spec 042 D12: lets a human tell "the target CLI's own protocol drifted out from under this
215
+ // adapter" apart from "the agent itself failed" — the two look identical from status alone.
216
+ const parts = [];
217
+ if (record.parserVersion !== undefined)
218
+ parts.push(`parserVersion=${record.parserVersion}`);
219
+ parts.push(`cliVersion=${record.cliVersion ?? "(未知)"}`);
220
+ lines.push(`适配器/CLI:${parts.join(",")}`);
221
+ }
222
+ if (record.invocationWarnings?.length) {
223
+ lines.push("", "⚠ 派发时的警告:", ...record.invocationWarnings.map((warning) => `- ${warning}`));
224
+ }
225
+ if (record.sessionId)
226
+ lines.push(`sessionId:\`${record.sessionId}\`(可用于 subagent_manage op=follow_up)`);
227
+ if (record.runtime === "external") {
228
+ const stderrTail = await readFile(join(record.artifactDir, "stderr.log"), "utf-8")
229
+ .then((text) => text.slice(-STDERR_TAIL_CHARS))
230
+ .catch(() => undefined);
231
+ if (stderrTail?.trim()) {
232
+ lines.push("", "## stderr (tail)", "```", stderrTail, "```");
233
+ }
234
+ }
235
+ return lines.join("\n");
236
+ }
237
+ async function showOutput(channelId, ref) {
238
+ const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
239
+ const error = formatRunResolution(resolution, ref);
240
+ if (error || resolution.kind !== "found")
241
+ return error ?? `未找到 run:\`${ref}\``;
242
+ const record = resolution.record;
243
+ const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => undefined);
244
+ if (!outputText?.trim()) {
245
+ const runningNote = record.status === "running" ? "该 run 仍在运行,可能还没有产出。" : "该 run 没有文本产出。";
246
+ return `# Run \`${record.runId}\` 的产出\n\n${runningNote}产物目录:\`${record.artifactDir}\``;
247
+ }
248
+ const tail = outputText.slice(-OUTPUT_TAIL_CHARS);
249
+ const truncatedNote = outputText.length > tail.length ? `(只显示末尾 ${OUTPUT_TAIL_CHARS} 字符,完整内容见上方产物目录)\n\n` : "";
250
+ return `# Run \`${record.runId}\` 的产出\n\n${truncatedNote}\`\`\`\n${tail}\n\`\`\``;
251
+ }
252
+ async function cancelRun(channelId, ref) {
253
+ const manager = getSubAgentRunManager(channelId);
254
+ if (ref === "all") {
255
+ const running = manager.list().filter((record) => record.status === "running");
256
+ if (running.length === 0)
257
+ return "没有正在运行的 run。";
258
+ const results = await Promise.all(running.map(async (record) => {
259
+ const status = await manager.cancel(record.runId);
260
+ return `- \`${record.runId}\` (${record.agent}):${status}`;
261
+ }));
262
+ return `# 已请求终止 ${running.length} 个 run\n\n${results.join("\n")}`;
263
+ }
264
+ const resolution = manager.resolveRef(ref);
265
+ const error = formatRunResolution(resolution, ref);
266
+ if (error || resolution.kind !== "found")
267
+ return error ?? `未找到 run:\`${ref}\``;
268
+ const status = await manager.cancel(resolution.record.runId);
269
+ return `已请求终止 run \`${resolution.record.runId}\`:${status}`;
270
+ }
271
+ function formatRoleSummaryLine(agent) {
272
+ const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
273
+ const mutates = agent.mutates ?? (agent.tools.includes("write") || agent.tools.includes("edit") ? "write" : "read");
274
+ const unavailable = agent.unavailable ? ` — ⚠ 不可用:${agent.unavailable}` : "";
275
+ return `- \`${agent.name}\` (${kind}, ${mutates}) — ${agent.description}${unavailable}`;
276
+ }
277
+ function formatRoleDetail(agent) {
278
+ const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
279
+ const lines = [
280
+ `# 角色 \`${agent.name}\``,
281
+ "",
282
+ `runtime:${kind}`,
283
+ `来源:${agent.source} (${agent.filePath ?? "inline"})`,
284
+ `说明:${agent.description}`,
285
+ ];
286
+ if (agent.unavailable)
287
+ lines.push(`⚠ 不可用:${agent.unavailable}`);
288
+ lines.push(`mutates:${agent.mutates ?? "(未声明,由 tools 推断)"}`);
289
+ if (agent.runtime === "internal") {
290
+ lines.push(`模型:${agent.modelRef ?? "(默认)"}`, `tools:${agent.tools.join(", ") || "(none)"}`, `预算:maxTurns=${agent.maxTurns} maxToolCalls=${agent.maxToolCalls} maxWallTimeSec=${agent.maxWallTimeSec} bashTimeoutSec=${agent.bashTimeoutSec}`, `contextMode:${agent.contextMode},memory:${agent.memory}`);
291
+ }
292
+ else {
293
+ lines.push(`command:\`${agent.command ?? ""}\`${agent.shell ? "(通过 shell 执行)" : ""}`, `maxWallTimeSec:${agent.maxWallTimeSec}`);
294
+ if (agent.externalModelRef)
295
+ lines.push(`模型:${agent.externalModelRef}`);
296
+ // spec 042 D4: contextMode/memory are effective for external roles too (memory 默认 none,
297
+ // 显式声明 session/relevant 才会把频道会话状态发给外部进程) — 显示出来而不是只在内置分支里说明。
298
+ lines.push(`contextMode:${agent.contextMode},memory:${agent.memory}`);
299
+ if (agent.memory !== "none") {
300
+ lines.push(`⚠ 该角色会把频道会话状态/记忆片段发送给外部进程(memory: ${agent.memory})`);
301
+ }
302
+ }
303
+ if (agent.paths.length > 0)
304
+ lines.push(`paths:${agent.paths.join(", ")}`);
305
+ lines.push("", "system prompt:", "```", agent.systemPrompt, "```");
306
+ return lines.join("\n");
307
+ }
308
+ async function showRoles(options, name) {
309
+ const discovery = await resolveDiscovery(options);
310
+ if (!discovery) {
311
+ return "角色目录不可用:本频道尚未激活过运行时,且无法在离线状态下解析模型引用。先给这个频道发一条消息,再重试。";
312
+ }
313
+ if (name) {
314
+ const agent = discovery.agents.find((candidate) => candidate.name === name);
315
+ if (!agent) {
316
+ const available = discovery.agents.length > 0 ? discovery.agents.map((a) => a.name).join(", ") : "(none)";
317
+ return `未找到角色 "${name}"。可用角色:${available}`;
318
+ }
319
+ return formatRoleDetail(agent);
320
+ }
321
+ const internal = discovery.agents.filter((agent) => agent.runtime === "internal");
322
+ const external = discovery.agents.filter((agent) => agent.runtime === "external");
323
+ const sections = [`# 角色目录\n\n目录:\`${discovery.directory}\``];
324
+ if (external.length > 0)
325
+ sections.push(`## 外部\n${external.map(formatRoleSummaryLine).join("\n")}`);
326
+ if (internal.length > 0)
327
+ sections.push(`## 内置\n${internal.map(formatRoleSummaryLine).join("\n")}`);
328
+ if (discovery.agents.length === 0)
329
+ sections.push("目录为空。");
330
+ for (const warning of discovery.warnings)
331
+ sections.push(`⚠ discovery: ${warning}`);
332
+ sections.push("用 `/subagents roles <name>` 看单个角色的详情。");
333
+ return sections.join("\n\n");
334
+ }
335
+ export async function handleSubagentsCommand(options) {
336
+ let command;
337
+ try {
338
+ command = parseSubagentsCommand(options.args);
339
+ }
340
+ catch (error) {
341
+ return `${errorMessage(error)}\n\n${usage()}`;
342
+ }
343
+ try {
344
+ switch (command.action) {
345
+ case "list":
346
+ return await listRuns(options, command.filter);
347
+ case "show":
348
+ return await showRun(options.channelId, command.ref);
349
+ case "output":
350
+ return await showOutput(options.channelId, command.ref);
351
+ case "cancel":
352
+ return await cancelRun(options.channelId, command.ref);
353
+ case "roles":
354
+ return await showRoles(options, command.name);
355
+ }
356
+ }
357
+ catch (error) {
358
+ return `执行 /subagents ${command.action} 失败:${errorMessage(error)}`;
359
+ }
360
+ }
@@ -3,14 +3,15 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { channelJobTaskIds } from "../agent/job-manager.js";
5
5
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
6
- import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
7
- import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
8
6
  import { errorMessage } from "../shared/text-utils.js";
9
7
  import { isRecord } from "../shared/type-guards.js";
8
+ import { channelDelegationTaskIds } from "../subagents/runs.js";
10
9
  import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
11
10
  import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
12
11
  import { withTaskMutation } from "../tasks/mutation-lock.js";
13
12
  import { claimTaskAttempt, openRecurringTaskCycle, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
13
+ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
14
+ import { nextTaskWake, validateTaskSchedule } from "../tasks/task-schedule.js";
14
15
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
15
16
  import { readVerificationAttestation } from "../tasks/verification.js";
16
17
  import { parseScheduledEventContent } from "./events.js";
@@ -474,6 +475,7 @@ async function doctor(options) {
474
475
  const archivedIds = await readArchivedTaskIds(options.channelDir);
475
476
  const events = await readTaskEvents(options.workspaceDir, options.channelId);
476
477
  const runningJobTaskIds = channelJobTaskIds(options.channelId);
478
+ const runningDelegationTaskIds = channelDelegationTaskIds(options.channelId);
477
479
  const issues = [];
478
480
  for (const entry of entries) {
479
481
  const status = entry.frontmatter.status ?? "active";
@@ -582,7 +584,9 @@ async function doctor(options) {
582
584
  // no running job carrying this id, whether it ever resumes is entirely up to the user.
583
585
  // That is legitimate when it is waiting on an answer — and indistinguishable, on disk,
584
586
  // from a task everyone has forgotten. Report the fact and name every way out.
585
- const hasDurableWaitingSource = control?.waitingFor === "verification" || (control?.waitingFor === "job" && runningJobTaskIds.has(entry.id));
587
+ const hasDurableWaitingSource = control?.waitingFor === "verification" ||
588
+ (control?.waitingFor === "job" && runningJobTaskIds.has(entry.id)) ||
589
+ (control?.waitingFor === "external-signal" && runningDelegationTaskIds.has(entry.id));
586
590
  if (isTaskParked(entry.frontmatter) && !hasDurableWaitingSource) {
587
591
  issues.push(issue(`tasks/${entry.id}.md is parked (waiting, no wake) and no running background job will wake it.`, `It resumes only when you reply to it, run /tasks run ${entry.id}, or give it a wake with /tasks set ${entry.id} wake <local time or +2h>; cancel it if what it waits for is gone.`));
588
592
  }
@@ -1,13 +1,13 @@
1
1
  import type { PipiclawTaskDriverSettings } from "../settings.js";
2
2
  import { type TaskLedgerEntry } from "../tasks/ledger.js";
3
- import type { DingTalkEvent } from "./dingtalk.js";
3
+ import type { ChannelEvent } from "./channel-event.js";
4
4
  export interface TaskDriverOptions {
5
5
  workspaceDir: string;
6
6
  getKnownChannelIds?: () => Iterable<string>;
7
7
  isChannelActive: (channelId: string) => boolean;
8
- dispatch: (event: DingTalkEvent) => boolean | Promise<boolean>;
8
+ dispatch: (event: ChannelEvent) => boolean | Promise<boolean>;
9
9
  /** Optional observability hook. It runs after every production dispatch attempt. */
10
- onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
10
+ onDispatch?: (event: ChannelEvent, accepted: boolean) => void;
11
11
  getSettings: () => PipiclawTaskDriverSettings;
12
12
  /**
13
13
  * Externally visible effects produced by this task's own turns so far (spec 031, D7).
@@ -19,13 +19,13 @@ export interface TaskDriverOptions {
19
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
20
20
  intervalMs?: number;
21
21
  /** Direct, non-LLM receipt for deterministic governor stops. */
22
- notify?: (event: DingTalkEvent) => boolean | Promise<boolean>;
22
+ notify?: (event: ChannelEvent) => boolean | Promise<boolean>;
23
23
  }
24
24
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
25
- export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): DingTalkEvent;
25
+ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): ChannelEvent;
26
26
  /** Durable checker wake created by request-verification; it is a normal main-agent turn. */
27
- export declare function createTaskVerificationEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
28
- export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): DingTalkEvent;
27
+ export declare function createTaskVerificationEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): ChannelEvent;
28
+ export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
29
29
  /**
30
30
  * Native, token-gated driver for the persistent task ledger.
31
31
  *
@@ -3,11 +3,11 @@ import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { PLAYBOOKS_DIR } from "../paths.js";
5
5
  import { parseLocalTime } from "../shared/local-time.js";
6
- import { nextTaskWake } from "../shared/task-schedule.js";
7
6
  import { errorMessage } from "../shared/text-utils.js";
8
7
  import { taskBudgetViolation } from "../tasks/control.js";
9
8
  import { normalizeTaskFields, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
10
9
  import { activateWaitingTask, claimTaskAttempt, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
10
+ import { nextTaskWake } from "../tasks/task-schedule.js";
11
11
  import { discoverWorkspaceChannelIds } from "./channel-index.js";
12
12
  import { isChannelId } from "./channel-paths.js";
13
13
  /** Short debounce so a burst of nudges collapses into a single rescan. */
@@ -146,7 +146,6 @@ export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration
146
146
  "For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_manage skip with the reason, then respond with exactly [SILENT]. " +
147
147
  "If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
148
148
  ts: String(nowMs),
149
- conversationId: "",
150
149
  conversationType: channelId.startsWith("group_") ? "2" : "1",
151
150
  dispatchId: taskDispatchId(channelId, entry, nowMs),
152
151
  taskAttemptGeneration: attemptGeneration,
@@ -165,7 +164,6 @@ export function createTaskVerificationEvent(channelId, entry, nowMs) {
165
164
  `subagent with purpose=verify. Import its attestation with task_manage verify using the returned run id. ` +
166
165
  `Do not modify the workspace or task contract; if verification fails, record the failure and leave the task recoverable.`,
167
166
  ts: String(nowMs),
168
- conversationId: "",
169
167
  conversationType: channelId.startsWith("group_") ? "2" : "1",
170
168
  dispatchId: `task:${channelId}:${entry.id}:verification:${control?.cycleId ?? `t${nowMs}`}`,
171
169
  };
@@ -192,7 +190,6 @@ export function taskGovernorReceipt(channelId, entry, reason, nowMs) {
192
190
  `当前阶段:${entry.frontmatter.status ?? "active"}${entry.frontmatter.control?.cycleId ? `;周期:${entry.frontmatter.control.cycleId}` : ""}\n` +
193
191
  `继续:/tasks resume ${entry.id}\n立即执行:/tasks run ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
194
192
  ts: String(nowMs),
195
- conversationId: "",
196
193
  conversationType: channelId.startsWith("group_") ? "2" : "1",
197
194
  // Keyed on the cause, not the moment: re-detecting the same violation before the user has
198
195
  // acted must not queue a second identical escalation, while a different cause still does.
@@ -2,12 +2,12 @@ import { mkdir, readdir, readFile, rename, stat, unlink } from "node:fs/promises
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { formatLocalTime } from "../shared/local-time.js";
5
- import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
6
5
  import { errorMessage } from "../shared/text-utils.js";
7
6
  import { createDefaultTaskControl } from "../tasks/control.js";
8
7
  import { appendCurrentCycleNote, parseTaskFrontmatter } from "../tasks/ledger.js";
9
8
  import { withTaskMutation } from "../tasks/mutation-lock.js";
10
9
  import { readStoredTask, updateStoredTask, writeStoredTask } from "../tasks/store.js";
10
+ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
11
11
  import { parseScheduledEventContent } from "./events.js";
12
12
  import { discoverTaskChannels } from "./task-driver.js";
13
13
  /**
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Verifying and claiming a background job's or delegation run's completion wake before it may
3
+ * activate a task parked with `waitingFor` (spec 040, D7/T9). Split out of `bootstrap.ts`: these
4
+ * are pure functions over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
+ * `createRuntimeContext`'s closures.
6
+ */
7
+ import { type JobSnapshot } from "../agent/job-manager.js";
8
+ import type { Executor } from "../executor.js";
9
+ import { type RunRecord } from "../subagents/runs.js";
10
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
11
+ import type { ChannelEvent } from "./channel-event.js";
12
+ /**
13
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
15
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
16
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
17
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
18
+ * untrusted stdout.
19
+ */
20
+ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
21
+ /**
22
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
23
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
24
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
25
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
26
+ */
27
+ export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
28
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
29
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
30
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
31
+ export declare function isTrustedInternalWake(event: ChannelEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is ChannelEvent & {
32
+ dispatchId: string;
33
+ };
34
+ export interface ClaimedDelegationWake {
35
+ taskId: string;
36
+ generation?: number;
37
+ activated: boolean;
38
+ finish(): Promise<void>;
39
+ rollback(): Promise<void>;
40
+ }
41
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
42
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
43
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
44
+ export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
45
+ export interface ClaimedJobWake {
46
+ taskId: string;
47
+ generation?: number;
48
+ activated: boolean;
49
+ finish(): Promise<void>;
50
+ }
51
+ /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
52
+ * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
53
+ * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
54
+ export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;