@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +9 -0
- package/dist/agent/channel-runner.js +58 -4
- package/dist/agent/commands.js +11 -3
- package/dist/agent/job-manager.d.ts +6 -0
- package/dist/agent/job-manager.js +55 -1
- package/dist/agent/progress-formatter.js +3 -3
- package/dist/agent/run-queue.d.ts +10 -1
- package/dist/agent/run-queue.js +19 -2
- package/dist/agent/session-resource-gate.d.ts +17 -0
- package/dist/agent/session-resource-gate.js +33 -2
- package/dist/agent/status-render.js +1 -3
- package/dist/agent/types.d.ts +8 -0
- package/dist/runtime/bootstrap.d.ts +52 -0
- package/dist/runtime/bootstrap.js +192 -25
- package/dist/runtime/delivery.js +5 -5
- package/dist/runtime/dingtalk.d.ts +8 -0
- package/dist/runtime/durable-dispatch.d.ts +4 -0
- package/dist/runtime/durable-dispatch.js +16 -0
- package/dist/runtime/subagent-commands.d.ts +8 -6
- package/dist/runtime/subagent-commands.js +264 -64
- package/dist/security/logger.js +7 -0
- package/dist/shared/host-process.d.ts +7 -1
- package/dist/shared/host-process.js +7 -3
- package/dist/shared/jsonl-appender.d.ts +2 -0
- package/dist/shared/jsonl-appender.js +25 -13
- package/dist/shared/with-timeout.d.ts +14 -0
- package/dist/shared/with-timeout.js +38 -0
- package/dist/subagents/detached-discovery.d.ts +13 -0
- package/dist/subagents/detached-discovery.js +17 -0
- package/dist/subagents/external/run.d.ts +10 -0
- package/dist/subagents/external/run.js +47 -1
- package/dist/subagents/format.d.ts +12 -0
- package/dist/subagents/format.js +24 -0
- package/dist/subagents/runs.d.ts +38 -0
- package/dist/subagents/runs.js +171 -24
- package/dist/subagents/tool.d.ts +18 -0
- package/dist/subagents/tool.js +147 -89
- package/dist/tasks/control.d.ts +12 -0
- package/dist/tasks/control.js +20 -0
- package/dist/tasks/store.d.ts +21 -0
- package/dist/tasks/store.js +80 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/subagent-manage.d.ts +5 -0
- package/dist/tools/subagent-manage.js +68 -51
- package/dist/usage/ledger.d.ts +7 -0
- package/dist/usage/ledger.js +15 -2
- package/dist/usage/render.js +22 -0
- package/examples/sub-agents/README.md +12 -7
- package/examples/sub-agents/documenter.md +3 -3
- package/examples/sub-agents/git-committer.md +1 -1
- package/examples/sub-agents/reviewer.md +12 -6
- package/examples/sub-agents/verifier.md +5 -2
- package/examples/sub-agents/worker.md +1 -1
- package/package.json +1 -1
|
@@ -1,102 +1,298 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
import { elapsedMs, formatCost, formatDuration, harnessLabel } from "../subagents/format.js";
|
|
4
5
|
import { getSubAgentRunManager } from "../subagents/runs.js";
|
|
5
6
|
function usage() {
|
|
6
|
-
return `#
|
|
7
|
+
return `# 委派 Run
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
用法:
|
|
9
10
|
|
|
10
|
-
- \`/subagents
|
|
11
|
-
- \`/subagents
|
|
12
|
-
- \`/subagents
|
|
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\`。`;
|
|
13
19
|
}
|
|
14
20
|
function parseSubagentsCommand(args) {
|
|
15
21
|
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
16
22
|
const action = parts[0];
|
|
17
23
|
if (!action || action === "list") {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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 };
|
|
21
34
|
}
|
|
22
35
|
if (action === "show") {
|
|
23
36
|
if (!parts[1] || parts.length > 2)
|
|
24
|
-
throw new Error("
|
|
25
|
-
return { action: "show",
|
|
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] };
|
|
26
44
|
}
|
|
27
45
|
if (action === "cancel") {
|
|
28
46
|
if (!parts[1] || parts.length > 2)
|
|
29
|
-
throw new Error("
|
|
30
|
-
return { action: "cancel",
|
|
47
|
+
throw new Error("用法:/subagents cancel <runId|all>");
|
|
48
|
+
return { action: "cancel", ref: parts[1] };
|
|
31
49
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
|
|
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}`);
|
|
39
56
|
}
|
|
40
|
-
function
|
|
41
|
-
|
|
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
|
+
}
|
|
42
70
|
}
|
|
43
71
|
function formatRunLine(record) {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
72
|
+
const bits = [harnessLabel(record), formatDuration(elapsedMs(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;
|
|
47
85
|
}
|
|
48
|
-
function
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (
|
|
52
|
-
|
|
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();
|
|
53
93
|
}
|
|
54
|
-
|
|
55
|
-
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
56
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 查看`;
|
|
57
105
|
for (const warning of discovery.warnings) {
|
|
58
|
-
|
|
106
|
+
line += `\n⚠ discovery: ${warning}`;
|
|
59
107
|
}
|
|
60
|
-
return
|
|
108
|
+
return line;
|
|
61
109
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
110
|
+
const DEFAULT_LIST_COMPLETED_LIMIT = 5;
|
|
111
|
+
async function listRuns(options, filter) {
|
|
112
|
+
const records = getSubAgentRunManager(options.channelId).list();
|
|
113
|
+
if (records.length === 0)
|
|
114
|
+
return "# 委派 Run\n\n没有委派记录。";
|
|
115
|
+
const running = records.filter((record) => record.status === "running").sort((a, b) => b.startedAt - a.startedAt);
|
|
116
|
+
const terminal = records
|
|
117
|
+
.filter((record) => record.status !== "running")
|
|
118
|
+
.sort((a, b) => (b.finishedAt ?? b.startedAt) - (a.finishedAt ?? a.startedAt));
|
|
119
|
+
const sections = [];
|
|
120
|
+
if (filter === "running") {
|
|
121
|
+
sections.push(running.length === 0 ? "没有正在运行的 run。" : running.map(formatRunLine).join("\n"));
|
|
122
|
+
return `# 委派 Run — 运行中\n\n${sections.join("\n")}`;
|
|
123
|
+
}
|
|
124
|
+
if (filter === "failed") {
|
|
125
|
+
const failed = terminal.filter((record) => record.status === "failed");
|
|
126
|
+
sections.push(failed.length === 0 ? "没有失败的 run。" : failed.map(formatRunLine).join("\n"));
|
|
127
|
+
return `# 委派 Run — 失败\n\n${sections.join("\n")}`;
|
|
128
|
+
}
|
|
129
|
+
if (filter === "all") {
|
|
130
|
+
sections.push([...running, ...terminal].map(formatRunLine).join("\n"));
|
|
131
|
+
return `# 委派 Run — 全部(${records.length})\n\n${sections.join("\n")}`;
|
|
132
|
+
}
|
|
133
|
+
// default: an overview — every running run, plus a capped tail of recent completions.
|
|
134
|
+
if (running.length > 0) {
|
|
135
|
+
sections.push(`## 运行中 (${running.length})\n${running.map(formatRunLine).join("\n")}`);
|
|
136
|
+
}
|
|
137
|
+
const shown = terminal.slice(0, DEFAULT_LIST_COMPLETED_LIMIT);
|
|
138
|
+
if (shown.length > 0) {
|
|
139
|
+
const countNote = terminal.length > shown.length ? `显示 ${shown.length} / 共 ${terminal.length}` : `${shown.length}`;
|
|
140
|
+
sections.push(`## 最近完成 (${countNote})\n${shown.map(formatRunLine).join("\n")}`);
|
|
141
|
+
}
|
|
142
|
+
if (sections.length === 0)
|
|
143
|
+
sections.push("没有委派记录。");
|
|
144
|
+
const discovery = await resolveDiscovery(options);
|
|
145
|
+
if (discovery)
|
|
146
|
+
sections.push(formatRolesTail(discovery));
|
|
147
|
+
sections.push("用 `/subagents show <runId>` 看详情,`/subagents output <runId>` 看产出。");
|
|
148
|
+
return `# 委派 Run\n\n${sections.join("\n\n")}`;
|
|
72
149
|
}
|
|
73
150
|
const STDERR_TAIL_CHARS = 2_000;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
151
|
+
const OUTPUT_TAIL_CHARS = 4_000;
|
|
152
|
+
function formatRunResolution(resolution, ref) {
|
|
153
|
+
if (resolution.kind === "not_found")
|
|
154
|
+
return `未找到 run:\`${ref}\``;
|
|
155
|
+
if (resolution.kind === "ambiguous") {
|
|
156
|
+
const candidates = resolution.candidates.map((record) => `\`${record.runId}\` (${record.agent})`).join("、");
|
|
157
|
+
return `"${ref}" 匹配到多个 run:${candidates}。请提供更完整的 runId。`;
|
|
158
|
+
}
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
async function showRun(channelId, ref) {
|
|
162
|
+
const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
|
|
163
|
+
const error = formatRunResolution(resolution, ref);
|
|
164
|
+
if (error || resolution.kind !== "found")
|
|
165
|
+
return error ?? `未找到 run:\`${ref}\``;
|
|
166
|
+
const record = resolution.record;
|
|
167
|
+
const lines = [
|
|
168
|
+
`# Run \`${record.runId}\``,
|
|
169
|
+
"",
|
|
170
|
+
`角色:${record.agent} (${harnessLabel(record)}, ${record.source})`,
|
|
171
|
+
`标签:${record.label}`,
|
|
172
|
+
`状态:${statusLabel(record.status)}(耗时 ${formatDuration(elapsedMs(record))})`,
|
|
173
|
+
];
|
|
174
|
+
if (record.failureReason)
|
|
175
|
+
lines.push(`失败原因:${record.failureReason}`);
|
|
176
|
+
if (record.verificationVerdict) {
|
|
177
|
+
lines.push(`验收结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? "(advisory)" : ""}`);
|
|
178
|
+
}
|
|
179
|
+
lines.push(`开始:${new Date(record.startedAt).toLocaleString()}`);
|
|
180
|
+
if (record.finishedAt)
|
|
181
|
+
lines.push(`结束:${new Date(record.finishedAt).toLocaleString()}`);
|
|
182
|
+
lines.push(`purpose:${record.purpose}`, `工作目录:\`${record.workingDirectory}\``, `产物目录:\`${record.artifactDir}\``);
|
|
183
|
+
if (record.taskId)
|
|
184
|
+
lines.push(`所属任务:${record.taskId}`);
|
|
185
|
+
if (record.leaseKey)
|
|
186
|
+
lines.push("持有写锁:是");
|
|
187
|
+
if (record.model)
|
|
188
|
+
lines.push(`模型:${record.model}`);
|
|
189
|
+
const cost = formatCost(record);
|
|
190
|
+
lines.push(`usage:input=${record.usage.input} output=${record.usage.output}${cost ? ` cost=${cost}` : record.costKnown ? "" : "(cost 未知)"}`);
|
|
191
|
+
if (record.argv)
|
|
192
|
+
lines.push("", "实际 argv:", "```", JSON.stringify(record.argv), "```");
|
|
193
|
+
if (record.sessionId)
|
|
194
|
+
lines.push(`sessionId:\`${record.sessionId}\`(可用于 subagent_manage op=follow_up)`);
|
|
79
195
|
if (record.runtime === "external") {
|
|
80
196
|
const stderrTail = await readFile(join(record.artifactDir, "stderr.log"), "utf-8")
|
|
81
197
|
.then((text) => text.slice(-STDERR_TAIL_CHARS))
|
|
82
198
|
.catch(() => undefined);
|
|
83
199
|
if (stderrTail?.trim()) {
|
|
84
|
-
|
|
200
|
+
lines.push("", "## stderr (tail)", "```", stderrTail, "```");
|
|
85
201
|
}
|
|
86
202
|
}
|
|
87
|
-
return
|
|
203
|
+
return lines.join("\n");
|
|
204
|
+
}
|
|
205
|
+
async function showOutput(channelId, ref) {
|
|
206
|
+
const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
|
|
207
|
+
const error = formatRunResolution(resolution, ref);
|
|
208
|
+
if (error || resolution.kind !== "found")
|
|
209
|
+
return error ?? `未找到 run:\`${ref}\``;
|
|
210
|
+
const record = resolution.record;
|
|
211
|
+
const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => undefined);
|
|
212
|
+
if (!outputText?.trim()) {
|
|
213
|
+
const runningNote = record.status === "running" ? "该 run 仍在运行,可能还没有产出。" : "该 run 没有文本产出。";
|
|
214
|
+
return `# Run \`${record.runId}\` 的产出\n\n${runningNote}产物目录:\`${record.artifactDir}\``;
|
|
215
|
+
}
|
|
216
|
+
const tail = outputText.slice(-OUTPUT_TAIL_CHARS);
|
|
217
|
+
const truncatedNote = outputText.length > tail.length ? `(只显示末尾 ${OUTPUT_TAIL_CHARS} 字符,完整内容见上方产物目录)\n\n` : "";
|
|
218
|
+
return `# Run \`${record.runId}\` 的产出\n\n${truncatedNote}\`\`\`\n${tail}\n\`\`\``;
|
|
88
219
|
}
|
|
89
|
-
async function
|
|
90
|
-
const
|
|
91
|
-
if (
|
|
92
|
-
|
|
93
|
-
|
|
220
|
+
async function cancelRun(channelId, ref) {
|
|
221
|
+
const manager = getSubAgentRunManager(channelId);
|
|
222
|
+
if (ref === "all") {
|
|
223
|
+
const running = manager.list().filter((record) => record.status === "running");
|
|
224
|
+
if (running.length === 0)
|
|
225
|
+
return "没有正在运行的 run。";
|
|
226
|
+
const results = await Promise.all(running.map(async (record) => {
|
|
227
|
+
const status = await manager.cancel(record.runId);
|
|
228
|
+
return `- \`${record.runId}\` (${record.agent}):${status}`;
|
|
229
|
+
}));
|
|
230
|
+
return `# 已请求终止 ${running.length} 个 run\n\n${results.join("\n")}`;
|
|
231
|
+
}
|
|
232
|
+
const resolution = manager.resolveRef(ref);
|
|
233
|
+
const error = formatRunResolution(resolution, ref);
|
|
234
|
+
if (error || resolution.kind !== "found")
|
|
235
|
+
return error ?? `未找到 run:\`${ref}\``;
|
|
236
|
+
const status = await manager.cancel(resolution.record.runId);
|
|
237
|
+
return `已请求终止 run \`${resolution.record.runId}\`:${status}`;
|
|
94
238
|
}
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return
|
|
239
|
+
function formatRoleSummaryLine(agent) {
|
|
240
|
+
const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
|
|
241
|
+
const mutates = agent.mutates ?? (agent.tools.includes("write") || agent.tools.includes("edit") ? "write" : "read");
|
|
242
|
+
const unavailable = agent.unavailable ? ` — ⚠ 不可用:${agent.unavailable}` : "";
|
|
243
|
+
return `- \`${agent.name}\` (${kind}, ${mutates}) — ${agent.description}${unavailable}`;
|
|
244
|
+
}
|
|
245
|
+
function formatRoleDetail(agent) {
|
|
246
|
+
const kind = agent.runtime === "external" ? `外部/${agent.harness}` : "内置";
|
|
247
|
+
const lines = [
|
|
248
|
+
`# 角色 \`${agent.name}\``,
|
|
249
|
+
"",
|
|
250
|
+
`runtime:${kind}`,
|
|
251
|
+
`来源:${agent.source} (${agent.filePath ?? "inline"})`,
|
|
252
|
+
`说明:${agent.description}`,
|
|
253
|
+
];
|
|
254
|
+
if (agent.unavailable)
|
|
255
|
+
lines.push(`⚠ 不可用:${agent.unavailable}`);
|
|
256
|
+
lines.push(`mutates:${agent.mutates ?? "(未声明,由 tools 推断)"}`);
|
|
257
|
+
if (agent.runtime === "internal") {
|
|
258
|
+
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}`);
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
lines.push(`command:\`${agent.command ?? ""}\`${agent.shell ? "(通过 shell 执行)" : ""}`, `maxWallTimeSec:${agent.maxWallTimeSec}`);
|
|
262
|
+
if (agent.externalModelRef)
|
|
263
|
+
lines.push(`模型:${agent.externalModelRef}`);
|
|
264
|
+
}
|
|
265
|
+
if (agent.paths.length > 0)
|
|
266
|
+
lines.push(`paths:${agent.paths.join(", ")}`);
|
|
267
|
+
lines.push("", "system prompt:", "```", agent.systemPrompt, "```");
|
|
268
|
+
return lines.join("\n");
|
|
269
|
+
}
|
|
270
|
+
async function showRoles(options, name) {
|
|
271
|
+
const discovery = await resolveDiscovery(options);
|
|
272
|
+
if (!discovery) {
|
|
273
|
+
return "角色目录不可用:本频道尚未激活过运行时,且无法在离线状态下解析模型引用。先给这个频道发一条消息,再重试。";
|
|
274
|
+
}
|
|
275
|
+
if (name) {
|
|
276
|
+
const agent = discovery.agents.find((candidate) => candidate.name === name);
|
|
277
|
+
if (!agent) {
|
|
278
|
+
const available = discovery.agents.length > 0 ? discovery.agents.map((a) => a.name).join(", ") : "(none)";
|
|
279
|
+
return `未找到角色 "${name}"。可用角色:${available}`;
|
|
280
|
+
}
|
|
281
|
+
return formatRoleDetail(agent);
|
|
282
|
+
}
|
|
283
|
+
const internal = discovery.agents.filter((agent) => agent.runtime === "internal");
|
|
284
|
+
const external = discovery.agents.filter((agent) => agent.runtime === "external");
|
|
285
|
+
const sections = [`# 角色目录\n\n目录:\`${discovery.directory}\``];
|
|
286
|
+
if (external.length > 0)
|
|
287
|
+
sections.push(`## 外部\n${external.map(formatRoleSummaryLine).join("\n")}`);
|
|
288
|
+
if (internal.length > 0)
|
|
289
|
+
sections.push(`## 内置\n${internal.map(formatRoleSummaryLine).join("\n")}`);
|
|
290
|
+
if (discovery.agents.length === 0)
|
|
291
|
+
sections.push("目录为空。");
|
|
292
|
+
for (const warning of discovery.warnings)
|
|
293
|
+
sections.push(`⚠ discovery: ${warning}`);
|
|
294
|
+
sections.push("用 `/subagents roles <name>` 看单个角色的详情。");
|
|
295
|
+
return sections.join("\n\n");
|
|
100
296
|
}
|
|
101
297
|
export async function handleSubagentsCommand(options) {
|
|
102
298
|
let command;
|
|
@@ -109,14 +305,18 @@ export async function handleSubagentsCommand(options) {
|
|
|
109
305
|
try {
|
|
110
306
|
switch (command.action) {
|
|
111
307
|
case "list":
|
|
112
|
-
return await listRuns(options
|
|
308
|
+
return await listRuns(options, command.filter);
|
|
113
309
|
case "show":
|
|
114
|
-
return await showRun(options.channelId, command.
|
|
310
|
+
return await showRun(options.channelId, command.ref);
|
|
311
|
+
case "output":
|
|
312
|
+
return await showOutput(options.channelId, command.ref);
|
|
115
313
|
case "cancel":
|
|
116
|
-
return await cancelRun(options.channelId, command.
|
|
314
|
+
return await cancelRun(options.channelId, command.ref);
|
|
315
|
+
case "roles":
|
|
316
|
+
return await showRoles(options, command.name);
|
|
117
317
|
}
|
|
118
318
|
}
|
|
119
319
|
catch (error) {
|
|
120
|
-
return
|
|
320
|
+
return `执行 /subagents ${command.action} 失败:${errorMessage(error)}`;
|
|
121
321
|
}
|
|
122
322
|
}
|
package/dist/security/logger.js
CHANGED
|
@@ -24,6 +24,13 @@ export async function logSecurityEvent(workspaceDir, config, event) {
|
|
|
24
24
|
// disappear just because the operator only wants blocked-action logging.
|
|
25
25
|
if (!config.audit.logBlocked && event.type !== "external-agent")
|
|
26
26
|
return;
|
|
27
|
+
if (event.type === "external-agent") {
|
|
28
|
+
// External agents bypass command-guard. Their complete dispatch record is therefore a
|
|
29
|
+
// security gate, not best-effort observability: do not return until it is on disk, and let
|
|
30
|
+
// capacity/permission/I/O failures reject the dispatch before a child can be spawned.
|
|
31
|
+
await getAppender(getLogPath(workspaceDir, config)).appendStrict({ date: formatLocalTime(), ...event });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
27
34
|
let timer;
|
|
28
35
|
try {
|
|
29
36
|
await Promise.race([
|
|
@@ -8,8 +8,14 @@
|
|
|
8
8
|
/** True if `pid` names a live process this user can at least see, without sending a real signal. */
|
|
9
9
|
export declare function isProcessAlive(pid: number): boolean;
|
|
10
10
|
/**
|
|
11
|
-
* SIGTERM the process group, then SIGKILL it after a short grace period
|
|
11
|
+
* SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
|
|
12
12
|
* `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
|
|
13
13
|
* it and everything it spawned.
|
|
14
|
+
*
|
|
15
|
+
* The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
|
|
16
|
+
* lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
|
|
17
|
+
* report false while the descendant is still alive and still holding the workspace, so probing
|
|
18
|
+
* only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
|
|
19
|
+
* A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
|
|
14
20
|
*/
|
|
15
21
|
export declare function killProcessGroup(pid: number, graceMs?: number): Promise<void>;
|
|
@@ -17,9 +17,15 @@ export function isProcessAlive(pid) {
|
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
/**
|
|
20
|
-
* SIGTERM the process group, then SIGKILL it after a short grace period
|
|
20
|
+
* SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
|
|
21
21
|
* `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
|
|
22
22
|
* it and everything it spawned.
|
|
23
|
+
*
|
|
24
|
+
* The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
|
|
25
|
+
* lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
|
|
26
|
+
* report false while the descendant is still alive and still holding the workspace, so probing
|
|
27
|
+
* only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
|
|
28
|
+
* A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
|
|
23
29
|
*/
|
|
24
30
|
export async function killProcessGroup(pid, graceMs = 300) {
|
|
25
31
|
try {
|
|
@@ -28,8 +34,6 @@ export async function killProcessGroup(pid, graceMs = 300) {
|
|
|
28
34
|
catch {
|
|
29
35
|
return; // Already gone.
|
|
30
36
|
}
|
|
31
|
-
if (!isProcessAlive(pid))
|
|
32
|
-
return;
|
|
33
37
|
await new Promise((resolve) => setTimeout(resolve, graceMs));
|
|
34
38
|
try {
|
|
35
39
|
process.kill(-pid, "SIGKILL");
|
|
@@ -26,6 +26,8 @@ export interface JsonlAppenderOptions {
|
|
|
26
26
|
export interface JsonlAppender {
|
|
27
27
|
/** Queue and await one record. Never throws; a full or closed writer drops it. */
|
|
28
28
|
append(record: unknown, priority?: JsonlPriority): Promise<void>;
|
|
29
|
+
/** Queue and durably append one record, rejecting on serialization, capacity, closure, or I/O failure. */
|
|
30
|
+
appendStrict(record: unknown, priority?: JsonlPriority): Promise<void>;
|
|
29
31
|
/** Queue one record without waiting for disk. Returns false when it cannot be accepted. */
|
|
30
32
|
tryAppend(record: unknown, priority?: JsonlPriority): boolean;
|
|
31
33
|
/** Wait until every currently accepted record has finished. */
|
|
@@ -93,7 +93,7 @@ export function createJsonlAppender(options) {
|
|
|
93
93
|
await appendFile(filePath, line, { encoding: "utf-8", mode });
|
|
94
94
|
sizes.set(filePath, (await currentSize(filePath)) + lineBytes);
|
|
95
95
|
};
|
|
96
|
-
const serialize = (record) => {
|
|
96
|
+
const serialize = (record, strict) => {
|
|
97
97
|
try {
|
|
98
98
|
const json = JSON.stringify(options.recordForWrite ? options.recordForWrite(record) : record);
|
|
99
99
|
if (json === undefined)
|
|
@@ -101,7 +101,9 @@ export function createJsonlAppender(options) {
|
|
|
101
101
|
const line = `${json}\n`;
|
|
102
102
|
return { filePath: resolvePath(new Date(), record), line, bytes: Buffer.byteLength(line) };
|
|
103
103
|
}
|
|
104
|
-
catch {
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (strict)
|
|
106
|
+
throw error;
|
|
105
107
|
if (!warnedDrop) {
|
|
106
108
|
warnedDrop = true;
|
|
107
109
|
fallbackWarning("runtime.log_sink.dropped", "Failed to serialize JSONL record; record was dropped");
|
|
@@ -109,15 +111,20 @@ export function createJsonlAppender(options) {
|
|
|
109
111
|
return null;
|
|
110
112
|
}
|
|
111
113
|
};
|
|
112
|
-
const enqueue = (record, priority) => {
|
|
113
|
-
if (closed)
|
|
114
|
+
const enqueue = (record, priority, strict = false) => {
|
|
115
|
+
if (closed) {
|
|
116
|
+
if (strict)
|
|
117
|
+
throw new Error("JSONL appender is closed");
|
|
114
118
|
return null;
|
|
115
|
-
|
|
119
|
+
}
|
|
120
|
+
const serialized = serialize(record, strict);
|
|
116
121
|
if (!serialized)
|
|
117
122
|
return null;
|
|
118
123
|
const recordLimit = priority === "critical" ? maxPendingRecords : maxPendingRecords - reservedCriticalRecords;
|
|
119
124
|
const byteLimit = priority === "critical" ? maxPendingBytes : maxPendingBytes - reservedCriticalBytes;
|
|
120
125
|
if (pending.size >= recordLimit || pendingBytes + serialized.bytes > byteLimit) {
|
|
126
|
+
if (strict)
|
|
127
|
+
throw new Error("JSONL queue limit reached");
|
|
121
128
|
if (!warnedDrop) {
|
|
122
129
|
warnedDrop = true;
|
|
123
130
|
fallbackWarning("runtime.log_sink.dropped", "JSONL queue limit reached; record was dropped");
|
|
@@ -125,20 +132,19 @@ export function createJsonlAppender(options) {
|
|
|
125
132
|
return null;
|
|
126
133
|
}
|
|
127
134
|
const previous = chains.get(serialized.filePath) ?? Promise.resolve();
|
|
128
|
-
const
|
|
135
|
+
const writeResult = previous
|
|
129
136
|
.catch(() => undefined)
|
|
130
|
-
.then(
|
|
131
|
-
|
|
132
|
-
|
|
137
|
+
.then(() => write(serialized.filePath, serialized.line, serialized.bytes));
|
|
138
|
+
const result = strict
|
|
139
|
+
? writeResult
|
|
140
|
+
: writeResult.then(() => {
|
|
133
141
|
warnedWrite = false;
|
|
134
|
-
}
|
|
135
|
-
catch {
|
|
142
|
+
}, () => {
|
|
136
143
|
if (!warnedWrite) {
|
|
137
144
|
warnedWrite = true;
|
|
138
145
|
fallbackWarning("runtime.log_sink.failed", "Failed to append JSONL record; continuing without it");
|
|
139
146
|
}
|
|
140
|
-
}
|
|
141
|
-
});
|
|
147
|
+
});
|
|
142
148
|
const completion = result.finally(() => {
|
|
143
149
|
pending.delete(completion);
|
|
144
150
|
pendingBytes -= serialized.bytes;
|
|
@@ -161,6 +167,12 @@ export function createJsonlAppender(options) {
|
|
|
161
167
|
async append(record, priority = "critical") {
|
|
162
168
|
await enqueue(record, priority)?.completion;
|
|
163
169
|
},
|
|
170
|
+
async appendStrict(record, priority = "critical") {
|
|
171
|
+
const pendingLine = enqueue(record, priority, true);
|
|
172
|
+
if (!pendingLine)
|
|
173
|
+
throw new Error("JSONL record was not accepted");
|
|
174
|
+
await pendingLine.completion;
|
|
175
|
+
},
|
|
164
176
|
tryAppend(record, priority = "normal") {
|
|
165
177
|
return enqueue(record, priority) !== null;
|
|
166
178
|
},
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bound an await that has no timeout of its own.
|
|
3
|
+
*
|
|
4
|
+
* The promise is *not* cancelled — nothing here can cancel an in-flight fetch or
|
|
5
|
+
* an SDK call — the caller is merely released so a stalled dependency cannot hold
|
|
6
|
+
* a turn (and with it the channel's busy state) open indefinitely. Callers decide
|
|
7
|
+
* what "released" means: most log a warning and continue with the previous state.
|
|
8
|
+
*/
|
|
9
|
+
export declare class OperationTimeoutError extends Error {
|
|
10
|
+
readonly operation: string;
|
|
11
|
+
readonly timeoutMs: number;
|
|
12
|
+
constructor(operation: string, timeoutMs: number);
|
|
13
|
+
}
|
|
14
|
+
export declare function withTimeout<T>(operation: string, timeoutMs: number, run: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bound an await that has no timeout of its own.
|
|
3
|
+
*
|
|
4
|
+
* The promise is *not* cancelled — nothing here can cancel an in-flight fetch or
|
|
5
|
+
* an SDK call — the caller is merely released so a stalled dependency cannot hold
|
|
6
|
+
* a turn (and with it the channel's busy state) open indefinitely. Callers decide
|
|
7
|
+
* what "released" means: most log a warning and continue with the previous state.
|
|
8
|
+
*/
|
|
9
|
+
export class OperationTimeoutError extends Error {
|
|
10
|
+
constructor(operation, timeoutMs) {
|
|
11
|
+
super(`${operation} timed out after ${timeoutMs}ms`);
|
|
12
|
+
this.name = "OperationTimeoutError";
|
|
13
|
+
this.operation = operation;
|
|
14
|
+
this.timeoutMs = timeoutMs;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function withTimeout(operation, timeoutMs, run) {
|
|
18
|
+
if (!(timeoutMs > 0)) {
|
|
19
|
+
return run();
|
|
20
|
+
}
|
|
21
|
+
let timer;
|
|
22
|
+
const guard = new Promise((_, reject) => {
|
|
23
|
+
timer = setTimeout(() => reject(new OperationTimeoutError(operation, timeoutMs)), timeoutMs);
|
|
24
|
+
// A pending guard must never keep the process alive on its own.
|
|
25
|
+
timer.unref?.();
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
// The abandoned promise keeps running; a rejection after the race is
|
|
29
|
+
// swallowed here so it never surfaces as an unhandled rejection.
|
|
30
|
+
const pending = run();
|
|
31
|
+
pending.catch(() => undefined);
|
|
32
|
+
return await Promise.race([pending, guard]);
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
if (timer)
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SubAgentDiscoveryResult } from "./discovery.js";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the role directory for `/subagents roles` when no `ChannelRunner` is currently active
|
|
4
|
+
* for the channel (spec 041) — mirrors `loadDetachedMaintenanceContext` in
|
|
5
|
+
* `agent/maintenance-context.ts`: deliberately much lighter than a full runner (no Agent, no
|
|
6
|
+
* AgentSession, no tool set), just enough to resolve model references in role frontmatter so
|
|
7
|
+
* `unavailable` reasons are accurate instead of guessed from an empty model list.
|
|
8
|
+
*/
|
|
9
|
+
export declare function loadDetachedSubAgentDiscovery(options: {
|
|
10
|
+
workspaceDir: string;
|
|
11
|
+
authConfigPath: string;
|
|
12
|
+
modelsConfigPath: string;
|
|
13
|
+
}): Promise<SubAgentDiscoveryResult>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createModelRuntime, wrapModelRegistry } from "../models/utils.js";
|
|
2
|
+
import { discoverSubAgents } from "./discovery.js";
|
|
3
|
+
/**
|
|
4
|
+
* Resolve the role directory for `/subagents roles` when no `ChannelRunner` is currently active
|
|
5
|
+
* for the channel (spec 041) — mirrors `loadDetachedMaintenanceContext` in
|
|
6
|
+
* `agent/maintenance-context.ts`: deliberately much lighter than a full runner (no Agent, no
|
|
7
|
+
* AgentSession, no tool set), just enough to resolve model references in role frontmatter so
|
|
8
|
+
* `unavailable` reasons are accurate instead of guessed from an empty model list.
|
|
9
|
+
*/
|
|
10
|
+
export async function loadDetachedSubAgentDiscovery(options) {
|
|
11
|
+
const modelRuntime = await createModelRuntime({
|
|
12
|
+
authConfigPath: options.authConfigPath,
|
|
13
|
+
modelsConfigPath: options.modelsConfigPath,
|
|
14
|
+
});
|
|
15
|
+
const modelRegistry = wrapModelRegistry(modelRuntime);
|
|
16
|
+
return discoverSubAgents(options.workspaceDir, modelRegistry.getAvailable());
|
|
17
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
|
+
import type { SecurityConfig } from "../../security/types.js";
|
|
2
3
|
import type { SubAgentThinkingLevel } from "../discovery.js";
|
|
4
|
+
import { type RunMutates } from "../runs.js";
|
|
3
5
|
/**
|
|
4
6
|
* The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
|
|
5
7
|
* detached process. The launch order matters (D1): admission and the lease are the caller's job
|
|
@@ -31,6 +33,14 @@ export interface LaunchExternalRunInput {
|
|
|
31
33
|
taskId?: string;
|
|
32
34
|
leaseKey?: string;
|
|
33
35
|
resumeSessionId?: string;
|
|
36
|
+
/** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
|
|
37
|
+
mutates?: RunMutates;
|
|
38
|
+
/** Where the audit trail lives (`<workspaceDir>/.pipiclaw/security.log` by default) and whether
|
|
39
|
+
* it is enabled — every external dispatch writes an `external-agent` audit event (D8.1), since
|
|
40
|
+
* external processes never pass through command-guard and this is the only record of what
|
|
41
|
+
* actually ran. */
|
|
42
|
+
workspaceDir: string;
|
|
43
|
+
securityConfig: SecurityConfig;
|
|
34
44
|
/** Test seam: inject a fake `child_process.spawn`. */
|
|
35
45
|
spawnFn?: typeof nodeSpawn;
|
|
36
46
|
}
|