@oyasmi/pipiclaw 0.9.0-beta.2 → 0.9.0-beta.4

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.
@@ -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 `# Subagents
7
+ return `# 委派 Run
7
8
 
8
- Usage:
9
+ 用法:
9
10
 
10
- - \`/subagents list\`
11
- - \`/subagents show <runId>\`
12
- - \`/subagents cancel <runId>\``;
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
- if (parts.length > 1)
19
- throw new Error("Usage: /subagents list");
20
- return { 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 };
21
34
  }
22
35
  if (action === "show") {
23
36
  if (!parts[1] || parts.length > 2)
24
- throw new Error("Usage: /subagents show <runId>");
25
- return { action: "show", runId: parts[1] };
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("Usage: /subagents cancel <runId>");
30
- return { action: "cancel", runId: parts[1] };
47
+ throw new Error("用法:/subagents cancel <runId|all>");
48
+ return { action: "cancel", ref: parts[1] };
31
49
  }
32
- throw new Error(`Unknown /subagents action: ${action}`);
33
- }
34
- function formatDuration(ms) {
35
- const seconds = Math.round(ms / 1000);
36
- if (seconds < 60)
37
- return `${seconds}s`;
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 elapsedMs(record) {
41
- return (record.finishedAt ?? Date.now()) - record.startedAt;
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 harness = record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
45
- const task = record.taskId ? `, task ${record.taskId}` : "";
46
- return `- [${record.runId}] ${record.agent} (${harness}) — ${record.status} (${formatDuration(elapsedMs(record))}${task})`;
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 formatHealthTail(discovery) {
49
- const unavailable = discovery.agents.filter((agent) => agent.unavailable);
50
- const lines = [];
51
- if (unavailable.length > 0 || discovery.warnings.length > 0) {
52
- lines.push("", "## Role directory health");
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
- for (const agent of unavailable) {
55
- lines.push(`- \`${agent.name}\`: unavailable (${agent.unavailable})`);
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
- lines.push(`- discovery warning: ${warning}`);
106
+ line += `\n⚠ discovery: ${warning}`;
59
107
  }
60
- return lines.join("\n");
108
+ return line;
61
109
  }
62
- async function listRuns(channelId, discovery) {
63
- const records = getSubAgentRunManager(channelId).list();
64
- const body = records.length === 0
65
- ? "No delegation runs."
66
- : records
67
- .sort((a, b) => b.startedAt - a.startedAt)
68
- .map(formatRunLine)
69
- .join("\n");
70
- const tail = discovery ? formatHealthTail(discovery) : "";
71
- return `# Subagent runs\n\n${body}${tail}`;
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
- async function formatRunDetail(record) {
75
- const parts = [`# Run ${record.runId}`, "", "```json", JSON.stringify(record, null, 2), "```"];
76
- // D6: "show" is the human/model escape hatch for a stuck or failed external run, so its
77
- // stderr belongs here even though it never rides the completion wake (that only carries
78
- // the harness's own parsed output).
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
- parts.push("", "## stderr (tail)", "```", stderrTail, "```");
200
+ lines.push("", "## stderr (tail)", "```", stderrTail, "```");
85
201
  }
86
202
  }
87
- return parts.join("\n");
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 showRun(channelId, runId) {
90
- const record = getSubAgentRunManager(channelId).get(runId);
91
- if (!record)
92
- return `Run not found: ${runId}`;
93
- return formatRunDetail(record);
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
- async function cancelRun(channelId, runId) {
96
- const status = await getSubAgentRunManager(channelId).cancel(runId);
97
- if (status === "not_found")
98
- return `Run not found: ${runId}`;
99
- return `Cancel requested for run \`${runId}\`: ${status}`;
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.channelId, options.discovery);
308
+ return await listRuns(options, command.filter);
113
309
  case "show":
114
- return await showRun(options.channelId, command.runId);
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.runId);
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 `Could not ${command.action} subagent run(s): ${errorMessage(error)}`;
320
+ return `执行 /subagents ${command.action} 失败:${errorMessage(error)}`;
121
321
  }
122
322
  }
@@ -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
+ }
@@ -0,0 +1,12 @@
1
+ import type { RunRecord } from "./runs.js";
2
+ /**
3
+ * Shared display primitives for delegation runs (spec 041), used by both the model-facing
4
+ * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
5
+ * are genuinely language/audience-neutral live here — duration math, the harness label, and the
6
+ * cost guard — not full line templates, since the two surfaces render in different languages.
7
+ */
8
+ export declare function formatDuration(ms: number): string;
9
+ export declare function elapsedMs(record: RunRecord, now?: number): number;
10
+ export declare function harnessLabel(record: RunRecord): string;
11
+ /** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
12
+ export declare function formatCost(record: RunRecord): string | undefined;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Shared display primitives for delegation runs (spec 041), used by both the model-facing
3
+ * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
4
+ * are genuinely language/audience-neutral live here — duration math, the harness label, and the
5
+ * cost guard — not full line templates, since the two surfaces render in different languages.
6
+ */
7
+ export function formatDuration(ms) {
8
+ const seconds = Math.round(ms / 1000);
9
+ if (seconds < 60)
10
+ return `${seconds}s`;
11
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
12
+ }
13
+ export function elapsedMs(record, now = Date.now()) {
14
+ return (record.finishedAt ?? now) - record.startedAt;
15
+ }
16
+ export function harnessLabel(record) {
17
+ return record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
18
+ }
19
+ /** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
20
+ export function formatCost(record) {
21
+ if (!record.costKnown)
22
+ return undefined;
23
+ return `$${record.usage.cost.total.toFixed(2)}`;
24
+ }
@@ -29,6 +29,23 @@ export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
29
29
  /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
30
30
  * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
31
31
  export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
32
+ /**
33
+ * Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
34
+ * own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
35
+ * chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
36
+ * `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
37
+ * because those are the characters people misread on a phone screen or misspeak out loud.
38
+ */
39
+ export declare const RUN_ID_PREFIX = "run_";
40
+ export type RunResolution = {
41
+ kind: "found";
42
+ record: RunRecord;
43
+ } | {
44
+ kind: "ambiguous";
45
+ candidates: RunRecord[];
46
+ } | {
47
+ kind: "not_found";
48
+ };
32
49
  export interface RunUsage {
33
50
  usage: UsageTotals;
34
51
  /** False only for harnesses that cannot report tokens at all (`exec`). */
@@ -151,6 +168,13 @@ export declare class SubAgentRunManager {
151
168
  /** Task ids a still-running delegation on this channel will eventually wake. Feeds `/tasks doctor`. */
152
169
  runningTaskIds(): Set<string>;
153
170
  runningCount(): number;
171
+ /** Mint a short, human-typeable run id (spec 041). Retried against currently known records;
172
+ * the id space (30^6 ≈ 7.3e8) makes a real collision astronomically unlikely, so this is a
173
+ * defensive check, not a real bottleneck. */
174
+ mintRunId(): string;
175
+ /** Resolve a user- or model-supplied id, exact or by unambiguous prefix (spec 041): `show
176
+ * a1b2c3` and `show run_a1b2c3` both work without retyping the full id. */
177
+ resolveRef(query: string): RunResolution;
154
178
  /** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
155
179
  register(input: RegisterRunInput): Promise<RunRecord>;
156
180
  /** Atomically crosses the external launch cancel window. The supplied live-handle callback is
@@ -20,6 +20,29 @@ export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
20
20
  /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
21
21
  * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
22
22
  export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
23
+ /**
24
+ * Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
25
+ * own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
26
+ * chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
27
+ * `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
28
+ * because those are the characters people misread on a phone screen or misspeak out loud.
29
+ */
30
+ export const RUN_ID_PREFIX = "run_";
31
+ const RUN_ID_ALPHABET = "23456789abcdefghjkmnpqrstvwxyz";
32
+ const RUN_ID_SUFFIX_LEN = 6;
33
+ function randomRunIdSuffix() {
34
+ let suffix = "";
35
+ for (let i = 0; i < RUN_ID_SUFFIX_LEN; i++) {
36
+ suffix += RUN_ID_ALPHABET[Math.floor(Math.random() * RUN_ID_ALPHABET.length)];
37
+ }
38
+ return suffix;
39
+ }
40
+ /** Strips a leading `run_` (case-insensitive) so `show a1b2c3` and `show run_a1b2c3` resolve
41
+ * the same way — nobody should have to remember whether the prefix is required. */
42
+ function normalizeRunIdQuery(query) {
43
+ const lower = query.trim().toLowerCase();
44
+ return lower.startsWith(RUN_ID_PREFIX) ? lower.slice(RUN_ID_PREFIX.length) : lower;
45
+ }
23
46
  /** Registration is serialized across channel managers so the host-wide count and insertion are
24
47
  * one admission transaction. The per-run manager queue alone cannot protect the 19 -> 20 edge
25
48
  * when two different channels register concurrently. */
@@ -132,6 +155,34 @@ export class SubAgentRunManager {
132
155
  runningCount() {
133
156
  return Array.from(this.runs.values()).filter((record) => record.status === "running").length;
134
157
  }
158
+ /** Mint a short, human-typeable run id (spec 041). Retried against currently known records;
159
+ * the id space (30^6 ≈ 7.3e8) makes a real collision astronomically unlikely, so this is a
160
+ * defensive check, not a real bottleneck. */
161
+ mintRunId() {
162
+ for (let attempt = 0; attempt < 20; attempt++) {
163
+ const id = `${RUN_ID_PREFIX}${randomRunIdSuffix()}`;
164
+ if (!this.runs.has(id))
165
+ return id;
166
+ }
167
+ throw new Error("Could not mint a unique delegation run id.");
168
+ }
169
+ /** Resolve a user- or model-supplied id, exact or by unambiguous prefix (spec 041): `show
170
+ * a1b2c3` and `show run_a1b2c3` both work without retyping the full id. */
171
+ resolveRef(query) {
172
+ const trimmed = query.trim();
173
+ const exact = this.runs.get(trimmed);
174
+ if (exact)
175
+ return { kind: "found", record: exact };
176
+ const needle = normalizeRunIdQuery(trimmed);
177
+ if (!needle)
178
+ return { kind: "not_found" };
179
+ const candidates = Array.from(this.runs.values()).filter((record) => normalizeRunIdQuery(record.runId).startsWith(needle));
180
+ if (candidates.length === 1)
181
+ return { kind: "found", record: candidates[0] };
182
+ if (candidates.length > 1)
183
+ return { kind: "ambiguous", candidates };
184
+ return { kind: "not_found" };
185
+ }
135
186
  /** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
136
187
  async register(input) {
137
188
  return hostAdmissionQueue.run("host", () => this.queue.run(input.runId, async () => {
@@ -146,6 +197,9 @@ export class SubAgentRunManager {
146
197
  throw new Error(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
147
198
  "Wait for one to finish before dispatching another.");
148
199
  }
200
+ if (this.runs.has(input.runId)) {
201
+ throw new Error(`Run id "${input.runId}" is already registered on this channel.`);
202
+ }
149
203
  const record = {
150
204
  ...input,
151
205
  status: "running",
@@ -448,7 +448,10 @@ export function createSubAgentTool(options) {
448
448
  }
449
449
  const config = invocation.config;
450
450
  const returns = params.returns ?? "text";
451
- const runContext = await prepareRunContext(_toolCallId, params, options);
451
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
452
+ // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
453
+ // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
454
+ const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
452
455
  // D9: an independent verifier checks against a target that isn't moving under it. It
453
456
  // never takes a lease itself, but a target with an active write lease is refused up
454
457
  // front — cheaper than explaining afterward why the attestation is worthless.
@@ -569,7 +572,6 @@ export function createSubAgentTool(options) {
569
572
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
570
573
  let detached = false;
571
574
  let lastUpdateText = "";
572
- const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
573
575
  try {
574
576
  await runManager.register({
575
577
  runId: runContext.runId,