@restranger/repi-subagents 0.0.0-stage → 0.0.1-sha.2ba2721

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/src/tools.ts ADDED
@@ -0,0 +1,546 @@
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
+ return runResult(run);
250
+ } catch (err) {
251
+ if (err instanceof UnknownAgentError) {
252
+ return errorResult(err.message);
253
+ }
254
+ return errorResult(`Could not start subagent: ${errorMessage(err)}`);
255
+ }
256
+ },
257
+ renderCall(args, theme) {
258
+ return linesComponent((width) => formatSubagentCall(args, theme, width));
259
+ },
260
+ renderResult(result, options, theme) {
261
+ const snapshot = isSubagentSnapshot(result.details) ? result.details : undefined;
262
+ return linesComponent((width) => {
263
+ if (!snapshot) {
264
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
265
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
266
+ }
267
+ if (options.isPartial || snapshot.status === "running") {
268
+ if (snapshot.background) {
269
+ return [];
270
+ }
271
+ return formatSubagentResultPartial(snapshot, theme, now(), spinnerFrame(), width);
272
+ }
273
+ if (options.expanded) {
274
+ return formatSubagentResultExpanded(snapshot, theme, now(), width);
275
+ }
276
+ if (snapshot.background && snapshot.status === "queued") {
277
+ return [];
278
+ }
279
+ return formatSubagentResultCompact(snapshot, theme, now(), width);
280
+ });
281
+ },
282
+ };
283
+
284
+ const statusTool: PiToolDefinition = {
285
+ name: "subagent_status",
286
+ label: "Subagent status",
287
+ description: "Show one subagent run by id, or all runs in this session.",
288
+ parameters: {
289
+ type: "object",
290
+ properties: { id: { type: "string", description: "Run id returned by subagent." } },
291
+ additionalProperties: false,
292
+ },
293
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
294
+ const resolved = sessionFor(ctx);
295
+ if (!resolved) {
296
+ return errorResult("subagent_status requires a Pi session context.");
297
+ }
298
+ const id = stringParam(params, "id");
299
+ if (id) {
300
+ const run = resolved.state.manager.get(id, resolved.sessionId);
301
+ return run ? runResult(run) : errorResult(`No subagent run "${id}" in this session.`);
302
+ }
303
+ const runs = resolved.state.manager.list(resolved.sessionId);
304
+ return textResult(formatRuns(runs), runs);
305
+ },
306
+ renderCall(args, theme) {
307
+ const id = stringParam(args, "id");
308
+ return linesComponent((width) => [
309
+ truncate(`${theme.fg("toolTitle", "subagent_status")}${id ? ` ${theme.fg("accent", id)}` : ""}`, width),
310
+ ]);
311
+ },
312
+ renderResult(result, options, theme) {
313
+ return linesComponent((width) => {
314
+ const details = result.details;
315
+ if (Array.isArray(details)) {
316
+ const runs = details.filter(isSubagentSnapshot);
317
+ if (!options.expanded) {
318
+ const active = runs.filter((r) => r.status === "running" || r.status === "queued").length;
319
+ const finished = runs.length - active;
320
+ const summary = `${theme.fg("toolTitle", "Subagents")} · ${active} active · ${finished} finished ${theme.fg("accent", "(enter to expand)")}`;
321
+ const lines = [truncate(summary, width)];
322
+ for (const r of runs.slice(-3)) {
323
+ lines.push(
324
+ truncate(
325
+ ` ${statusGlyph(r)} ${paintAgent(r.agent, theme, r.color)} · ${theme.fg(statusColor(r.status), r.status)} · ${formatDuration(runDuration(r))}`,
326
+ width,
327
+ ),
328
+ );
329
+ }
330
+ return lines;
331
+ }
332
+ const lines = [truncate(`${theme.fg("toolTitle", "Subagent Runs")} (${runs.length}):`, width)];
333
+ for (const r of runs) {
334
+ lines.push(
335
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
336
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
337
+ ),
338
+ );
339
+ }
340
+ return lines;
341
+ }
342
+ if (isSubagentSnapshot(details)) {
343
+ return options.expanded
344
+ ? formatSubagentResultExpanded(details, theme, now(), width)
345
+ : formatSubagentResultCompact(details, theme, now(), width);
346
+ }
347
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
348
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
349
+ });
350
+ },
351
+ };
352
+
353
+ const waitTool: PiToolDefinition = {
354
+ name: "subagent_wait",
355
+ label: "Wait for subagents",
356
+ description: "Wait for background subagent runs to finish (all active runs when `ids` is omitted).",
357
+ parameters: {
358
+ type: "object",
359
+ properties: {
360
+ ids: { type: "array", items: { type: "string" }, description: "Run ids to wait for." },
361
+ timeoutMs: { type: "integer", minimum: 0, description: "Maximum wait in milliseconds (default 120000)." },
362
+ },
363
+ additionalProperties: false,
364
+ },
365
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
366
+ const resolved = sessionFor(ctx);
367
+ if (!resolved) {
368
+ return errorResult("subagent_wait requires a Pi session context.");
369
+ }
370
+ const requested = Array.isArray(params.ids)
371
+ ? params.ids.filter((id): id is string => typeof id === "string")
372
+ : undefined;
373
+ // Unknown ids are an error: silently dropping them turned a typo into "waited for
374
+ // everything" and handed the caller a success it never earned.
375
+ const unknown = (requested ?? []).filter(
376
+ (id) => resolved.state.manager.get(id, resolved.sessionId) === undefined,
377
+ );
378
+ if (unknown.length > 0) {
379
+ return errorResult(`No subagent run ${unknown.map((id) => `"${id}"`).join(", ")} in this session.`);
380
+ }
381
+ const ids =
382
+ requested && requested.length > 0
383
+ ? requested
384
+ : resolved.state.manager
385
+ .list(resolved.sessionId)
386
+ .filter((run) => run.status === "queued" || run.status === "running")
387
+ .map((run) => run.id);
388
+ if (ids.length === 0) {
389
+ const finished = resolved.state.manager.list(resolved.sessionId);
390
+ return textResult(formatRuns(finished), finished);
391
+ }
392
+ const timeoutMs = numberParam(params, "timeoutMs") ?? 120_000;
393
+ await resolved.state.manager.wait(ids, timeoutMs, signal);
394
+ const runs = ids
395
+ .map((id) => resolved.state.manager.get(id, resolved.sessionId))
396
+ .filter((run): run is SubagentRunSnapshot => run !== undefined);
397
+ return textResult(
398
+ formatRuns(runs),
399
+ runs,
400
+ runs.some((run) => run.status === "failed" || run.status === "aborted"),
401
+ );
402
+ },
403
+ renderCall(args, theme) {
404
+ const ids = Array.isArray(args.ids) ? args.ids.join(", ") : "all";
405
+ return linesComponent((width) => [
406
+ truncate(`${theme.fg("toolTitle", "subagent_wait")} ${theme.fg("muted", `[${ids}]`)}`, width),
407
+ ]);
408
+ },
409
+ renderResult(result, options, theme) {
410
+ return linesComponent((width) => {
411
+ const details = result.details;
412
+ if (Array.isArray(details)) {
413
+ const runs = details.filter(isSubagentSnapshot);
414
+ if (!options.expanded) {
415
+ const completed = runs.filter((r) => r.status === "completed").length;
416
+ const failed = runs.filter((r) => r.status === "failed" || r.status === "aborted").length;
417
+ const note = failed > 0 ? theme.fg("error", ` · ${failed} failed`) : "";
418
+ const summary = `${theme.fg("toolTitle", "Waited")} for ${runs.length} subagents · ${theme.fg("success", `${completed} completed`)}${note} ${theme.fg("accent", "(enter to expand)")}`;
419
+ return [truncate(summary, width)];
420
+ }
421
+ const lines = [truncate(`${theme.fg("toolTitle", "Waited Subagents")} (${runs.length}):`, width)];
422
+ for (const r of runs) {
423
+ lines.push(
424
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
425
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
426
+ ),
427
+ );
428
+ }
429
+ return lines;
430
+ }
431
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
432
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
433
+ });
434
+ },
435
+ };
436
+
437
+ const abortTool: PiToolDefinition = {
438
+ name: "subagent_abort",
439
+ label: "Abort subagent",
440
+ description: "Abort a running or queued subagent run.",
441
+ parameters: {
442
+ type: "object",
443
+ properties: { id: { type: "string", description: "Run id returned by subagent." } },
444
+ required: ["id"],
445
+ additionalProperties: false,
446
+ },
447
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
448
+ const resolved = sessionFor(ctx);
449
+ if (!resolved) {
450
+ return errorResult("subagent_abort requires a Pi session context.");
451
+ }
452
+ const id = stringParam(params, "id");
453
+ if (!id) {
454
+ return errorResult("`id` is required.");
455
+ }
456
+ const aborted = resolved.state.manager.abort(id, resolved.sessionId);
457
+ return aborted
458
+ ? textResult(`Subagent run "${id}" aborted.`)
459
+ : errorResult(`No active subagent run "${id}" in this session.`);
460
+ },
461
+ renderCall(args, theme) {
462
+ const id = stringParam(args, "id");
463
+ return linesComponent((width) => [
464
+ truncate(`${theme.fg("toolTitle", "subagent_abort")}${id ? ` ${theme.fg("accent", id)}` : ""}`, width),
465
+ ]);
466
+ },
467
+ renderResult(result, _options, theme) {
468
+ const text = result.content[0]?.text ?? "";
469
+ return linesComponent((width) => [
470
+ truncate(result.isError ? theme.fg("error", text) : theme.fg("success", text), width),
471
+ ]);
472
+ },
473
+ };
474
+
475
+ const listTool: PiToolDefinition = {
476
+ name: "subagent_list",
477
+ label: "List subagents",
478
+ description:
479
+ "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.",
480
+ parameters: { type: "object", properties: {}, additionalProperties: false },
481
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
482
+ const resolved = sessionFor(ctx);
483
+ if (!resolved) {
484
+ return errorResult("subagent_list requires a Pi session context.");
485
+ }
486
+ const agents = resolved.state.registry.list();
487
+ const runs = resolved.state.manager.list(resolved.sessionId);
488
+ const diagnostics = resolved.state.registry.diagnostics();
489
+ const text = [
490
+ `Agents (${agents.length}):`,
491
+ formatAgentCatalog(agents, 100),
492
+ `Directories:\n${
493
+ resolved.state.registry
494
+ .directories()
495
+ .map((dir) => `- ${dir}`)
496
+ .join("\n") || "- none"
497
+ }`,
498
+ `Override configs:\n${
499
+ resolved.state.registry
500
+ .configFiles()
501
+ .map((file) => `- ${file}`)
502
+ .join("\n") || "- none"
503
+ }`,
504
+ `Concurrency limit: ${resolved.state.manager.getMaxConcurrent()} active runs`,
505
+ `Runs:\n${formatRunList(runs)}`,
506
+ `Diagnostics:\n${formatDiagnostics(diagnostics)}`,
507
+ ].join("\n\n");
508
+ return textResult(text, { agents, runs, diagnostics, configFiles: resolved.state.registry.configFiles() });
509
+ },
510
+ renderCall(_args, theme) {
511
+ return linesComponent((width) => [truncate(theme.fg("toolTitle", "subagent_list"), width)]);
512
+ },
513
+ renderResult(result, options, theme) {
514
+ return linesComponent((width) => {
515
+ const details = result.details as { agents?: AgentDefinition[]; runs?: SubagentRunSnapshot[] } | undefined;
516
+ if (Array.isArray(details?.agents)) {
517
+ if (!options.expanded) {
518
+ const agentNames = details.agents.map((a) => paintAgent(a.name, theme, a.color)).join(", ");
519
+ const summary = `${theme.fg("toolTitle", "Agents")} (${details.agents.length}): ${agentNames} ${theme.fg("accent", "(enter to expand catalog)")}`;
520
+ return [truncate(summary, width)];
521
+ }
522
+ const lines = [truncate(`${theme.fg("toolTitle", "Agent Catalogue")} (${details.agents.length}):`, width)];
523
+ for (const a of details.agents) {
524
+ lines.push(truncate(` - ${paintAgent(a.name, theme, a.color)} — ${a.description}`, width));
525
+ }
526
+ if (Array.isArray(details.runs) && details.runs.length > 0) {
527
+ const validRuns = details.runs.filter(isSubagentSnapshot);
528
+ lines.push(truncate(theme.fg("muted", `─── Runs in this session (${validRuns.length}) ───`), width));
529
+ for (const r of validRuns.slice(-5)) {
530
+ lines.push(
531
+ ...formatSubagentResultCompact(r, theme, now(), Math.max(1, width - 2)).map(
532
+ (l) => ` ${truncate(l, Math.max(0, width - 2))}`,
533
+ ),
534
+ );
535
+ }
536
+ }
537
+ return lines;
538
+ }
539
+ const text = result.content[0]?.text ?? (result.isError ? "Error" : "(no output)");
540
+ return [truncate(result.isError ? theme.fg("error", text) : text, width)];
541
+ });
542
+ },
543
+ };
544
+
545
+ return [subagentTool, statusTool, waitTool, abortTool, listTool];
546
+ }