pi-herdr-managed-agents 0.1.0-beta.1

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,951 @@
1
+ /**
2
+ * Subagents — spawn background subagents on one of three backends
3
+ * (pi, Claude Code, Codex) unified behind a single Effect service interface.
4
+ *
5
+ * Tools (for the parent LLM):
6
+ * - subagent_spawn: fire-and-forget spawn (prompt, title, agent, working_dir,
7
+ * model, reasoning_effort, mode). Max 4 running at once across all backends.
8
+ * - subagent_wait: block until the listed subagents settle, return results.
9
+ * - subagent_send: steer or continue an existing native session.
10
+ * - subagent_cancel: stop one or more running subagents.
11
+ * - subagent_check: peek at a subagent's status and recent activity.
12
+ * - subagent_list: list all subagents.
13
+ *
14
+ * Unawaited subagents queue their result as a follow-up message when they
15
+ * settle. `/subagents` opens a picker + full interactive takeover view.
16
+ *
17
+ * Architecture: Effect v4 generators throughout (backends -> manager ->
18
+ * runtime); this file is the async boundary where tool handlers run effects
19
+ * against one shared ManagedRuntime. Inside Herdr, all harnesses launch their
20
+ * real interactive CLIs in separate full-size tabs. Outside Herdr, pi runs in-process,
21
+ * Claude uses its Agent SDK, and Codex uses `codex app-server` JSON-RPC.
22
+ */
23
+
24
+ import * as fs from "node:fs";
25
+ import * as path from "node:path";
26
+ import { StringEnum } from "@earendil-works/pi-ai";
27
+ import type {
28
+ ExtensionAPI,
29
+ ExtensionCommandContext,
30
+ ExtensionContext,
31
+ ExtensionUIContext,
32
+ } from "@earendil-works/pi-coding-agent";
33
+ import {
34
+ DEFAULT_MAX_BYTES,
35
+ DEFAULT_MAX_LINES,
36
+ formatSize,
37
+ getAgentDir,
38
+ getMarkdownTheme,
39
+ ProjectTrustStore,
40
+ truncateHead,
41
+ } from "@earendil-works/pi-coding-agent";
42
+ import { Markdown, Text } from "@earendil-works/pi-tui";
43
+ import { Type } from "typebox";
44
+ import { deriveBtwTitle, isModelVisible } from "./src/by-the-way.ts";
45
+ import {
46
+ BACKEND_NAMES,
47
+ formatElapsed,
48
+ latestText,
49
+ REASONING_EFFORTS,
50
+ SUBAGENT_MODES,
51
+ type SubagentSnapshot,
52
+ } from "./src/domain.ts";
53
+ import {
54
+ formatActivityStatus,
55
+ formatContextUtilization,
56
+ } from "./src/format.ts";
57
+ import { SubagentManager, type SubagentManagerShape } from "./src/manager.ts";
58
+ import {
59
+ buildSubagentInputRequiredMessage,
60
+ buildSubagentResultMessage,
61
+ buildSubagentSpawnResult,
62
+ buildTerminalCleanupReminder,
63
+ SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS,
64
+ SUBAGENT_CANCEL_TOOL_DESCRIPTION,
65
+ SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS,
66
+ SUBAGENT_CHECK_TOOL_DESCRIPTION,
67
+ SUBAGENT_LIST_TOOL_DESCRIPTION,
68
+ SUBAGENT_SEND_PARAMETER_DESCRIPTIONS,
69
+ SUBAGENT_SEND_TOOL_DESCRIPTION,
70
+ SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS,
71
+ SUBAGENT_SPAWN_PROMPT_GUIDELINES,
72
+ SUBAGENT_SPAWN_PROMPT_SNIPPET,
73
+ SUBAGENT_SPAWN_TOOL_DESCRIPTION,
74
+ SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS,
75
+ SUBAGENT_WAIT_TOOL_DESCRIPTION,
76
+ } from "./src/prompt.ts";
77
+ import { createDeferredResultDelivery } from "./src/result-delivery.ts";
78
+ import {
79
+ createSubagentRuntime,
80
+ runTool,
81
+ type SubagentRuntime,
82
+ } from "./src/runtime.ts";
83
+ import { openSubagentPicker, openSubagentTakeover } from "./src/ui/takeover.ts";
84
+
85
+ const SUBAGENT_OUTPUT_MAX_BYTES = 24 * 1024;
86
+ const WAIT_OUTPUT_MAX_BYTES = 48 * 1024;
87
+ const WAIT_PER_AGENT_MAX_BYTES = 16 * 1024;
88
+
89
+ interface BtwResultData {
90
+ readonly id: string;
91
+ readonly title: string;
92
+ readonly status: SubagentSnapshot["status"];
93
+ readonly errorText?: string;
94
+ readonly prompt: string;
95
+ readonly answer: string;
96
+ readonly sessionFilePath?: string;
97
+ }
98
+
99
+ function describeSubagent(snap: SubagentSnapshot) {
100
+ const details = [
101
+ `${snap.backend}: ${snap.meta.modelLabel ?? "?"}`,
102
+ formatContextUtilization(snap.usage),
103
+ formatElapsed(snap),
104
+ snap.cwd,
105
+ snap.meta.herdrTabId ? `tab ${snap.meta.herdrTabId}` : undefined,
106
+ snap.meta.herdrPaneId ? `pane ${snap.meta.herdrPaneId}` : undefined,
107
+ ].filter(Boolean);
108
+ const status = snap.inputRequired ? "needs-input" : snap.status;
109
+ return `${snap.id} [${status}] "${snap.title}" (${details.join(", ")})`;
110
+ }
111
+
112
+ function truncatedOutput(
113
+ snap: SubagentSnapshot,
114
+ maxBytes = SUBAGENT_OUTPUT_MAX_BYTES,
115
+ ): string {
116
+ const output = snap.finalText || "(no output)";
117
+ const truncation = truncateHead(output, {
118
+ maxBytes: Math.min(maxBytes, DEFAULT_MAX_BYTES),
119
+ maxLines: Math.min(600, DEFAULT_MAX_LINES),
120
+ });
121
+ let text = truncation.content;
122
+ if (truncation.truncated) {
123
+ text += `\n\n[Output truncated: ${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)} shown. Full transcript in session file: ${snap.meta.sessionFilePath ?? "?"}]`;
124
+ }
125
+ return text;
126
+ }
127
+
128
+ export function formatWaitSection(
129
+ snap: SubagentSnapshot,
130
+ remainingBytes: number,
131
+ ) {
132
+ const running = snap.status === "running";
133
+ const verb = running
134
+ ? snap.inputRequired
135
+ ? "needs input"
136
+ : "is still running"
137
+ : snap.status === "error"
138
+ ? "failed"
139
+ : "finished";
140
+ let section = `## ${snap.id} "${snap.title}" ${verb}`;
141
+ if (snap.errorText) section += `\nError: ${snap.errorText}`;
142
+ if (running) {
143
+ section += snap.inputRequired
144
+ ? `\nInput required: ${snap.inputRequired}`
145
+ : "\nThis wait returned early for another child. Its result will arrive automatically.";
146
+ return section;
147
+ }
148
+ const outputBudget = Math.max(
149
+ 512,
150
+ Math.min(
151
+ WAIT_PER_AGENT_MAX_BYTES,
152
+ remainingBytes - Buffer.byteLength(section, "utf8") - 2,
153
+ ),
154
+ );
155
+ section += `\n\n${truncatedOutput(snap, outputBudget)}`;
156
+ const cleanup = buildTerminalCleanupReminder(snap.meta);
157
+ if (cleanup) section += `\n\n${cleanup}`;
158
+ return section;
159
+ }
160
+
161
+ function canonicalPath(candidate: string) {
162
+ try {
163
+ return fs.realpathSync(candidate);
164
+ } catch {
165
+ return path.resolve(candidate);
166
+ }
167
+ }
168
+
169
+ function isWithin(candidate: string, root: string) {
170
+ const relative = path.relative(canonicalPath(root), canonicalPath(candidate));
171
+ return (
172
+ relative === "" ||
173
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
174
+ );
175
+ }
176
+
177
+ /**
178
+ * Same-directory children inherit the live parent decision. Pi's user-owned
179
+ * global agent directory is inherently trusted; any other alternate cwd must
180
+ * be explicitly trusted in the persisted store. Invalid data fails closed.
181
+ */
182
+ export function resolveChildProjectTrust(options: {
183
+ parentCwd: string;
184
+ childCwd: string;
185
+ parentTrusted: boolean;
186
+ }) {
187
+ if (path.resolve(options.childCwd) === path.resolve(options.parentCwd)) {
188
+ return options.parentTrusted;
189
+ }
190
+ // An untrusted parent must not escape into any trusted directory and launch
191
+ // a permission-bypassing child there.
192
+ if (!options.parentTrusted) return false;
193
+ if (isWithin(options.childCwd, getAgentDir())) return true;
194
+ try {
195
+ const trustStore = new ProjectTrustStore(getAgentDir());
196
+ return trustStore.get(options.childCwd) === true;
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+
202
+ export default function (pi: ExtensionAPI) {
203
+ let runtime: SubagentRuntime | undefined;
204
+ let managerPromise: Promise<SubagentManagerShape> | undefined;
205
+ let sessionContext: ExtensionContext | undefined;
206
+ let ui: ExtensionUIContext | undefined;
207
+ let unsubStatus: (() => void) | undefined;
208
+ const notifiedInputVersions = new Map<string, number>();
209
+ const resultDelivery = createDeferredResultDelivery<SubagentSnapshot>();
210
+
211
+ const getRuntime = () => (runtime ??= createSubagentRuntime());
212
+
213
+ /** Resolve the manager service once per runtime and wire the extension hooks. */
214
+ const getManager = () => {
215
+ managerPromise ??= getRuntime()
216
+ .runPromise(SubagentManager)
217
+ .then((manager) => {
218
+ manager.view.setOnSettled(onSettled);
219
+ unsubStatus?.();
220
+ unsubStatus = manager.view.subscribe(() =>
221
+ handleManagerChange(manager),
222
+ );
223
+ handleManagerChange(manager);
224
+ return manager;
225
+ });
226
+ return managerPromise;
227
+ };
228
+
229
+ const updateStatus = (manager: SubagentManagerShape) => {
230
+ if (!ui) return;
231
+ const subs = manager.view.list();
232
+ if (subs.length === 0) {
233
+ ui.setStatus("subagents", undefined);
234
+ return;
235
+ }
236
+ const running = subs.filter((snap) => snap.status === "running").length;
237
+ const failed = subs.filter((snap) => snap.status === "error").length;
238
+ const done = subs.length - running - failed;
239
+ ui.setStatus(
240
+ "subagents",
241
+ formatActivityStatus(ui.theme, { running, done, failed }),
242
+ );
243
+ };
244
+
245
+ const handleManagerChange = (manager: SubagentManagerShape) => {
246
+ updateStatus(manager);
247
+ for (const snap of manager.view.list()) {
248
+ if (
249
+ snap.origin !== "model" ||
250
+ snap.status !== "running" ||
251
+ !snap.inputRequired ||
252
+ snap.inputRequiredVersion <= (notifiedInputVersions.get(snap.id) ?? 0)
253
+ ) {
254
+ continue;
255
+ }
256
+ if (!sessionContext) continue;
257
+ pi.sendMessage(
258
+ {
259
+ customType: "subagent-input-required",
260
+ content: buildSubagentInputRequiredMessage({
261
+ id: snap.id,
262
+ title: snap.title,
263
+ message: snap.inputRequired,
264
+ herdrTabId: snap.meta.herdrTabId,
265
+ herdrPaneId: snap.meta.herdrPaneId,
266
+ }),
267
+ display: true,
268
+ details: {
269
+ id: snap.id,
270
+ title: snap.title,
271
+ status: snap.status,
272
+ herdrTabId: snap.meta.herdrTabId,
273
+ herdrPaneId: snap.meta.herdrPaneId,
274
+ },
275
+ },
276
+ { deliverAs: "steer", triggerTurn: true },
277
+ );
278
+ notifiedInputVersions.set(snap.id, snap.inputRequiredVersion);
279
+ ui?.notify(`Subagent “${snap.title}” needs input`, "warning");
280
+ }
281
+ };
282
+
283
+ const deliverResult = (snap: SubagentSnapshot) => {
284
+ pi.sendMessage(
285
+ {
286
+ customType: "subagent-result",
287
+ content: buildSubagentResultMessage({
288
+ id: snap.id,
289
+ title: snap.title,
290
+ status: snap.status,
291
+ errorText: snap.errorText,
292
+ output: truncatedOutput(snap),
293
+ herdrTabId: snap.meta.herdrTabId,
294
+ herdrPaneId: snap.meta.herdrPaneId,
295
+ }),
296
+ display: true,
297
+ details: {
298
+ id: snap.id,
299
+ title: snap.title,
300
+ status: snap.status,
301
+ herdrTabId: snap.meta.herdrTabId,
302
+ herdrPaneId: snap.meta.herdrPaneId,
303
+ },
304
+ },
305
+ { deliverAs: "followUp", triggerTurn: true },
306
+ );
307
+ };
308
+
309
+ const flushResults = () => {
310
+ resultDelivery.flush(deliverResult);
311
+ };
312
+
313
+ const deliverBtwResult = (snap: SubagentSnapshot) => {
314
+ // appendEntry is a synchronous SessionManager operation and emits an
315
+ // entry_appended event, so it is safe while the parent is streaming and
316
+ // never enters the model's context or follow-up queue.
317
+ pi.appendEntry<BtwResultData>("btw-result", {
318
+ id: snap.id,
319
+ title: snap.title,
320
+ status: snap.status,
321
+ errorText: snap.errorText,
322
+ prompt: snap.prompt,
323
+ answer: truncatedOutput(snap),
324
+ sessionFilePath: snap.meta.sessionFilePath,
325
+ });
326
+ ui?.notify(
327
+ snap.status === "error"
328
+ ? `by the way “${snap.title}” failed — reopen it with /subagents`
329
+ : `by the way “${snap.title}” answered — reopen it with /subagents`,
330
+ snap.status === "error" ? "error" : "info",
331
+ );
332
+ };
333
+
334
+ const onSettled = (snap: SubagentSnapshot, consumed: boolean) => {
335
+ // A shutdown can settle children while disposing their scopes. Never
336
+ // append into a session whose extension runtime is already closing.
337
+ if (!sessionContext) return;
338
+ if (snap.origin === "btw") {
339
+ deliverBtwResult({ ...snap, meta: { ...snap.meta } });
340
+ return;
341
+ }
342
+ if (consumed) {
343
+ resultDelivery.consume([snap.id]);
344
+ return;
345
+ }
346
+ // Keep the result retractable while the parent is working. A later
347
+ // subagent_wait can consume it before agent_settled flushes follow-ups.
348
+ // Defer a copy: the live snapshot keeps mutating if the subagent is
349
+ // restarted before the deferred result flushes.
350
+ resultDelivery.defer({ ...snap, meta: { ...snap.meta } });
351
+ if (sessionContext?.isIdle()) flushResults();
352
+ };
353
+
354
+ pi.on("session_start", (_event, ctx) => {
355
+ sessionContext = ctx;
356
+ if (ctx.hasUI) ui = ctx.ui;
357
+ });
358
+
359
+ pi.on("agent_settled", flushResults);
360
+
361
+ pi.on("session_shutdown", async () => {
362
+ sessionContext = undefined;
363
+ resultDelivery.clear();
364
+ notifiedInputVersions.clear();
365
+ unsubStatus?.();
366
+ unsubStatus = undefined;
367
+ ui?.setStatus("subagents", undefined);
368
+ ui = undefined;
369
+ const closing = runtime;
370
+ runtime = undefined;
371
+ managerPromise = undefined;
372
+ // Disposing the runtime runs the manager finalizer, which tears down all
373
+ // subagent scopes (and, later, their real child processes).
374
+ await closing?.dispose();
375
+ });
376
+
377
+ // --- Tools -------------------------------------------------------------
378
+
379
+ pi.registerTool({
380
+ name: "subagent_spawn",
381
+ label: "Spawn Subagent",
382
+ description: SUBAGENT_SPAWN_TOOL_DESCRIPTION,
383
+ promptSnippet: SUBAGENT_SPAWN_PROMPT_SNIPPET,
384
+ promptGuidelines: SUBAGENT_SPAWN_PROMPT_GUIDELINES,
385
+ parameters: Type.Object({
386
+ prompt: Type.String({
387
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.prompt,
388
+ }),
389
+ name: Type.String({
390
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.name,
391
+ }),
392
+ harness: StringEnum(BACKEND_NAMES, {
393
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.harness,
394
+ }),
395
+ working_dir: Type.Optional(
396
+ Type.String({
397
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.workingDir,
398
+ }),
399
+ ),
400
+ model: Type.Optional(
401
+ Type.String({
402
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.model,
403
+ }),
404
+ ),
405
+ reasoning_effort: Type.Optional(
406
+ StringEnum(REASONING_EFFORTS, {
407
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.reasoningEffort,
408
+ }),
409
+ ),
410
+ mode: Type.Optional(
411
+ StringEnum(SUBAGENT_MODES, {
412
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.mode,
413
+ }),
414
+ ),
415
+ }),
416
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
417
+ const manager = await getManager();
418
+ const harness = params.harness;
419
+ if (params.mode === "plan" && harness !== "claude") {
420
+ throw new Error('mode "plan" is currently supported only by Claude.');
421
+ }
422
+
423
+ const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
424
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
425
+ throw new Error(`working_dir is not a directory: ${cwd}`);
426
+ }
427
+
428
+ const title = params.name.trim().slice(0, 160) || "subagent";
429
+ const snap = await runTool(
430
+ getRuntime(),
431
+ manager.spawn(harness, {
432
+ prompt: params.prompt,
433
+ title,
434
+ cwd,
435
+ model: params.model,
436
+ reasoningEffort: params.reasoning_effort,
437
+ mode: params.mode,
438
+ parent: {
439
+ parentCwd: ctx.cwd,
440
+ projectTrusted: resolveChildProjectTrust({
441
+ parentCwd: ctx.cwd,
442
+ childCwd: cwd,
443
+ parentTrusted: ctx.isProjectTrusted(),
444
+ }),
445
+ inheritedModel: ctx.model
446
+ ? { provider: ctx.model.provider, id: ctx.model.id }
447
+ : undefined,
448
+ inheritedThinkingLevel: pi.getThinkingLevel(),
449
+ modelRegistry: ctx.modelRegistry,
450
+ },
451
+ }),
452
+ { signal, interruptMessage: "Subagent spawn aborted." },
453
+ );
454
+
455
+ return {
456
+ content: [
457
+ {
458
+ type: "text",
459
+ text: buildSubagentSpawnResult({
460
+ id: snap.id,
461
+ title: snap.title,
462
+ harness,
463
+ modelLabel: snap.meta.modelLabel ?? "?",
464
+ cwd,
465
+ herdrTabId: snap.meta.herdrTabId,
466
+ herdrPaneId: snap.meta.herdrPaneId,
467
+ }),
468
+ },
469
+ ],
470
+ details: {
471
+ id: snap.id,
472
+ title: snap.title,
473
+ cwd,
474
+ harness,
475
+ model: snap.meta.modelLabel,
476
+ mode: params.mode ?? "default",
477
+ herdrTabId: snap.meta.herdrTabId,
478
+ herdrPaneId: snap.meta.herdrPaneId,
479
+ herdrAgentName: snap.meta.herdrAgentName,
480
+ },
481
+ };
482
+ },
483
+ });
484
+
485
+ pi.registerTool({
486
+ name: "subagent_wait",
487
+ label: "Wait for Subagents",
488
+ description: SUBAGENT_WAIT_TOOL_DESCRIPTION,
489
+ parameters: Type.Object({
490
+ ids: Type.Array(Type.String(), {
491
+ maxItems: 64,
492
+ description: SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS.ids,
493
+ }),
494
+ }),
495
+ async execute(_toolCallId, params, signal, onUpdate) {
496
+ const manager = await getManager();
497
+ const ids = [...new Set(params.ids)];
498
+ if (ids.length === 0)
499
+ throw new Error("Provide at least one subagent id.");
500
+ const known = manager.view
501
+ .list()
502
+ .filter(isModelVisible)
503
+ .map((snap) => snap.id);
504
+ const unknown = ids.filter((id) => {
505
+ const snap = manager.view.get(id);
506
+ return !snap || !isModelVisible(snap);
507
+ });
508
+ if (unknown.length > 0) {
509
+ throw new Error(
510
+ `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
511
+ );
512
+ }
513
+
514
+ await runTool(
515
+ getRuntime(),
516
+ manager.waitFor(ids, (pending) => {
517
+ onUpdate?.({
518
+ content: [
519
+ { type: "text", text: `Waiting for ${pending.join(", ")}...` },
520
+ ],
521
+ details: { pending },
522
+ });
523
+ }),
524
+ { signal, interruptMessage: "Wait aborted. Subagents keep running." },
525
+ );
526
+
527
+ // Settlement may have happened before this wait began. Remove any
528
+ // deferred automatic delivery now that the tool is returning the result.
529
+ resultDelivery.consume(ids);
530
+
531
+ const sections: string[] = [];
532
+ let remainingBytes = WAIT_OUTPUT_MAX_BYTES;
533
+ for (const id of ids) {
534
+ const snap = manager.view.get(id);
535
+ if (!snap) {
536
+ sections.push(`## ${id}\n\n(no longer tracked)`);
537
+ continue;
538
+ }
539
+ const section = formatWaitSection(snap, remainingBytes);
540
+ const sectionBytes = Buffer.byteLength(section, "utf8");
541
+ if (sectionBytes > remainingBytes) {
542
+ sections.push(
543
+ `## ${snap.id} "${snap.title}"\n\n[omitted: total wait output limit reached]`,
544
+ );
545
+ break;
546
+ }
547
+ sections.push(section);
548
+ remainingBytes -= sectionBytes;
549
+ }
550
+
551
+ const combined = sections.join("\n\n---\n\n");
552
+ const bounded = truncateHead(combined, {
553
+ maxBytes: WAIT_OUTPUT_MAX_BYTES - 128,
554
+ maxLines: DEFAULT_MAX_LINES,
555
+ });
556
+ const text = bounded.truncated
557
+ ? `${bounded.content}\n\n[wait output truncated at the total output limit]`
558
+ : bounded.content;
559
+ return {
560
+ content: [{ type: "text", text }],
561
+ details: {
562
+ results: ids.map((id) => {
563
+ const snap = manager.view.get(id);
564
+ return {
565
+ id,
566
+ title: snap?.title,
567
+ status: snap?.status,
568
+ inputRequired: snap?.inputRequired,
569
+ herdrTabId: snap?.meta.herdrTabId,
570
+ herdrPaneId: snap?.meta.herdrPaneId,
571
+ };
572
+ }),
573
+ },
574
+ };
575
+ },
576
+ });
577
+
578
+ pi.registerTool({
579
+ name: "subagent_send",
580
+ label: "Send to Subagent",
581
+ description: SUBAGENT_SEND_TOOL_DESCRIPTION,
582
+ parameters: Type.Object({
583
+ id: Type.String({
584
+ description: SUBAGENT_SEND_PARAMETER_DESCRIPTIONS.id,
585
+ }),
586
+ message: Type.String({
587
+ description: SUBAGENT_SEND_PARAMETER_DESCRIPTIONS.message,
588
+ }),
589
+ }),
590
+ async execute(_toolCallId, params, signal) {
591
+ const manager = await getManager();
592
+ const snap = manager.view.get(params.id);
593
+ if (!snap || !isModelVisible(snap)) {
594
+ const known = manager.view
595
+ .list()
596
+ .filter(isModelVisible)
597
+ .map((entry) => entry.id);
598
+ throw new Error(
599
+ `Unknown subagent id "${params.id}". Known: ${known.join(", ") || "none"}.`,
600
+ );
601
+ }
602
+ const message = params.message.trim();
603
+ if (!message) throw new Error("Follow-up message cannot be empty.");
604
+
605
+ const action = snap.status === "running" ? "Steered" : "Continued";
606
+ const previousResult = resultDelivery.peek(params.id);
607
+ await runTool(getRuntime(), manager.send(params.id, message), {
608
+ signal,
609
+ interruptMessage:
610
+ "Subagent follow-up submission aborted; inspect the existing session before retrying.",
611
+ });
612
+ // A very fast new turn may already have settled during send().
613
+ // Retract only the previous result, never that new completion.
614
+ resultDelivery.consume(
615
+ [params.id],
616
+ (result) => result === previousResult,
617
+ );
618
+ const updated = manager.view.get(params.id);
619
+ return {
620
+ content: [
621
+ {
622
+ type: "text",
623
+ text: `${action} ${params.id} "${snap.title}" in the same session.`,
624
+ },
625
+ ],
626
+ details: {
627
+ id: params.id,
628
+ title: snap.title,
629
+ status: updated?.status,
630
+ herdrTabId: updated?.meta.herdrTabId,
631
+ herdrPaneId: updated?.meta.herdrPaneId,
632
+ },
633
+ };
634
+ },
635
+ });
636
+
637
+ pi.registerTool({
638
+ name: "subagent_cancel",
639
+ label: "Cancel Subagents",
640
+ description: SUBAGENT_CANCEL_TOOL_DESCRIPTION,
641
+ parameters: Type.Object({
642
+ ids: Type.Array(Type.String(), {
643
+ description: SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS.ids,
644
+ }),
645
+ }),
646
+ async execute(_toolCallId, params, signal) {
647
+ const manager = await getManager();
648
+ const ids = [...new Set(params.ids)];
649
+ if (ids.length === 0)
650
+ throw new Error("Provide at least one subagent id.");
651
+
652
+ const known = manager.view
653
+ .list()
654
+ .filter(isModelVisible)
655
+ .map((snap) => snap.id);
656
+ const unknown = ids.filter((id) => {
657
+ const snap = manager.view.get(id);
658
+ return !snap || !isModelVisible(snap);
659
+ });
660
+ if (unknown.length > 0) {
661
+ throw new Error(
662
+ `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
663
+ );
664
+ }
665
+
666
+ const report = await runTool(getRuntime(), manager.cancel(ids), {
667
+ signal,
668
+ interruptMessage: "Subagent cancellation aborted.",
669
+ });
670
+
671
+ const lines = report.map((entry) =>
672
+ entry.cancelled
673
+ ? `Cancelled ${entry.id} "${entry.title}".`
674
+ : `${entry.id} "${entry.title}" was already ${entry.status}.`,
675
+ );
676
+
677
+ return {
678
+ content: [{ type: "text", text: lines.join("\n") }],
679
+ details: {
680
+ results: report.map((entry) => ({
681
+ id: entry.id,
682
+ title: entry.title,
683
+ status: entry.status,
684
+ })),
685
+ },
686
+ };
687
+ },
688
+ });
689
+
690
+ pi.registerTool({
691
+ name: "subagent_check",
692
+ label: "Check Subagent",
693
+ description: SUBAGENT_CHECK_TOOL_DESCRIPTION,
694
+ parameters: Type.Object({
695
+ id: Type.String({
696
+ description: SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS.id,
697
+ }),
698
+ }),
699
+ async execute(_toolCallId, params) {
700
+ const manager = await getManager();
701
+ const snap = manager.view.get(params.id);
702
+ if (!snap || !isModelVisible(snap)) {
703
+ const known = manager.view
704
+ .list()
705
+ .filter(isModelVisible)
706
+ .map((s) => s.id);
707
+ throw new Error(
708
+ `Unknown subagent id "${params.id}". Known: ${known.join(", ") || "none"}.`,
709
+ );
710
+ }
711
+
712
+ let text = `${describeSubagent(snap)}\nTurns: ${snap.turns}`;
713
+ if (snap.errorText) text += `\nError: ${snap.errorText}`;
714
+ if (snap.inputRequired) {
715
+ text += `\nInput required: ${snap.inputRequired}`;
716
+ }
717
+
718
+ const output = latestText(snap);
719
+ if (output) {
720
+ const preview = truncateHead(output, { maxBytes: 2048, maxLines: 20 });
721
+ text += `\n\nLatest output:\n${preview.content}`;
722
+ if (preview.truncated) text += "\n[...]";
723
+ } else if (snap.status === "running") {
724
+ text += "\n\n(no text output yet)";
725
+ }
726
+ if (snap.status !== "running") {
727
+ const cleanup = buildTerminalCleanupReminder({
728
+ herdrTabId: snap.meta.herdrTabId,
729
+ herdrPaneId: snap.meta.herdrPaneId,
730
+ });
731
+ if (cleanup) text += `\n\n${cleanup}`;
732
+ }
733
+
734
+ return {
735
+ content: [{ type: "text", text }],
736
+ details: {
737
+ id: snap.id,
738
+ status: snap.status,
739
+ turns: snap.turns,
740
+ inputRequired: snap.inputRequired,
741
+ herdrTabId: snap.meta.herdrTabId,
742
+ herdrPaneId: snap.meta.herdrPaneId,
743
+ },
744
+ };
745
+ },
746
+ });
747
+
748
+ pi.registerTool({
749
+ name: "subagent_list",
750
+ label: "List Subagents",
751
+ description: SUBAGENT_LIST_TOOL_DESCRIPTION,
752
+ parameters: Type.Object({}),
753
+ async execute() {
754
+ const manager = await getManager();
755
+ const subs = manager.view.list().filter(isModelVisible);
756
+ const text =
757
+ subs.length === 0
758
+ ? "No subagents."
759
+ : subs.map((snap) => describeSubagent(snap)).join("\n");
760
+ return {
761
+ content: [{ type: "text", text }],
762
+ details: {
763
+ subagents: subs.map((snap) => ({
764
+ id: snap.id,
765
+ title: snap.title,
766
+ harness: snap.backend,
767
+ status: snap.status,
768
+ inputRequired: snap.inputRequired,
769
+ herdrTabId: snap.meta.herdrTabId,
770
+ herdrPaneId: snap.meta.herdrPaneId,
771
+ })),
772
+ },
773
+ };
774
+ },
775
+ });
776
+
777
+ // --- Result message rendering ------------------------------------------
778
+
779
+ pi.registerMessageRenderer(
780
+ "subagent-result",
781
+ (message, { expanded }, theme) => {
782
+ const details = (message.details ?? {}) as {
783
+ id?: string;
784
+ title?: string;
785
+ status?: string;
786
+ };
787
+ const failed = details.status === "error";
788
+ const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
789
+ const header =
790
+ `${icon} ` +
791
+ theme.fg("accent", theme.bold(`subagent ${details.id ?? "?"}`)) +
792
+ theme.fg(
793
+ "muted",
794
+ ` · ${details.title ?? ""} · ${failed ? "failed" : "finished"}`,
795
+ );
796
+
797
+ const content =
798
+ typeof message.content === "string" ? message.content : "";
799
+ // Remove only the summary line. The following Error line (when present)
800
+ // is part of the actual result and must remain visible.
801
+ const body = content.split("\n").slice(1).join("\n").trim();
802
+
803
+ if (expanded) {
804
+ const md = new Markdown(`${body}`, 0, 0, getMarkdownTheme());
805
+ const container = new Text(header, 0, 0);
806
+ return {
807
+ render: (width: number) => [
808
+ ...container.render(width),
809
+ ...md.render(width),
810
+ ],
811
+ invalidate: () => {
812
+ container.invalidate();
813
+ md.invalidate();
814
+ },
815
+ };
816
+ }
817
+
818
+ const previewLines = body.split("\n").slice(0, 8);
819
+ let text = header;
820
+ for (const line of previewLines)
821
+ text += `\n${theme.fg("toolOutput", line)}`;
822
+ if (body.split("\n").length > 8)
823
+ text += `\n${theme.fg("dim", "... (ctrl+o to expand)")}`;
824
+ return new Text(text, 0, 0);
825
+ },
826
+ );
827
+
828
+ pi.registerEntryRenderer<BtwResultData>(
829
+ "btw-result",
830
+ (entry, { expanded }, theme) => {
831
+ const data = entry.data;
832
+ const failed = data?.status === "error";
833
+ const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
834
+ const header =
835
+ `${icon} ` +
836
+ theme.fg("accent", theme.bold(`by the way · ${data?.title ?? "?"}`)) +
837
+ theme.fg(
838
+ "muted",
839
+ ` · ${failed ? "failed" : "answered"} · ${data?.id ?? "?"}`,
840
+ );
841
+ const body = [
842
+ data?.errorText ? `Error: ${data.errorText}` : "",
843
+ data?.answer ?? "(no answer)",
844
+ ]
845
+ .filter(Boolean)
846
+ .join("\n\n");
847
+
848
+ if (expanded) {
849
+ const md = new Markdown(body, 0, 0, getMarkdownTheme());
850
+ const container = new Text(header, 0, 0);
851
+ return {
852
+ render: (width: number) => [
853
+ ...container.render(width),
854
+ ...md.render(width),
855
+ ],
856
+ invalidate: () => {
857
+ container.invalidate();
858
+ md.invalidate();
859
+ },
860
+ };
861
+ }
862
+
863
+ const lines = body.split("\n");
864
+ let text = header;
865
+ for (const line of lines.slice(0, 8))
866
+ text += `\n${theme.fg("toolOutput", line)}`;
867
+ if (lines.length > 8)
868
+ text += `\n${theme.fg("dim", "... (ctrl+o to expand)")}`;
869
+ return new Text(text, 0, 0);
870
+ },
871
+ );
872
+
873
+ // --- Commands -----------------------------------------------------------
874
+
875
+ const runByTheWay = async (rawArgs: string, ctx: ExtensionCommandContext) => {
876
+ if (ctx.mode !== "tui") {
877
+ if (ctx.hasUI)
878
+ ctx.ui.notify("by the way is only available in the TUI", "error");
879
+ return;
880
+ }
881
+
882
+ let prompt = rawArgs.trim();
883
+ if (!prompt) {
884
+ const input = await ctx.ui.input("by the way", "Ask a one-off question…");
885
+ prompt = input?.trim() ?? "";
886
+ if (!prompt) return;
887
+ }
888
+
889
+ const manager = await getManager();
890
+ let snap: SubagentSnapshot;
891
+ try {
892
+ snap = await runTool(
893
+ getRuntime(),
894
+ manager.spawn("pi", {
895
+ origin: "btw",
896
+ prompt,
897
+ title: deriveBtwTitle(prompt),
898
+ cwd: ctx.cwd,
899
+ parent: {
900
+ parentCwd: ctx.cwd,
901
+ projectTrusted: ctx.isProjectTrusted(),
902
+ inheritedModel: ctx.model
903
+ ? { provider: ctx.model.provider, id: ctx.model.id }
904
+ : undefined,
905
+ inheritedThinkingLevel: pi.getThinkingLevel(),
906
+ modelRegistry: ctx.modelRegistry,
907
+ },
908
+ }),
909
+ );
910
+ } catch (error) {
911
+ ctx.ui.notify(
912
+ error instanceof Error ? error.message : String(error),
913
+ "error",
914
+ );
915
+ return;
916
+ }
917
+
918
+ await openSubagentTakeover(ctx, manager.view, snap.id, {
919
+ badge: "by the way",
920
+ });
921
+ };
922
+
923
+ pi.registerCommand("btw", {
924
+ description:
925
+ "Ask a one-off side question while the main agent keeps working",
926
+ handler: runByTheWay,
927
+ });
928
+
929
+ pi.registerCommand("subagents", {
930
+ description: "List, inspect, and take over subagents",
931
+ handler: async (_args, ctx) => {
932
+ if (ctx.mode !== "tui") {
933
+ if (ctx.hasUI)
934
+ ctx.ui.notify(
935
+ "Subagent takeover is only available in the TUI",
936
+ "error",
937
+ );
938
+ return;
939
+ }
940
+ const manager = await getManager();
941
+ if (manager.view.size() === 0) {
942
+ ctx.ui.notify(
943
+ "No subagents yet. The agent spawns them with subagent_spawn.",
944
+ "info",
945
+ );
946
+ return;
947
+ }
948
+ await openSubagentPicker(ctx, manager.view);
949
+ },
950
+ });
951
+ }