@restranger/repi-subagents 0.0.0-stage → 0.0.1-ca9b82c

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.
@@ -0,0 +1,77 @@
1
+ import type { AgentDefinition } from "./types.js";
2
+
3
+ /** Tools a child agent may use when its declaration omits `tools:`. */
4
+ export const DEFAULT_CHILD_TOOLS = ["read", "bash", "edit", "write", "grep", "find", "ls"] as const;
5
+
6
+ /** Tools owned by this extension; a child must never inherit them (recursion guard). */
7
+ export const SUBAGENT_TOOL_NAMES = [
8
+ "subagent",
9
+ "subagent_status",
10
+ "subagent_wait",
11
+ "subagent_abort",
12
+ "subagent_list",
13
+ ] as const;
14
+
15
+ const RECURSION_GUARD = new Set<string>(SUBAGENT_TOOL_NAMES);
16
+
17
+ export interface ResolvedToolAllowlist {
18
+ /** `undefined` means "every tool the child session can see". */
19
+ readonly tools?: readonly string[];
20
+ readonly source: "default" | "all" | "list";
21
+ /** Requested tools the parent host does not currently expose. */
22
+ readonly unavailable: readonly string[];
23
+ }
24
+
25
+ /**
26
+ * Turn an agent declaration into the child session's tool allowlist.
27
+ *
28
+ * The declaration is the authority: an omitted `tools:` means the documented built-ins, `tools:
29
+ * none`/`[]` means none, and `tools: "*"` means every parent tool. The extension's own tool names
30
+ * are always removed, even when a declaration asks for them, because a child that can spawn
31
+ * children would make the parent's wait/abort ownership ambiguous in P0.
32
+ */
33
+ export function resolveToolAllowlist(
34
+ agent: AgentDefinition,
35
+ parentToolNames: readonly string[],
36
+ ): ResolvedToolAllowlist {
37
+ const disallowed = new Set(agent.disallowedTools);
38
+ const parent = parentToolNames.length > 0 ? new Set(parentToolNames) : undefined;
39
+
40
+ let source: ResolvedToolAllowlist["source"];
41
+ let requested: readonly string[] | undefined;
42
+ if (agent.tools === "*") {
43
+ source = "all";
44
+ requested = parent ? [...parent] : undefined;
45
+ } else if (agent.tools === undefined) {
46
+ source = "default";
47
+ requested = [...DEFAULT_CHILD_TOOLS];
48
+ } else {
49
+ source = "list";
50
+ requested = agent.tools;
51
+ }
52
+
53
+ const unavailable = parent && requested ? requested.filter((name) => !parent.has(name)) : [];
54
+ const filtered = requested
55
+ ?.filter((name) => !RECURSION_GUARD.has(name) && !disallowed.has(name))
56
+ .filter((name, index, list) => list.indexOf(name) === index);
57
+
58
+ return {
59
+ ...(filtered ? { tools: filtered } : {}),
60
+ source,
61
+ unavailable,
62
+ };
63
+ }
64
+
65
+ /** Human-readable form for listings and diagnostics. */
66
+ export function describeToolSpec(agent: AgentDefinition): string {
67
+ if (agent.tools === "*") {
68
+ return "all tools";
69
+ }
70
+ if (agent.tools === undefined) {
71
+ return "default tools";
72
+ }
73
+ if (agent.tools.length === 0) {
74
+ return "no tools";
75
+ }
76
+ return agent.tools.join(", ");
77
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,554 @@
1
+ import { type PiContext, type PiToolDefinition, type PiToolResult, SHIMMER_INTERVAL_MS } from "@restranger/repi-lib";
2
+ import {
3
+ formatAgentCatalog,
4
+ formatDiagnostics,
5
+ formatDuration,
6
+ formatRun,
7
+ formatRunList,
8
+ formatRunProgress,
9
+ formatRuns,
10
+ formatSubagentCall,
11
+ formatSubagentResultCompact,
12
+ formatSubagentResultExpanded,
13
+ formatSubagentResultPartial,
14
+ linesComponent,
15
+ paintAgent,
16
+ runDuration,
17
+ statusColor,
18
+ statusGlyph,
19
+ truncate,
20
+ } from "./format.js";
21
+ import { type SubagentManager, UnknownAgentError } from "./manager.js";
22
+ import { SUBAGENT_GUIDELINES } from "./prompt.js";
23
+ import type { AgentRegistry } from "./registry.js";
24
+ import { type AgentDefinition, type SubagentRunSnapshot, isSubagentSnapshot } from "./types.js";
25
+
26
+ /** The slice of a live session the tools need; the runtime state in plugin.ts satisfies it. */
27
+ export interface SubagentToolState {
28
+ readonly ctx: PiContext;
29
+ readonly registry: AgentRegistry;
30
+ readonly manager: SubagentManager;
31
+ }
32
+
33
+ export interface SubagentSessionHandle {
34
+ readonly sessionId: string;
35
+ readonly state: SubagentToolState;
36
+ }
37
+
38
+ /**
39
+ * Host hooks for the tool definitions.
40
+ *
41
+ * The tools hold no runtime state of their own: the spinner, the clock and the registry behind the
42
+ * dynamic subagent description all arrive as callbacks, so /subagents reload and the widget timer
43
+ * keep driving the same objects they always did.
44
+ */
45
+ export interface SubagentToolsContext {
46
+ /** Resolve the session a tool call belongs to; undefined outside a Pi session. */
47
+ readonly sessionFor: (ctx: PiContext | undefined) => SubagentSessionHandle | undefined;
48
+ /** Current registry for the tool description; refreshed by /subagents reload. */
49
+ readonly descriptionRegistry: () => AgentRegistry;
50
+ readonly now: () => number;
51
+ readonly spinnerFrame: () => string;
52
+ /** Advance the shared spinner frame used by streaming progress. */
53
+ readonly tickSpinner: () => void;
54
+ }
55
+
56
+ const errorResult = (message: string): PiToolResult => ({
57
+ content: [{ type: "text", text: message }],
58
+ isError: true,
59
+ });
60
+
61
+ const textResult = (text: string, details?: unknown, isError = false): PiToolResult => ({
62
+ content: [{ type: "text", text }],
63
+ ...(details !== undefined ? { details } : {}),
64
+ ...(isError ? { isError: true } : {}),
65
+ });
66
+
67
+ const runResult = (run: SubagentRunSnapshot): PiToolResult =>
68
+ textResult(formatRun(run), run, run.status === "failed" || run.status === "aborted");
69
+
70
+ const stringParam = (params: Record<string, unknown>, key: string): string | undefined => {
71
+ const value = params[key];
72
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
73
+ };
74
+
75
+ const numberParam = (params: Record<string, unknown>, key: string): number | undefined => {
76
+ const value = params[key];
77
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
78
+ };
79
+
80
+ const listParam = (params: Record<string, unknown>, key: string): string[] | undefined => {
81
+ const value = params[key];
82
+ if (Array.isArray(value)) {
83
+ const items = value.filter((v): v is string => typeof v === "string" && v.trim().length > 0).map((v) => v.trim());
84
+ return items.length > 0 ? items : undefined;
85
+ }
86
+ if (typeof value === "string" && value.trim().length > 0) {
87
+ const items = value
88
+ .split(",")
89
+ .map((v) => v.trim())
90
+ .filter(Boolean);
91
+ return items.length > 0 ? items : undefined;
92
+ }
93
+ return undefined;
94
+ };
95
+
96
+ function errorMessage(error: unknown): string {
97
+ return error instanceof Error ? error.message : String(error);
98
+ }
99
+
100
+ /** Build the five tool definitions this plugin registers with Pi. */
101
+ export function createSubagentTools(context: SubagentToolsContext): PiToolDefinition[] {
102
+ const { sessionFor, descriptionRegistry, now, spinnerFrame, tickSpinner } = context;
103
+
104
+ const subagentTool: PiToolDefinition = {
105
+ name: "subagent",
106
+ label: "Subagent",
107
+ // Rules live on the tool definition, so Pi renders them in the `<rules>` block next to the
108
+ // built-in tool rules and drops them when the tool is not active. Without them the model
109
+ // reads `subagent` as an incidental extra and grinds through inline read/grep loops.
110
+ promptGuidelines: SUBAGENT_GUIDELINES,
111
+ promptSnippet: "Run one declarative subagent in an isolated child session and get its report.",
112
+ get description() {
113
+ // The catalog itself lives in the system prompt (`formatAgentPromptSection`), so this
114
+ // description stays cheap: names only, and an explicit instruction not to go looking.
115
+ const names = descriptionRegistry()
116
+ .list()
117
+ .map((agent) => agent.name)
118
+ .join(", ");
119
+ return [
120
+ "Run one declarative subagent in an isolated child session. The child starts with fresh context; include everything it needs in `task` (`prompt` is accepted as an alias).",
121
+ names ? `Declared agents: ${names}.` : "No declarative agents are configured.",
122
+ "Descriptions and tool allowlists are in the Repi subagents section of your system prompt; delegate directly instead of listing agents first.",
123
+ "Use subagent_status, subagent_wait and subagent_abort for background runs. Set `background: true` to return immediately. Run /subagents fleet for the live dashboard.",
124
+ ].join("\n");
125
+ },
126
+ parameters: {
127
+ type: "object",
128
+ properties: {
129
+ agent: { type: "string", description: "Declared agent name (see the list in this tool's description)." },
130
+ task: {
131
+ type: "string",
132
+ description: "Complete task for the subagent. The child does not see the parent conversation.",
133
+ },
134
+ prompt: {
135
+ type: "string",
136
+ description: "Alias for `task` (accepted for Claude-style tool calls).",
137
+ },
138
+ description: { type: "string", description: "Short 3-5 word label for the status widget." },
139
+ background: { type: "boolean", description: "Return immediately and keep working in the background." },
140
+ async: { type: "boolean", description: "Alias for background." },
141
+ model: { type: "string", description: "Override the agent's model (provider/model or fuzzy name)." },
142
+ fallbackModels: {
143
+ type: "array",
144
+ items: { type: "string" },
145
+ description: "Fallback models to try if the primary model fails (provider/model, fuzzy name, or 'inherit').",
146
+ },
147
+ maxTurns: { type: "integer", minimum: 2, description: "Override the agent's turn limit." },
148
+ },
149
+ required: ["agent"],
150
+ additionalProperties: false,
151
+ },
152
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
153
+ const resolved = sessionFor(ctx);
154
+ if (!resolved) {
155
+ return errorResult("Subagent tool requires a Pi session context.");
156
+ }
157
+ const agent = stringParam(params, "agent");
158
+ const task = stringParam(params, "task") ?? stringParam(params, "prompt");
159
+ if (!agent || !task) {
160
+ return errorResult("Both `agent` and `task` (or `prompt`) are required.");
161
+ }
162
+ try {
163
+ // An explicit `background` wins even when it is `false`; `??` would let it cancel
164
+ // a Claude-style `async: true`.
165
+ const requestedBackground =
166
+ typeof params.background === "boolean"
167
+ ? params.background
168
+ : typeof params.async === "boolean"
169
+ ? params.async
170
+ : undefined;
171
+ const requestedModel = stringParam(params, "model");
172
+ const requestedFallbackModels =
173
+ listParam(params, "fallbackModels") ?? listParam(params, "fallback_models") ?? listParam(params, "fallbacks");
174
+ const parentModelRuntime = resolved.state.ctx.modelRegistry?.runtime;
175
+ const requestedMaxTurns = numberParam(params, "maxTurns");
176
+ const requestedDescription = stringParam(params, "description");
177
+ // A foreground run streams its progress into the tool call, the way both reference
178
+ // implementations do; it stops once the call resumes (a background spawn resolves early).
179
+ const streaming = typeof onUpdate === "function" ? (onUpdate as (result: PiToolResult) => void) : undefined;
180
+ let foreground = requestedBackground !== true;
181
+ let latestSnapshot: SubagentRunSnapshot | undefined;
182
+ let progressTimer: ReturnType<typeof setInterval> | undefined;
183
+
184
+ const pushProgress = (snapshot: SubagentRunSnapshot): void => {
185
+ if (!foreground || !streaming) {
186
+ return;
187
+ }
188
+ const step = Math.floor(now() / SHIMMER_INTERVAL_MS);
189
+ streaming({
190
+ content: [
191
+ {
192
+ type: "text",
193
+ text: formatRunProgress(snapshot, now(), spinnerFrame(), 100, undefined, step),
194
+ },
195
+ ],
196
+ details: snapshot,
197
+ });
198
+ };
199
+
200
+ if (streaming && foreground) {
201
+ progressTimer = setInterval(() => {
202
+ tickSpinner();
203
+ if (latestSnapshot && foreground) {
204
+ pushProgress(latestSnapshot);
205
+ }
206
+ }, SHIMMER_INTERVAL_MS);
207
+ progressTimer.unref?.();
208
+ }
209
+
210
+ let run: SubagentRunSnapshot;
211
+ try {
212
+ run = await resolved.state.manager.spawn({
213
+ agent,
214
+ task,
215
+ cwd: resolved.state.ctx.cwd,
216
+ parentSessionId: resolved.sessionId,
217
+ ...(typeof requestedBackground === "boolean" ? { background: requestedBackground } : {}),
218
+ ...(requestedDescription ? { description: requestedDescription } : {}),
219
+ ...(requestedModel ? { model: requestedModel } : {}),
220
+ ...(requestedFallbackModels ? { fallbackModels: requestedFallbackModels } : {}),
221
+ ...(requestedMaxTurns !== undefined ? { maxTurns: requestedMaxTurns } : {}),
222
+ ...(resolved.state.ctx.model ? { parentModel: resolved.state.ctx.model } : {}),
223
+ ...(parentModelRuntime !== undefined ? { parentModelRuntime } : {}),
224
+ ...(resolved.state.ctx.thinkingLevel ? { parentThinkingLevel: resolved.state.ctx.thinkingLevel } : {}),
225
+ ...(resolved.state.ctx.modelRegistry ? { parentModelRegistry: resolved.state.ctx.modelRegistry } : {}),
226
+ ...(signal ? { signal } : {}),
227
+ ...(streaming && foreground
228
+ ? {
229
+ onUpdate: (snapshot: SubagentRunSnapshot) => {
230
+ latestSnapshot = snapshot;
231
+ pushProgress(snapshot);
232
+ },
233
+ }
234
+ : {}),
235
+ });
236
+ } finally {
237
+ foreground = false;
238
+ if (progressTimer) {
239
+ clearInterval(progressTimer);
240
+ progressTimer = undefined;
241
+ }
242
+ }
243
+ if (run.background && (run.status === "queued" || run.status === "running")) {
244
+ return textResult(
245
+ `Subagent "${run.agent}" started in background (${run.id}). Use subagent_wait or subagent_status to collect it.`,
246
+ run,
247
+ );
248
+ }
249
+ // The result is already in this tool output, so the prompt must stop asking for it.
250
+ resolved.state.manager.markCollected([run.id]);
251
+ return runResult(run);
252
+ } catch (err) {
253
+ if (err instanceof UnknownAgentError) {
254
+ return errorResult(err.message);
255
+ }
256
+ return errorResult(`Could not start subagent: ${errorMessage(err)}`);
257
+ }
258
+ },
259
+ renderCall(args, theme) {
260
+ return linesComponent((width) => formatSubagentCall(args, theme, width));
261
+ },
262
+ renderResult(result, options, theme) {
263
+ const snapshot = isSubagentSnapshot(result.details) ? result.details : undefined;
264
+ return linesComponent((width) => {
265
+ if (!snapshot) {
266
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
267
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
268
+ }
269
+ if (options.isPartial || snapshot.status === "running") {
270
+ if (snapshot.background) {
271
+ return [];
272
+ }
273
+ return formatSubagentResultPartial(snapshot, theme, now(), spinnerFrame(), width);
274
+ }
275
+ if (options.expanded) {
276
+ return formatSubagentResultExpanded(snapshot, theme, now(), width);
277
+ }
278
+ if (snapshot.background && snapshot.status === "queued") {
279
+ return [];
280
+ }
281
+ return formatSubagentResultCompact(snapshot, theme, now(), width);
282
+ });
283
+ },
284
+ };
285
+
286
+ const statusTool: PiToolDefinition = {
287
+ name: "subagent_status",
288
+ label: "Subagent status",
289
+ description: "Show one subagent run by id, or all runs in this session.",
290
+ parameters: {
291
+ type: "object",
292
+ properties: { id: { type: "string", description: "Run id returned by subagent." } },
293
+ additionalProperties: false,
294
+ },
295
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
296
+ const resolved = sessionFor(ctx);
297
+ if (!resolved) {
298
+ return errorResult("subagent_status requires a Pi session context.");
299
+ }
300
+ const id = stringParam(params, "id");
301
+ if (id) {
302
+ const run = resolved.state.manager.get(id, resolved.sessionId);
303
+ if (!run) {
304
+ return errorResult(`No subagent run "${id}" in this session.`);
305
+ }
306
+ // Inspecting one run counts as reading its result, even when it is still running
307
+ // (the flag only lands on settled runs).
308
+ resolved.state.manager.markCollected([id]);
309
+ return runResult(run);
310
+ }
311
+ const runs = resolved.state.manager.list(resolved.sessionId);
312
+ return textResult(formatRuns(runs), runs);
313
+ },
314
+ renderCall(args, theme) {
315
+ const id = stringParam(args, "id");
316
+ return linesComponent((width) => [
317
+ truncate(`${theme.fg("toolTitle", "subagent_status")}${id ? ` ${theme.fg("accent", id)}` : ""}`, width),
318
+ ]);
319
+ },
320
+ renderResult(result, options, theme) {
321
+ return linesComponent((width) => {
322
+ const details = result.details;
323
+ if (Array.isArray(details)) {
324
+ const runs = details.filter(isSubagentSnapshot);
325
+ if (!options.expanded) {
326
+ const active = runs.filter((r) => r.status === "running" || r.status === "queued").length;
327
+ const finished = runs.length - active;
328
+ const summary = `${theme.fg("toolTitle", "Subagents")} · ${active} active · ${finished} finished ${theme.fg("accent", "(enter to expand)")}`;
329
+ const lines = [truncate(summary, width)];
330
+ for (const r of runs.slice(-3)) {
331
+ lines.push(
332
+ truncate(
333
+ ` ${statusGlyph(r)} ${paintAgent(r.agent, theme, r.color)} · ${theme.fg(statusColor(r.status), r.status)} · ${formatDuration(runDuration(r))}`,
334
+ width,
335
+ ),
336
+ );
337
+ }
338
+ return lines;
339
+ }
340
+ const lines = [truncate(`${theme.fg("toolTitle", "Subagent Runs")} (${runs.length}):`, width)];
341
+ for (const r of runs) {
342
+ lines.push(
343
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
344
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
345
+ ),
346
+ );
347
+ }
348
+ return lines;
349
+ }
350
+ if (isSubagentSnapshot(details)) {
351
+ return options.expanded
352
+ ? formatSubagentResultExpanded(details, theme, now(), width)
353
+ : formatSubagentResultCompact(details, theme, now(), width);
354
+ }
355
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
356
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
357
+ });
358
+ },
359
+ };
360
+
361
+ const waitTool: PiToolDefinition = {
362
+ name: "subagent_wait",
363
+ label: "Wait for subagents",
364
+ description: "Wait for background subagent runs to finish (all active runs when `ids` is omitted).",
365
+ parameters: {
366
+ type: "object",
367
+ properties: {
368
+ ids: { type: "array", items: { type: "string" }, description: "Run ids to wait for." },
369
+ timeoutMs: { type: "integer", minimum: 0, description: "Maximum wait in milliseconds (default 120000)." },
370
+ },
371
+ additionalProperties: false,
372
+ },
373
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
374
+ const resolved = sessionFor(ctx);
375
+ if (!resolved) {
376
+ return errorResult("subagent_wait requires a Pi session context.");
377
+ }
378
+ const requested = Array.isArray(params.ids)
379
+ ? params.ids.filter((id): id is string => typeof id === "string")
380
+ : undefined;
381
+ // Unknown ids are an error: silently dropping them turned a typo into "waited for
382
+ // everything" and handed the caller a success it never earned.
383
+ const unknown = (requested ?? []).filter(
384
+ (id) => resolved.state.manager.get(id, resolved.sessionId) === undefined,
385
+ );
386
+ if (unknown.length > 0) {
387
+ return errorResult(`No subagent run ${unknown.map((id) => `"${id}"`).join(", ")} in this session.`);
388
+ }
389
+ const ids =
390
+ requested && requested.length > 0
391
+ ? requested
392
+ : resolved.state.manager
393
+ .list(resolved.sessionId)
394
+ .filter((run) => run.status === "queued" || run.status === "running")
395
+ .map((run) => run.id);
396
+ if (ids.length === 0) {
397
+ const finished = resolved.state.manager.list(resolved.sessionId);
398
+ return textResult(formatRuns(finished), finished);
399
+ }
400
+ const timeoutMs = numberParam(params, "timeoutMs") ?? 120_000;
401
+ await resolved.state.manager.wait(ids, timeoutMs, signal);
402
+ const runs = ids
403
+ .map((id) => resolved.state.manager.get(id, resolved.sessionId))
404
+ .filter((run): run is SubagentRunSnapshot => run !== undefined);
405
+ return textResult(
406
+ formatRuns(runs),
407
+ runs,
408
+ runs.some((run) => run.status === "failed" || run.status === "aborted"),
409
+ );
410
+ },
411
+ renderCall(args, theme) {
412
+ const ids = Array.isArray(args.ids) ? args.ids.join(", ") : "all";
413
+ return linesComponent((width) => [
414
+ truncate(`${theme.fg("toolTitle", "subagent_wait")} ${theme.fg("muted", `[${ids}]`)}`, width),
415
+ ]);
416
+ },
417
+ renderResult(result, options, theme) {
418
+ return linesComponent((width) => {
419
+ const details = result.details;
420
+ if (Array.isArray(details)) {
421
+ const runs = details.filter(isSubagentSnapshot);
422
+ if (!options.expanded) {
423
+ const completed = runs.filter((r) => r.status === "completed").length;
424
+ const failed = runs.filter((r) => r.status === "failed" || r.status === "aborted").length;
425
+ const note = failed > 0 ? theme.fg("error", ` · ${failed} failed`) : "";
426
+ const summary = `${theme.fg("toolTitle", "Waited")} for ${runs.length} subagents · ${theme.fg("success", `${completed} completed`)}${note} ${theme.fg("accent", "(enter to expand)")}`;
427
+ return [truncate(summary, width)];
428
+ }
429
+ const lines = [truncate(`${theme.fg("toolTitle", "Waited Subagents")} (${runs.length}):`, width)];
430
+ for (const r of runs) {
431
+ lines.push(
432
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
433
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
434
+ ),
435
+ );
436
+ }
437
+ return lines;
438
+ }
439
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
440
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
441
+ });
442
+ },
443
+ };
444
+
445
+ const abortTool: PiToolDefinition = {
446
+ name: "subagent_abort",
447
+ label: "Abort subagent",
448
+ description: "Abort a running or queued subagent run.",
449
+ parameters: {
450
+ type: "object",
451
+ properties: { id: { type: "string", description: "Run id returned by subagent." } },
452
+ required: ["id"],
453
+ additionalProperties: false,
454
+ },
455
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
456
+ const resolved = sessionFor(ctx);
457
+ if (!resolved) {
458
+ return errorResult("subagent_abort requires a Pi session context.");
459
+ }
460
+ const id = stringParam(params, "id");
461
+ if (!id) {
462
+ return errorResult("`id` is required.");
463
+ }
464
+ const aborted = resolved.state.manager.abort(id, resolved.sessionId);
465
+ return aborted
466
+ ? textResult(`Subagent run "${id}" aborted.`)
467
+ : errorResult(`No active subagent run "${id}" in this session.`);
468
+ },
469
+ renderCall(args, theme) {
470
+ const id = stringParam(args, "id");
471
+ return linesComponent((width) => [
472
+ truncate(`${theme.fg("toolTitle", "subagent_abort")}${id ? ` ${theme.fg("accent", id)}` : ""}`, width),
473
+ ]);
474
+ },
475
+ renderResult(result, _options, theme) {
476
+ const text = result.content[0]?.text ?? "";
477
+ return linesComponent((width) => [
478
+ truncate(result.isError ? theme.fg("error", text) : theme.fg("success", text), width),
479
+ ]);
480
+ },
481
+ };
482
+
483
+ const listTool: PiToolDefinition = {
484
+ name: "subagent_list",
485
+ label: "List subagents",
486
+ description:
487
+ "Diagnostics for the subagent setup: scanned directories, override config files, discovery diagnostics and runs in this session. Not needed to choose an agent — the catalog is already in the system prompt.",
488
+ parameters: { type: "object", properties: {}, additionalProperties: false },
489
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
490
+ const resolved = sessionFor(ctx);
491
+ if (!resolved) {
492
+ return errorResult("subagent_list requires a Pi session context.");
493
+ }
494
+ const agents = resolved.state.registry.list();
495
+ const runs = resolved.state.manager.list(resolved.sessionId);
496
+ const diagnostics = resolved.state.registry.diagnostics();
497
+ const text = [
498
+ `Agents (${agents.length}):`,
499
+ formatAgentCatalog(agents, 100),
500
+ `Directories:\n${
501
+ resolved.state.registry
502
+ .directories()
503
+ .map((dir) => `- ${dir}`)
504
+ .join("\n") || "- none"
505
+ }`,
506
+ `Override configs:\n${
507
+ resolved.state.registry
508
+ .configFiles()
509
+ .map((file) => `- ${file}`)
510
+ .join("\n") || "- none"
511
+ }`,
512
+ `Concurrency limit: ${resolved.state.manager.getMaxConcurrent()} active runs`,
513
+ `Runs:\n${formatRunList(runs)}`,
514
+ `Diagnostics:\n${formatDiagnostics(diagnostics)}`,
515
+ ].join("\n\n");
516
+ return textResult(text, { agents, runs, diagnostics, configFiles: resolved.state.registry.configFiles() });
517
+ },
518
+ renderCall(_args, theme) {
519
+ return linesComponent((width) => [truncate(theme.fg("toolTitle", "subagent_list"), width)]);
520
+ },
521
+ renderResult(result, options, theme) {
522
+ return linesComponent((width) => {
523
+ const details = result.details as { agents?: AgentDefinition[]; runs?: SubagentRunSnapshot[] } | undefined;
524
+ if (Array.isArray(details?.agents)) {
525
+ if (!options.expanded) {
526
+ const agentNames = details.agents.map((a) => paintAgent(a.name, theme, a.color)).join(", ");
527
+ const summary = `${theme.fg("toolTitle", "Agents")} (${details.agents.length}): ${agentNames} ${theme.fg("accent", "(enter to expand catalog)")}`;
528
+ return [truncate(summary, width)];
529
+ }
530
+ const lines = [truncate(`${theme.fg("toolTitle", "Agent Catalogue")} (${details.agents.length}):`, width)];
531
+ for (const a of details.agents) {
532
+ lines.push(truncate(` - ${paintAgent(a.name, theme, a.color)} — ${a.description}`, width));
533
+ }
534
+ if (Array.isArray(details.runs) && details.runs.length > 0) {
535
+ const validRuns = details.runs.filter(isSubagentSnapshot);
536
+ lines.push(truncate(theme.fg("muted", `─── Runs in this session (${validRuns.length}) ───`), width));
537
+ for (const r of validRuns.slice(-5)) {
538
+ lines.push(
539
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
540
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
541
+ ),
542
+ );
543
+ }
544
+ }
545
+ return lines;
546
+ }
547
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
548
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
549
+ });
550
+ },
551
+ };
552
+
553
+ return [subagentTool, statusTool, waitTool, abortTool, listTool];
554
+ }