@ferris1225/pi-subagents 0.32.2 → 1.0.0

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 CHANGED
@@ -1,748 +1,730 @@
1
- /**
2
- * Thread controls and lookup tools around the subagent runtime:
3
- * subagent_control (steer/retarget/park/resume), subagent_wait (in-turn result
4
- * lookup), subagent_status, and destructive subagent_stop.
5
- */
6
-
7
- import { StringEnum } from "@earendil-works/pi-ai";
8
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
9
- import { Text } from "@earendil-works/pi-tui";
10
- import { Type } from "typebox";
11
- import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "./config.ts";
12
- import { emptyUsage, formatCompletionBlock, formatUsage, matchRunIds } from "./format.ts";
13
- import {
14
- formatElapsed,
15
- formatUsageCompact,
16
- isRunActiveStatus,
17
- monitor,
18
- runLabel,
19
- statusLabel,
20
- type RunStatus,
21
- } from "./monitor.ts";
22
- import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
23
- import { getResultOutput, isFailedResult, type SingleResult } from "./spawn.ts";
24
- import { inspectorStore } from "./trajectory.ts";
25
-
26
- /** In-turn result lookup. Dispatch already ended the turn and results arrive as
27
- * wake-up messages, so the default must NOT block: a settled run returns its
28
- * result immediately, a still-active run returns a "still running — end your
29
- * turn" note and the model finishes (the completion then wakes it). Blocking
30
- * is opt-in via an explicit timeoutMs — a long default would hold the turn
31
- * hostage for nothing, since the result arrives on its own either way. */
32
- const SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS = 0;
33
-
34
- function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
35
- const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
36
- const text = parts
37
- .map((part) => (typeof part.text === "string" ? part.text : ""))
38
- .join(" ")
39
- .trim();
40
- const firstLine = text.split("\n").find((line) => line.trim()) ?? "(no output)";
41
- return new Text(`${theme.fg("toolTitle", theme.bold(label))}${theme.fg("dim", firstLine.slice(0, 60))}`, 0, 0);
42
- }
43
-
44
- export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime): void {
45
- const SubagentControlParams = Type.Object({
46
- action: StringEnum(["steer", "retarget", "park", "resume", "fork"] as const, {
47
- description: "Control operation for the logical sub-agent thread.",
48
- }),
49
- id: Type.Integer({ minimum: 1, description: "Stable run id shown in the subagent widget/status output." }),
50
- instruction: Type.Optional(
51
- Type.String({ description: "Instruction queued by steer after the current child tool batch." }),
52
- ),
53
- objective: Type.Optional(
54
- Type.String({ description: "Replacement objective for retarget, or optional objective for resume/fork." }),
55
- ),
56
- });
57
-
58
- pi.registerTool({
59
- name: "subagent_control",
60
- label: "Subagent Control",
61
- description: [
62
- "Control an existing sub-agent thread by stable run id.",
63
- "steer queues an instruction after the current child tool batch.",
64
- "retarget aborts the current objective to a stable checkpoint, suppresses that aborted completion, then starts the replacement objective in the same session.",
65
- "park aborts to a stable checkpoint, terminates the child, preserves context, and releases its concurrency slot.",
66
- "resume restarts a parked, completed, or failed retained thread with the same run id; objective is optional.",
67
- "fork copies a parked/completed/failed retained session branch into a new logical thread and run id; an isolated checkpoint must be settled and integrated first; objective is optional.",
68
- ].join(" "),
69
- promptSnippet: "Control a subagent thread: steer, retarget, park, resume, or fork by stable run id.",
70
- promptGuidelines: [
71
- "Use subagent_control steer to refine active work without restarting it; the instruction is delivered after the child's current tool batch.",
72
- "Use subagent_control retarget when the active objective is obsolete; do not call subagent_stop and start a fresh thread because retarget preserves context and suppresses the abandoned completion.",
73
- "Use subagent_control park to checkpoint useful context while releasing the process/concurrency slot, and resume to continue the same run id later.",
74
- "Use subagent_control fork only on a parked or settled retained thread; isolated work must settle and integrate before it can fork. Fork creates a new run id while leaving the source untouched.",
75
- "Use subagent_stop only for destructive cancellation; it retires that thread's retained session without retiring independent forks.",
76
- ],
77
- parameters: SubagentControlParams,
78
-
79
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
80
- const thread = runtime.threads.get(params.id);
81
- if (!thread) {
82
- return { content: [{ type: "text", text: `No subagent thread matches run #${params.id}.` }], details: {} };
83
- }
84
- const nonBlank = (value: string | undefined): string | undefined => {
85
- const trimmed = value?.trim();
86
- return trimmed ? trimmed : undefined;
87
- };
88
-
89
- try {
90
- switch (params.action) {
91
- case "steer": {
92
- const instruction = nonBlank(params.instruction);
93
- if (!instruction) {
94
- return { content: [{ type: "text", text: "steer requires a non-blank instruction." }], details: {} };
95
- }
96
- if (!(["running", "steering"] as const).includes(thread.control.getPhase() as any)) {
97
- return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.control.getPhase()}; only a running thread can be steered.` }], details: {} };
98
- }
99
- await thread.control.steer(instruction);
100
- inspectorStore.get(thread.id).trajectory.append({ kind: "steer", instruction });
101
- return { content: [{ type: "text", text: `Queued steering instruction for run #${thread.id} after its current tool batch.` }], details: {} };
102
- }
103
- case "retarget": {
104
- const objective = nonBlank(params.objective);
105
- if (!objective) {
106
- return { content: [{ type: "text", text: "retarget requires a non-blank objective." }], details: {} };
107
- }
108
- const phase = thread.control.getPhase();
109
- if (thread.state === "queued" && phase === "queued") {
110
- thread.task = objective;
111
- thread.control.retargetPending(objective);
112
- monitor.setTask(thread.id, objective);
113
- inspectorStore.get(thread.id).trajectory.append({ kind: "retarget", objective });
114
- return { content: [{ type: "text", text: `Updated queued run #${thread.id} to the new objective; no child was spawned by this control action.` }], details: {} };
115
- }
116
- if (!(["starting", "running", "steering", "interrupting", "retrying"] as const).includes(phase as any)) {
117
- return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.state}; use resume with objective to restart retained context.` }], details: {} };
118
- }
119
- thread.task = objective;
120
- monitor.setTask(thread.id, objective);
121
- await thread.control.retarget(objective);
122
- inspectorStore.get(thread.id).trajectory.append({ kind: "retarget", objective });
123
- return { content: [{ type: "text", text: `Retargeted run #${thread.id} in the same session; the aborted objective will not be delivered as a completion.` }], details: {} };
124
- }
125
- case "park": {
126
- if (thread.state === "parked") {
127
- return { content: [{ type: "text", text: `Run #${thread.id} is already parked.` }], details: {} };
128
- }
129
- const disposition = await thread.park();
130
- return disposition === "queued"
131
- ? {
132
- content: [{ type: "text", text: `Parked queued run #${thread.id}; it never spawned a child or empty session.` }],
133
- details: {},
134
- }
135
- : {
136
- content: [{ type: "text", text: `Parked run #${thread.id} at a stable checkpoint; its session is retained and concurrency slot released.` }],
137
- details: {},
138
- };
139
- }
140
- case "resume": {
141
- if (thread.retired) {
142
- return { content: [{ type: "text", text: `Run #${thread.id} was retired by subagent_stop and has no resumable session.` }], details: {} };
143
- }
144
- if (!(["parked", "completed", "failed"] as const).includes(thread.state as any)) {
145
- return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.state}; it must be parked or settled before resume.` }], details: {} };
146
- }
147
- const objective = params.objective === undefined ? undefined : nonBlank(params.objective);
148
- if (params.objective !== undefined && !objective) {
149
- return { content: [{ type: "text", text: "resume objective must be non-blank when provided." }], details: {} };
150
- }
151
- const pending = await thread.resume(objective, ctx);
152
- if (pending.exitCode !== -1) {
153
- return { content: [{ type: "text", text: getResultOutput(pending) }], details: {} };
154
- }
155
- return { content: [{ type: "text", text: `Resumed run #${thread.id}${objective ? " with a new objective" : " from retained context"}; completion will arrive automatically.` }], details: {}, terminate: true };
156
- }
157
- case "fork": {
158
- const objective = params.objective === undefined ? undefined : nonBlank(params.objective);
159
- if (params.objective !== undefined && !objective) {
160
- return { content: [{ type: "text", text: "fork objective must be non-blank when provided." }], details: {} };
161
- }
162
- const pending = await thread.fork(objective, ctx);
163
- if (pending.exitCode !== -1 || pending.runId === undefined) {
164
- return { content: [{ type: "text", text: getResultOutput(pending) }], details: {} };
165
- }
166
- return {
167
- content: [{
168
- type: "text",
169
- text: `Forked run #${thread.id} into new run #${pending.runId}${objective ? " with a new objective" : " from retained context"}; the source is unchanged and child completion will arrive automatically.`,
170
- }],
171
- details: { sourceRunId: thread.id, childRunId: pending.runId, result: pending },
172
- terminate: true,
173
- };
174
- }
175
- }
176
- } catch (error) {
177
- throw new Error(`Could not ${params.action} run #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
178
- }
179
- },
180
-
181
- renderCall(args, theme) {
182
- return new Text(`${theme.fg("toolTitle", theme.bold("subagent_control "))}${theme.fg("accent", `${args.action} #${args.id}`)}`, 0, 0);
183
- },
184
- renderResult(result, _options, theme) {
185
- return renderFirstLine(result, "subagent_control ", theme);
186
- },
187
- });
188
-
189
- const SubagentWaitParams = Type.Object({
190
- id: Type.Optional(
191
- Type.String({
192
- description: "Run id or prefix shown in the subagent widget (#id). Omit to wait for all active runs in this session.",
193
- }),
194
- ),
195
- timeoutMs: Type.Optional(
196
- Type.Number({
197
- description: `Block for up to this many milliseconds and report the still-running runs. Default ${SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS}: no blocking — settled runs return their result immediately, active runs return a note telling the model to end its turn.`,
198
- }),
199
- ),
200
- });
201
-
202
- pi.registerTool({
203
- name: "subagent_wait",
204
- label: "Subagent Wait",
205
- description: [
206
- "Look up background sub-agent run(s) and return their results.",
207
- "PREFER NOT CALLING THIS: dispatching already ended your turn and results arrive as a message that wakes you automatically.",
208
- "By default it does NOT block: a settled run returns its result immediately; a still-active run returns a 'still running — end your turn' note.",
209
- "Pass an explicit timeoutMs ONLY when you must stay in the turn and need the result right now (sequential dependent steps).",
210
- "NEVER sleep, poll, or wait with bash to get a sub-agent result: end the turn, or call this tool.",
211
- "The same result is also delivered as a completion message that resumes the main agent, so you may see it twice (once here, once as a wake-up) — that is expected, not a duplicate.",
212
- ].join(" "),
213
- promptSnippet: "Look up a background subagent result in-turn (id: run id from the widget; omit for all). Non-blocking by default; pass timeoutMs to block.",
214
- promptGuidelines: [
215
- "Do NOT call subagent_wait to hold the turn: results arrive as wake-up messages automatically. The default call is a non-blocking lookup — settled results return immediately, active runs return a note telling you to end your turn.",
216
- "Pass an explicit timeoutMs only when you must keep the turn AND the next step depends on the result right now — e.g. the user asked you to wait for it.",
217
- "Never use bash sleep/timeout/polling to wait for a sub-agent — it blocks the turn and delays result delivery.",
218
- "If subagent_wait times out, end the turn and wait for the wake-up message, or call it again with a longer timeoutMs.",
219
- ],
220
- parameters: SubagentWaitParams,
221
-
222
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
223
- const config = await loadConfig(runtime.configPath);
224
- // A non-finite or negative timeout would produce a nonsensical note
225
- // ("timed out after Infinitys") or an instant "timeout" that was never
226
- // asked for; fall back to the default. Zero is honored as an immediate
227
- // give-up (clamped to 1ms below).
228
- const timeoutMs =
229
- typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs >= 0
230
- ? params.timeoutMs
231
- : SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS;
232
- const isActive = (run: { status: RunStatus; retained?: boolean }): boolean =>
233
- isRunActiveStatus(run.status) || run.retained === true;
234
-
235
- const requested = params.id?.trim();
236
- // A run that already settled resolves immediately with its result.
237
- if (requested) {
238
- const settledIds = matchRunIds([...runtime.settledRuns.keys()], requested);
239
- if (settledIds.length > 0) {
240
- return {
241
- content: [
242
- { type: "text", text: settledIds.map((id) => formatCompletionBlock(runtime.settledRuns.get(id)!, config.maxResultLines, ctx.cwd)).join("\n\n") },
243
- ],
244
- details: {},
245
- };
246
- }
247
- }
248
-
249
- const activeRuns = monitor.getRuns().filter(isActive);
250
- const targetIds = requested ? matchRunIds(activeRuns.map((run) => run.id), requested) : activeRuns.map((run) => run.id);
251
- const targets = activeRuns.filter((run) => targetIds.includes(run.id));
252
- if (targets.length === 0) {
253
- const activeList = activeRuns.map((run) => `#${run.id} ${run.agent}`).join(", ");
254
- return {
255
- content: [
256
- {
257
- type: "text",
258
- text: requested
259
- ? `No active subagent run matches "${requested}".${activeList ? ` Active runs: ${activeList}.` : ""}`
260
- : `No active subagent runs${activeList ? ` (active: ${activeList})` : " right now"}.`,
261
- },
262
- ],
263
- details: {},
264
- };
265
- }
266
-
267
- const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
268
- const already = runtime.settledRuns.get(runId);
269
- if (already) return Promise.resolve({ result: already });
270
- return new Promise((resolve) => {
271
- let done = false;
272
- let timer: ReturnType<typeof setTimeout> | undefined;
273
- let unsub: (() => void) | undefined;
274
- const cleanup = (): void => {
275
- if (timer) clearTimeout(timer);
276
- if (unsub) unsub();
277
- signal?.removeEventListener("abort", onAbort);
278
- const listeners = runtime.settledListeners.get(runId);
279
- if (listeners) {
280
- listeners.delete(onSettled);
281
- if (listeners.size === 0) runtime.settledListeners.delete(runId);
282
- }
283
- };
284
- const finish = (outcome: { result?: SingleResult; note?: string }): void => {
285
- if (done) return;
286
- done = true;
287
- cleanup();
288
- resolve(outcome);
289
- };
290
- const onSettled = (result: SingleResult): void => finish({ result });
291
- const onMonitor = (): void => {
292
- const current = runtime.settledRuns.get(runId);
293
- if (current) {
294
- finish({ result: current });
295
- return;
296
- }
297
- const live = monitor.findRun(runId);
298
- if (live?.status === "parked") {
299
- finish({ note: `run #${runId} was parked at a stable checkpoint; use subagent_control resume to continue it` });
300
- return;
301
- }
302
- if (!live) {
303
- // Removal is followed synchronously by registerRunResult in the
304
- // finishing task; re-check on the next tick so the result wins.
305
- setTimeout(() => {
306
- const late = runtime.settledRuns.get(runId);
307
- if (late) finish({ result: late });
308
- else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
309
- }, 0);
310
- }
311
- };
312
- const onAbort = (): void => finish({ note: "wait aborted" });
313
- let listeners = runtime.settledListeners.get(runId);
314
- if (!listeners) {
315
- listeners = new Set();
316
- runtime.settledListeners.set(runId, listeners);
317
- }
318
- listeners.add(onSettled);
319
- unsub = monitor.subscribe(onMonitor);
320
- timer = setTimeout(
321
- () =>
322
- finish({
323
- note:
324
- timeoutMs === 0
325
- ? `run #${runId} is still active — end your turn: the result will wake you (or call subagent_wait again with an explicit timeoutMs to block)`
326
- : `wait timed out after ${Math.round(timeoutMs / 1000)}s — run #${runId} is still active; call subagent_wait again or end the turn (the result will wake you when ready)`,
327
- }),
328
- Math.max(1, timeoutMs),
329
- );
330
- if (signal?.aborted) onAbort();
331
- else signal?.addEventListener("abort", onAbort, { once: true });
332
- });
333
- };
334
-
335
- const outcomes = await Promise.all(targets.map((run) => waitForRun(run.id)));
336
- const blocks = outcomes.map((outcome) =>
337
- outcome.result ? formatCompletionBlock(outcome.result, config.maxResultLines, ctx.cwd) : (outcome.note ?? "(no outcome)"),
338
- );
339
- return { content: [{ type: "text", text: blocks.join("\n\n") }], details: {} };
340
- },
341
-
342
- renderCall(args, theme) {
343
- const target = args.id ? `#${args.id}` : "all";
344
- return new Text(`${theme.fg("toolTitle", theme.bold("subagent_wait "))}${theme.fg("accent", target)}`, 0, 0);
345
- },
346
-
347
- renderResult(result, _options, theme) {
348
- return renderFirstLine(result, "subagent_wait ", theme);
349
- },
350
- });
351
-
352
- // Status overview: what is running right now and what finished this session,
353
- // with per-run details (id, agent, model, usage, elapsed, activity) so the
354
- // main agent can decide whether to wait, stop, or re-dispatch. Learned from
355
- // nicobailon/pi-subagents ({action:"status"} + status files): inspect before
356
- // you act, and report run ids when handing off.
357
- const SubagentStatusParams = Type.Object({
358
- id: Type.Optional(
359
- Type.String({
360
- description: "Run id or prefix to show the full result for (must already be finished; use subagent_wait to block on an active run).",
361
- }),
362
- ),
363
- });
364
-
365
- pi.registerTool({
366
- name: "subagent_status",
367
- label: "Subagent Status",
368
- description: [
369
- "List active background sub-agent runs (id, agent, model, usage, elapsed, current activity) and recently finished results.",
370
- "Pass id to read the full result of a finished run; pass no id for the overview.",
371
- "Use it to decide whether to subagent_wait, subagent_stop, or re-dispatch — never to poll: results arrive by themselves.",
372
- ].join(" "),
373
- promptSnippet: "Inspect background subagents: active runs, finished results, full result by id.",
374
- promptGuidelines: [
375
- "Call subagent_status to see what is running and what already finished; the widget shows the same live state.",
376
- "Never poll subagent_status in a loop to wait for a run: end the turn (you will be woken) or call subagent_wait.",
377
- "A finished run's id stays available for the session; its full result is one subagent_status call away.",
378
- ],
379
- parameters: SubagentStatusParams,
380
-
381
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
382
- const config = await loadConfig(runtime.configPath);
383
- const requested = params.id?.trim();
384
-
385
- if (requested) {
386
- const settledIds = matchRunIds([...runtime.settledRuns.keys()], requested);
387
- if (settledIds.length > 0) {
388
- return {
389
- content: [
390
- { type: "text", text: settledIds.map((id) => formatCompletionBlock(runtime.settledRuns.get(id)!, config.maxResultLines, ctx.cwd)).join("\n\n") },
391
- ],
392
- details: {},
393
- };
394
- }
395
- const runs = monitor.getRuns();
396
- const activeId = matchRunIds(runs.map((run) => run.id), requested)[0];
397
- const active = activeId === undefined ? undefined : runs.find((run) => run.id === activeId);
398
- if (active) {
399
- const parked = active.status === "parked";
400
- const activeThread = runtime.threads.get(active.id);
401
- const metadata = [
402
- activeThread?.isolation === "worktree" ? `worktree ${active.integrationStatus ?? activeThread.worktree?.state ?? "active"}` : undefined,
403
- activeThread?.forkedFromRunId !== undefined ? `forked from #${activeThread.forkedFromRunId}` : undefined,
404
- (activeThread?.forkChildRunIds.length ?? 0) > 0 ? `forks ${activeThread!.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
405
- ].filter(Boolean).join(" · ");
406
- return {
407
- content: [
408
- {
409
- type: "text",
410
- text: parked
411
- ? `Run #${active.id} ${active.agent} is parked with retained context${metadata ? ` (${metadata})` : ""}. Use subagent_control resume to restart it, or subagent_stop to retire it.`
412
- : `Run #${active.id} ${active.agent} is still active (${active.activity ?? statusLabel(active.status)}${metadata ? ` · ${metadata}` : ""}). Use subagent_wait to block for its result, subagent_control to steer/park it, or subagent_stop to cancel it.`,
413
- },
414
- ],
415
- details: {},
416
- };
417
- }
418
- return { content: [{ type: "text", text: `No subagent run matches "${requested}".` }], details: {} };
419
- }
420
-
421
- const now = Date.now();
422
- const activeRuns = monitor.getRuns().filter(
423
- (run) => isRunActiveStatus(run.status) || run.retained,
424
- );
425
- const activeLines = activeRuns.map((run) => {
426
- const thread = runtime.threads.get(run.id);
427
- const model = run.modelFallbackFrom
428
- ? `${run.model ?? "?"} (pool fallback from ${run.modelFallbackFrom})`
429
- : (run.model ?? "?");
430
- const parts = [
431
- `#${run.id} ${run.agent}`,
432
- run.label,
433
- model,
434
- formatUsageCompact(run.usage),
435
- formatElapsed(run, now),
436
- thread?.isolation === "worktree" ? `worktree ${run.integrationStatus ?? thread.worktree?.state ?? "active"}` : undefined,
437
- thread?.forkedFromRunId !== undefined ? `forked from #${thread.forkedFromRunId}` : undefined,
438
- (thread?.forkChildRunIds.length ?? 0) > 0 ? `forks ${thread!.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
439
- ].filter(Boolean);
440
- return `- ${parts.join(" · ")} · ${run.activity ?? statusLabel(run.status)}`;
441
- });
442
- const parkedThreads = [...runtime.threads.values()].filter((thread) => thread.state === "parked");
443
- const parkedLines = parkedThreads.map((thread) => {
444
- const relations = [
445
- thread.forkedFromRunId !== undefined ? `forked from #${thread.forkedFromRunId}` : undefined,
446
- thread.forkChildRunIds.length > 0 ? `forks ${thread.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
447
- ].filter(Boolean);
448
- const relation = relations.length > 0 ? ` · ${relations.join(" · ")}` : "";
449
- const isolation = thread.isolation === "worktree" ? ` · worktree ${thread.worktree?.state ?? "active"}` : "";
450
- return `- #${thread.id} ${thread.agentName} · ${runLabel(thread.task)} · parked${thread.sessionDir ? " · context retained" : " · not started"}${isolation}${relation}`;
451
- });
452
- const completed = [...runtime.settledRuns.entries()].slice(-5);
453
- const completedLines = completed.map(([id, result]) => {
454
- const usage = formatUsage(result.usage);
455
- const label = runLabel(result.task);
456
- const model = result.modelFallbackFrom
457
- ? `${result.model ?? "?"} (pool fallback from ${result.modelFallbackFrom})`
458
- : (result.model ?? "?");
459
- const isolation = result.isolation === "worktree" ? ` · worktree ${result.integrationStatus ?? "unknown"}` : "";
460
- const relations = [
461
- result.forkedFromRunId !== undefined ? `forked from #${result.forkedFromRunId}` : undefined,
462
- (result.forkChildRunIds?.length ?? 0) > 0 ? `forks ${result.forkChildRunIds!.map((childId) => `#${childId}`).join(",")}` : undefined,
463
- ].filter(Boolean);
464
- const relation = relations.length > 0 ? ` · ${relations.join(" · ")}` : "";
465
- return `- #${id} ${result.agent}${label ? ` · ${label}` : ""} · ${isFailedResult(result) ? "failed" : "completed"} · ${model}${isolation}${relation}${usage ? ` · ${usage}` : ""}`;
466
- });
467
-
468
- const sections: string[] = [];
469
- sections.push(`### Active subagent runs (${activeRuns.length})`);
470
- sections.push(activeLines.length > 0 ? activeLines.join("\n") : "(none)");
471
- sections.push(`### Parked subagent threads (${parkedThreads.length})`);
472
- sections.push(parkedLines.length > 0 ? parkedLines.join("\n") : "(none)");
473
- sections.push(`### Finished this session (${runtime.settledRuns.size})`);
474
- sections.push(completedLines.length > 0 ? completedLines.join("\n") : "(none)");
475
- sections.push("Pass a run id to subagent_status for the full result, use subagent_control to steer/park/resume/fork, or subagent_wait for active work.");
476
- return { content: [{ type: "text", text: sections.join("\n\n") }], details: {} };
477
- },
478
-
479
- renderCall(args, theme) {
480
- return new Text(
481
- `${theme.fg("toolTitle", theme.bold("subagent_status "))}${theme.fg("accent", args.id ? `#${args.id}` : "overview")}`,
482
- 0,
483
- 0,
484
- );
485
- },
486
-
487
- renderResult(result, _options, theme) {
488
- return renderFirstLine(result, "subagent_status ", theme);
489
- },
490
- });
491
-
492
- // Cancel one or more active runs: aborts the queue controller, which
493
- // terminates the child and delivers an aborted result (with whatever partial
494
- // output it produced) so the main agent always knows the run stopped.
495
- const SubagentStopParams = Type.Object({
496
- id: Type.Optional(
497
- Type.String({
498
- description: "Run id or prefix to stop (see the widget or subagent_status).",
499
- }),
500
- ),
501
- all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
502
- });
503
-
504
- pi.registerTool({
505
- name: "subagent_stop",
506
- label: "Subagent Stop",
507
- description: [
508
- "Destructively stop a sub-agent thread: terminate active work, deliver its aborted partial result, and retire any retained session so it cannot be resumed.",
509
- "Pass id (run id or prefix) to stop one active, parked, or completed thread; all: true stops every active run.",
510
- ].join(" "),
511
- promptSnippet: "Stop a running background subagent (id from the widget/subagent_status; or all: true).",
512
- promptGuidelines: [
513
- "Stop a run when its task is obsolete, stuck, or superseded — do not leave it burning tokens.",
514
- "A stopped run reports as failed with 'aborted' and its partial output, so the next step knows it did not complete.",
515
- ],
516
- parameters: SubagentStopParams,
517
-
518
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
519
- // Start config I/O without yielding: every target below must be claimed
520
- // synchronously before a resume/fork preflight can cross its next await.
521
- const configPromise = loadConfig(runtime.configPath).catch(() => undefined);
522
- const completionResults: SingleResult[] = [];
523
- const candidateIds = params.all === true
524
- ? [...new Set([
525
- ...runtime.runControllers.keys(),
526
- ...[...runtime.threads.values()]
527
- .filter((thread) =>
528
- thread.lifecycleOperation !== undefined ||
529
- ["queued", "resuming", "running", "steering", "interrupting"].includes(thread.state),
530
- )
531
- .map((thread) => thread.id),
532
- ])]
533
- : [...runtime.threads.keys()];
534
- const targets =
535
- params.all === true
536
- ? candidateIds
537
- : params.id !== undefined && params.id.trim() !== ""
538
- ? matchRunIds(candidateIds, params.id.trim())
539
- : [];
540
-
541
- if (targets.length === 0) {
542
- const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
543
- return {
544
- content: [{
545
- type: "text",
546
- text: params.all === true
547
- ? "No active subagent runs to stop."
548
- : `No subagent thread matches "${params.id}".${available ? ` Known threads: ${available}.` : ""}`,
549
- }],
550
- details: {},
551
- };
552
- }
553
-
554
- const claimed: Array<{
555
- runId: number;
556
- thread: SubagentThread;
557
- run: ReturnType<typeof monitor.findRun>;
558
- previousState: SubagentThread["state"];
559
- wasQueued: boolean;
560
- wasResuming: boolean;
561
- wasActive: boolean;
562
- generation: number;
563
- controller: AbortController | undefined;
564
- completion: Promise<void>;
565
- stopVersion: number;
566
- stopMessage: string;
567
- }> = [];
568
- for (const runId of targets) {
569
- const thread = runtime.threads.get(runId);
570
- if (!thread) continue;
571
- const previousState = thread.state;
572
- const wasQueued = previousState === "queued";
573
- const wasResuming = previousState === "resuming";
574
- const wasActive =
575
- thread.lifecycleOperation !== undefined ||
576
- ["queued", "resuming", "running", "steering", "interrupting"].includes(previousState);
577
- const stopVersion = ++thread.lifecycleVersion;
578
- // Stop-all claims every target before the first await. This invalidates
579
- // all concurrent resume/fork preflights as one synchronous operation.
580
- thread.lifecycleOperation = "stop";
581
- thread.retired = true;
582
- thread.retireOnSettle = true;
583
- thread.state = "stopped";
584
- const stopMessage = wasQueued
585
- ? "Stopped by subagent_stop before the run started."
586
- : wasResuming
587
- ? "Stopped by subagent_stop while resume was preparing."
588
- : wasActive
589
- ? "Stopped by subagent_stop."
590
- : previousState === "parked"
591
- ? "Stopped by subagent_stop from a parked checkpoint."
592
- : "Retired by subagent_stop.";
593
- claimed.push({
594
- runId,
595
- thread,
596
- run: monitor.findRun(runId),
597
- previousState,
598
- wasQueued,
599
- wasResuming,
600
- wasActive,
601
- generation: thread.generation,
602
- controller: thread.queueController,
603
- completion: thread.generationCompletion,
604
- stopVersion,
605
- stopMessage,
606
- });
607
- }
608
-
609
- const stopped: string[] = [];
610
- const retainedIntegration: string[] = [];
611
- for (const claim of claimed) {
612
- const {
613
- runId,
614
- thread,
615
- run,
616
- previousState,
617
- wasQueued,
618
- wasResuming,
619
- wasActive,
620
- generation,
621
- controller,
622
- completion,
623
- stopVersion,
624
- stopMessage,
625
- } = claim;
626
- await thread.control.stop(stopMessage).catch(() => undefined);
627
- runtime.backgroundQueue.cancel(controller);
628
- await completion;
629
- if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
630
- if (thread.queueController === controller) thread.queueController = undefined;
631
-
632
- // Dispatch yields publication ownership as soon as stop claims the
633
- // lifecycle. Synthesize and publish the one aborted result here only when
634
- // this stop actually interrupted unfinished work.
635
- let stoppedResult: SingleResult | undefined;
636
- if (
637
- wasQueued ||
638
- wasResuming ||
639
- previousState === "parked" ||
640
- !runtime.settledRuns.has(runId)
641
- ) {
642
- const prior = thread.lastResult;
643
- stoppedResult = prior
644
- ? {
645
- ...prior,
646
- parked: undefined,
647
- exitCode: 1,
648
- stopReason: "aborted",
649
- errorMessage: stopMessage,
650
- runId,
651
- }
652
- : {
653
- agent: thread.agentName,
654
- agentSource: "builtin",
655
- task: thread.task,
656
- exitCode: 1,
657
- messages: [],
658
- stderr: stopMessage,
659
- usage: emptyUsage(),
660
- model: run?.model,
661
- thinking: run?.thinking,
662
- stopReason: "aborted",
663
- errorMessage: stopMessage,
664
- runId,
665
- isolation: thread.isolation,
666
- originalCwd: thread.cwd,
667
- isolationCwd: thread.executionCwd,
668
- };
669
- const finalization = await thread.finalizeIsolation(generation, stoppedResult);
670
- if (finalization?.status === "retained") retainedIntegration.push(`#${runId}`);
671
- runtime.registerRunResult(runId, stoppedResult);
672
- thread.lastResult = stoppedResult;
673
- }
674
- monitor.setStatus(runId, "failed");
675
- if (stoppedResult) {
676
- const inspectState = inspectorStore.get(runId);
677
- const alreadyStampedStopped = inspectState.trajectory.getGenerationEvents().some(
678
- (event) => event.kind === "settled" && event.status === "stopped",
679
- );
680
- if (!alreadyStampedStopped) {
681
- inspectState.trajectory.append({
682
- kind: "settled",
683
- status: "stopped",
684
- model: stoppedResult.model ?? run?.model,
685
- isolation: thread.isolation,
686
- ...(stoppedResult.integrationStatus && stoppedResult.integrationStatus !== "pending"
687
- ? { integrationStatus: stoppedResult.integrationStatus }
688
- : {}),
689
- });
690
- }
691
- const stoppedRun = monitor.findRun(runId);
692
- inspectState.retainFrom(stoppedRun
693
- ? {
694
- ...stoppedRun,
695
- agent: stoppedResult.agent,
696
- task: stoppedResult.task,
697
- model: stoppedResult.model ?? stoppedRun.model,
698
- usage: stoppedResult.usage,
699
- }
700
- : {
701
- agent: stoppedResult.agent,
702
- task: stoppedResult.task,
703
- model: stoppedResult.model,
704
- thinking: stoppedResult.thinking,
705
- status: "failed",
706
- endedAt: inspectState.trajectory.summary().endedAt,
707
- usage: stoppedResult.usage,
708
- });
709
- completionResults.push(stoppedResult);
710
- }
711
- monitor.removeRun(runId);
712
- runtime.retireThreadSession(thread);
713
- if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
714
- thread.lifecycleOperation = undefined;
715
- }
716
- stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
717
- }
718
- if (completionResults.length > 0) {
719
- const maxResultLines = (await configPromise)?.maxResultLines ?? DEFAULT_MAX_RESULT_LINES;
720
- runtime.sendCompletionGroup(completionResults.map((result) => ({
721
- agent: result.agent,
722
- block: formatCompletionBlock(result, maxResultLines, ctx.cwd),
723
- triggerTurn: true,
724
- })));
725
- runtime.completionBatcher.flush();
726
- }
727
- return {
728
- content: [{
729
- type: "text",
730
- text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}`,
731
- }],
732
- details: {},
733
- };
734
- },
735
-
736
- renderCall(args, theme) {
737
- return new Text(
738
- `${theme.fg("toolTitle", theme.bold("subagent_stop "))}${theme.fg("accent", args.all === true ? "all" : args.id ? `#${args.id}` : "?")}`,
739
- 0,
740
- 0,
741
- );
742
- },
743
-
744
- renderResult(result, _options, theme) {
745
- return renderFirstLine(result, "subagent_stop ", theme);
746
- },
747
- });
748
- }
1
+ /**
2
+ * Thread controls and lookup tools around the subagent runtime:
3
+ * subagent_control (steer/retarget/park/resume), subagent_wait (in-turn result
4
+ * lookup), subagent_status, and destructive subagent_stop.
5
+ */
6
+
7
+ import { StringEnum } from "@earendil-works/pi-ai";
8
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
9
+ import { Text } from "@earendil-works/pi-tui";
10
+ import { Type } from "typebox";
11
+ import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "./config.ts";
12
+ import { emptyUsage, formatCompletionBlock, formatUsage, matchRunIds } from "./format.ts";
13
+ import {
14
+ formatElapsed,
15
+ formatUsageCompact,
16
+ isRunActiveStatus,
17
+ monitor,
18
+ runLabel,
19
+ statusLabel,
20
+ type RunStatus,
21
+ } from "./monitor.ts";
22
+ import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
23
+ import { getResultOutput, isFailedResult, type SingleResult } from "./spawn.ts";
24
+ import { trajectoryStore } from "./trajectory.ts";
25
+
26
+ /** In-turn result lookup. Dispatch already ended the turn and results arrive as
27
+ * wake-up messages, so the default must NOT block: a settled run returns its
28
+ * result immediately, a still-active run returns a "still running — end your
29
+ * turn" note and the model finishes (the completion then wakes it). Blocking
30
+ * is opt-in via an explicit timeoutMs — a long default would hold the turn
31
+ * hostage for nothing, since the result arrives on its own either way. */
32
+ const SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS = 0;
33
+
34
+ function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
35
+ const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
36
+ const text = parts
37
+ .map((part) => (typeof part.text === "string" ? part.text : ""))
38
+ .join(" ")
39
+ .trim();
40
+ const firstLine = text.split("\n").find((line) => line.trim()) ?? "(no output)";
41
+ return new Text(`${theme.fg("toolTitle", theme.bold(label))}${theme.fg("dim", firstLine.slice(0, 60))}`, 0, 0);
42
+ }
43
+
44
+ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime): void {
45
+ const SubagentControlParams = Type.Object({
46
+ action: StringEnum(["steer", "retarget", "park", "resume", "fork"] as const, {
47
+ description: "Control operation for the logical sub-agent thread.",
48
+ }),
49
+ id: Type.Integer({ minimum: 1, description: "Stable run id shown by subagent dispatch/status output." }),
50
+ instruction: Type.Optional(
51
+ Type.String({ description: "Instruction queued by steer after the current child tool batch." }),
52
+ ),
53
+ objective: Type.Optional(
54
+ Type.String({ description: "Replacement objective for retarget, or optional objective for resume/fork." }),
55
+ ),
56
+ });
57
+
58
+ pi.registerTool({
59
+ name: "subagent_control",
60
+ label: "Subagent Control",
61
+ description: [
62
+ "Control an existing sub-agent thread by stable run id.",
63
+ "steer queues an instruction after the current child tool batch.",
64
+ "retarget aborts the current objective to a stable checkpoint, suppresses that aborted completion, then starts the replacement objective in the same session.",
65
+ "park aborts to a stable checkpoint, terminates the child, preserves context, and releases its concurrency slot.",
66
+ "resume restarts a parked, completed, or failed retained thread with the same run id; objective is optional.",
67
+ "fork copies a parked/completed/failed retained session branch into a new logical thread and run id; an isolated checkpoint must be settled and integrated first; objective is optional.",
68
+ ].join(" "),
69
+ promptSnippet: "Control a subagent thread: steer, retarget, park, resume, or fork by stable run id.",
70
+ promptGuidelines: [
71
+ "Use subagent_control steer to refine active work without restarting it; the instruction is delivered after the child's current tool batch.",
72
+ "Use subagent_control retarget when the active objective is obsolete; do not call subagent_stop and start a fresh thread because retarget preserves context and suppresses the abandoned completion.",
73
+ "Use subagent_control park to checkpoint useful context while releasing the process/concurrency slot, and resume to continue the same run id later.",
74
+ "Use subagent_control fork only on a parked or settled retained thread; isolated work must settle and integrate before it can fork. Fork creates a new run id while leaving the source untouched.",
75
+ "Use subagent_stop only for destructive cancellation; it retires that thread's retained session without retiring independent forks.",
76
+ ],
77
+ parameters: SubagentControlParams,
78
+
79
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
80
+ const thread = runtime.threads.get(params.id);
81
+ if (!thread) {
82
+ return { content: [{ type: "text", text: `No subagent thread matches run #${params.id}.` }], details: {} };
83
+ }
84
+ const nonBlank = (value: string | undefined): string | undefined => {
85
+ const trimmed = value?.trim();
86
+ return trimmed ? trimmed : undefined;
87
+ };
88
+
89
+ try {
90
+ switch (params.action) {
91
+ case "steer": {
92
+ const instruction = nonBlank(params.instruction);
93
+ if (!instruction) {
94
+ return { content: [{ type: "text", text: "steer requires a non-blank instruction." }], details: {} };
95
+ }
96
+ if (!(["running", "steering"] as const).includes(thread.control.getPhase() as any)) {
97
+ return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.control.getPhase()}; only a running thread can be steered.` }], details: {} };
98
+ }
99
+ await thread.control.steer(instruction);
100
+ trajectoryStore.get(thread.id).trajectory.append({ kind: "steer", instruction });
101
+ return { content: [{ type: "text", text: `Queued steering instruction for run #${thread.id} after its current tool batch.` }], details: {} };
102
+ }
103
+ case "retarget": {
104
+ const objective = nonBlank(params.objective);
105
+ if (!objective) {
106
+ return { content: [{ type: "text", text: "retarget requires a non-blank objective." }], details: {} };
107
+ }
108
+ const phase = thread.control.getPhase();
109
+ if (thread.state === "queued" && phase === "queued") {
110
+ thread.task = objective;
111
+ thread.control.retargetPending(objective);
112
+ monitor.setTask(thread.id, objective);
113
+ trajectoryStore.get(thread.id).trajectory.append({ kind: "retarget", objective });
114
+ return { content: [{ type: "text", text: `Updated queued run #${thread.id} to the new objective; no child was spawned by this control action.` }], details: {} };
115
+ }
116
+ if (!(["starting", "running", "steering", "interrupting", "retrying"] as const).includes(phase as any)) {
117
+ return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.state}; use resume with objective to restart retained context.` }], details: {} };
118
+ }
119
+ thread.task = objective;
120
+ monitor.setTask(thread.id, objective);
121
+ await thread.control.retarget(objective);
122
+ trajectoryStore.get(thread.id).trajectory.append({ kind: "retarget", objective });
123
+ return { content: [{ type: "text", text: `Retargeted run #${thread.id} in the same session; the aborted objective will not be delivered as a completion.` }], details: {} };
124
+ }
125
+ case "park": {
126
+ if (thread.state === "parked") {
127
+ return { content: [{ type: "text", text: `Run #${thread.id} is already parked.` }], details: {} };
128
+ }
129
+ const disposition = await thread.park();
130
+ return disposition === "queued"
131
+ ? {
132
+ content: [{ type: "text", text: `Parked queued run #${thread.id}; it never spawned a child or empty session.` }],
133
+ details: {},
134
+ }
135
+ : {
136
+ content: [{ type: "text", text: `Parked run #${thread.id} at a stable checkpoint; its session is retained and concurrency slot released.` }],
137
+ details: {},
138
+ };
139
+ }
140
+ case "resume": {
141
+ if (thread.retired) {
142
+ return { content: [{ type: "text", text: `Run #${thread.id} was retired by subagent_stop and has no resumable session.` }], details: {} };
143
+ }
144
+ if (!(["parked", "completed", "failed"] as const).includes(thread.state as any)) {
145
+ return { content: [{ type: "text", text: `Run #${thread.id} is ${thread.state}; it must be parked or settled before resume.` }], details: {} };
146
+ }
147
+ const objective = params.objective === undefined ? undefined : nonBlank(params.objective);
148
+ if (params.objective !== undefined && !objective) {
149
+ return { content: [{ type: "text", text: "resume objective must be non-blank when provided." }], details: {} };
150
+ }
151
+ const pending = await thread.resume(objective, ctx);
152
+ if (pending.exitCode !== -1) {
153
+ return { content: [{ type: "text", text: getResultOutput(pending) }], details: {} };
154
+ }
155
+ return { content: [{ type: "text", text: `Resumed run #${thread.id}${objective ? " with a new objective" : " from retained context"}; completion will arrive automatically.` }], details: {}, terminate: true };
156
+ }
157
+ case "fork": {
158
+ const objective = params.objective === undefined ? undefined : nonBlank(params.objective);
159
+ if (params.objective !== undefined && !objective) {
160
+ return { content: [{ type: "text", text: "fork objective must be non-blank when provided." }], details: {} };
161
+ }
162
+ const pending = await thread.fork(objective, ctx);
163
+ if (pending.exitCode !== -1 || pending.runId === undefined) {
164
+ return { content: [{ type: "text", text: getResultOutput(pending) }], details: {} };
165
+ }
166
+ return {
167
+ content: [{
168
+ type: "text",
169
+ text: `Forked run #${thread.id} into new run #${pending.runId}${objective ? " with a new objective" : " from retained context"}; the source is unchanged and child completion will arrive automatically.`,
170
+ }],
171
+ details: { sourceRunId: thread.id, childRunId: pending.runId, result: pending },
172
+ terminate: true,
173
+ };
174
+ }
175
+ }
176
+ } catch (error) {
177
+ throw new Error(`Could not ${params.action} run #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
178
+ }
179
+ },
180
+
181
+ renderCall(args, theme) {
182
+ return new Text(`${theme.fg("toolTitle", theme.bold("subagent_control "))}${theme.fg("accent", `${args.action} #${args.id}`)}`, 0, 0);
183
+ },
184
+ renderResult(result, _options, theme) {
185
+ return renderFirstLine(result, "subagent_control ", theme);
186
+ },
187
+ });
188
+
189
+ const SubagentWaitParams = Type.Object({
190
+ id: Type.Optional(
191
+ Type.String({
192
+ description: "Run id or prefix shown by subagent dispatch/status output. Omit to wait for all active runs in this session.",
193
+ }),
194
+ ),
195
+ timeoutMs: Type.Optional(
196
+ Type.Number({
197
+ description: `Block for up to this many milliseconds and report the still-running runs. Default ${SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS}: no blocking — settled runs return their result immediately, active runs return a note telling the model to end its turn.`,
198
+ }),
199
+ ),
200
+ });
201
+
202
+ pi.registerTool({
203
+ name: "subagent_wait",
204
+ label: "Subagent Wait",
205
+ description: [
206
+ "Look up background sub-agent run(s) and return their results.",
207
+ "PREFER NOT CALLING THIS: dispatching already ended your turn and results arrive as a message that wakes you automatically.",
208
+ "By default it does NOT block: a settled run returns its result immediately; a still-active run returns a 'still running — end your turn' note.",
209
+ "Pass an explicit timeoutMs ONLY when you must stay in the turn and need the result right now (sequential dependent steps).",
210
+ "NEVER sleep, poll, or wait with bash to get a sub-agent result: end the turn, or call this tool.",
211
+ "The same result is also delivered as a completion message that resumes the main agent, so you may see it twice (once here, once as a wake-up) — that is expected, not a duplicate.",
212
+ ].join(" "),
213
+ promptSnippet: "Look up a background subagent result in-turn (id: run id from dispatch/status output; omit for all). Non-blocking by default; pass timeoutMs to block.",
214
+ promptGuidelines: [
215
+ "Do NOT call subagent_wait to hold the turn: results arrive as wake-up messages automatically. The default call is a non-blocking lookup — settled results return immediately, active runs return a note telling you to end your turn.",
216
+ "Pass an explicit timeoutMs only when you must keep the turn AND the next step depends on the result right now — e.g. the user asked you to wait for it.",
217
+ "Never use bash sleep/timeout/polling to wait for a sub-agent — it blocks the turn and delays result delivery.",
218
+ "If subagent_wait times out, end the turn and wait for the wake-up message, or call it again with a longer timeoutMs.",
219
+ ],
220
+ parameters: SubagentWaitParams,
221
+
222
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
223
+ const config = await loadConfig(runtime.configPath);
224
+ // A non-finite or negative timeout would produce a nonsensical note
225
+ // ("timed out after Infinitys") or an instant "timeout" that was never
226
+ // asked for; fall back to the default. Zero is honored as an immediate
227
+ // give-up (clamped to 1ms below).
228
+ const timeoutMs =
229
+ typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs >= 0
230
+ ? params.timeoutMs
231
+ : SUBAGENT_WAIT_DEFAULT_TIMEOUT_MS;
232
+ const isActive = (run: { status: RunStatus; retained?: boolean }): boolean =>
233
+ isRunActiveStatus(run.status) || run.retained === true;
234
+
235
+ const requested = params.id?.trim();
236
+ // A run that already settled resolves immediately with its result.
237
+ if (requested) {
238
+ const settledIds = matchRunIds([...runtime.settledRuns.keys()], requested);
239
+ if (settledIds.length > 0) {
240
+ return {
241
+ content: [
242
+ { type: "text", text: settledIds.map((id) => formatCompletionBlock(runtime.settledRuns.get(id)!, config.maxResultLines, ctx.cwd)).join("\n\n") },
243
+ ],
244
+ details: {},
245
+ };
246
+ }
247
+ }
248
+
249
+ const activeRuns = monitor.getRuns().filter(isActive);
250
+ const targetIds = requested ? matchRunIds(activeRuns.map((run) => run.id), requested) : activeRuns.map((run) => run.id);
251
+ const targets = activeRuns.filter((run) => targetIds.includes(run.id));
252
+ if (targets.length === 0) {
253
+ const activeList = activeRuns.map((run) => `#${run.id} ${run.agent}`).join(", ");
254
+ return {
255
+ content: [
256
+ {
257
+ type: "text",
258
+ text: requested
259
+ ? `No active subagent run matches "${requested}".${activeList ? ` Active runs: ${activeList}.` : ""}`
260
+ : `No active subagent runs${activeList ? ` (active: ${activeList})` : " right now"}.`,
261
+ },
262
+ ],
263
+ details: {},
264
+ };
265
+ }
266
+
267
+ const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
268
+ const already = runtime.settledRuns.get(runId);
269
+ if (already) return Promise.resolve({ result: already });
270
+ return new Promise((resolve) => {
271
+ let done = false;
272
+ let timer: ReturnType<typeof setTimeout> | undefined;
273
+ let unsub: (() => void) | undefined;
274
+ const cleanup = (): void => {
275
+ if (timer) clearTimeout(timer);
276
+ if (unsub) unsub();
277
+ signal?.removeEventListener("abort", onAbort);
278
+ const listeners = runtime.settledListeners.get(runId);
279
+ if (listeners) {
280
+ listeners.delete(onSettled);
281
+ if (listeners.size === 0) runtime.settledListeners.delete(runId);
282
+ }
283
+ };
284
+ const finish = (outcome: { result?: SingleResult; note?: string }): void => {
285
+ if (done) return;
286
+ done = true;
287
+ cleanup();
288
+ resolve(outcome);
289
+ };
290
+ const onSettled = (result: SingleResult): void => finish({ result });
291
+ const onMonitor = (): void => {
292
+ const current = runtime.settledRuns.get(runId);
293
+ if (current) {
294
+ finish({ result: current });
295
+ return;
296
+ }
297
+ const live = monitor.findRun(runId);
298
+ if (live?.status === "parked") {
299
+ finish({ note: `run #${runId} was parked at a stable checkpoint; use subagent_control resume to continue it` });
300
+ return;
301
+ }
302
+ if (!live) {
303
+ // Removal is followed synchronously by registerRunResult in the
304
+ // finishing task; re-check on the next tick so the result wins.
305
+ setTimeout(() => {
306
+ const late = runtime.settledRuns.get(runId);
307
+ if (late) finish({ result: late });
308
+ else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
309
+ }, 0);
310
+ }
311
+ };
312
+ const onAbort = (): void => finish({ note: "wait aborted" });
313
+ let listeners = runtime.settledListeners.get(runId);
314
+ if (!listeners) {
315
+ listeners = new Set();
316
+ runtime.settledListeners.set(runId, listeners);
317
+ }
318
+ listeners.add(onSettled);
319
+ unsub = monitor.subscribe(onMonitor);
320
+ timer = setTimeout(
321
+ () =>
322
+ finish({
323
+ note:
324
+ timeoutMs === 0
325
+ ? `run #${runId} is still active — end your turn: the result will wake you (or call subagent_wait again with an explicit timeoutMs to block)`
326
+ : `wait timed out after ${Math.round(timeoutMs / 1000)}s — run #${runId} is still active; call subagent_wait again or end the turn (the result will wake you when ready)`,
327
+ }),
328
+ Math.max(1, timeoutMs),
329
+ );
330
+ if (signal?.aborted) onAbort();
331
+ else signal?.addEventListener("abort", onAbort, { once: true });
332
+ });
333
+ };
334
+
335
+ const outcomes = await Promise.all(targets.map((run) => waitForRun(run.id)));
336
+ const blocks = outcomes.map((outcome) =>
337
+ outcome.result ? formatCompletionBlock(outcome.result, config.maxResultLines, ctx.cwd) : (outcome.note ?? "(no outcome)"),
338
+ );
339
+ return { content: [{ type: "text", text: blocks.join("\n\n") }], details: {} };
340
+ },
341
+
342
+ renderCall(args, theme) {
343
+ const target = args.id ? `#${args.id}` : "all";
344
+ return new Text(`${theme.fg("toolTitle", theme.bold("subagent_wait "))}${theme.fg("accent", target)}`, 0, 0);
345
+ },
346
+
347
+ renderResult(result, _options, theme) {
348
+ return renderFirstLine(result, "subagent_wait ", theme);
349
+ },
350
+ });
351
+
352
+ // Status overview: what is running right now and what finished this session,
353
+ // with per-run details (id, agent, model, usage, elapsed, activity) so the
354
+ // main agent can decide whether to wait, stop, or re-dispatch. Learned from
355
+ // nicobailon/pi-subagents ({action:"status"} + status files): inspect before
356
+ // you act, and report run ids when handing off.
357
+ const SubagentStatusParams = Type.Object({
358
+ id: Type.Optional(
359
+ Type.String({
360
+ description: "Run id or prefix to show the full result for (must already be finished; use subagent_wait to block on an active run).",
361
+ }),
362
+ ),
363
+ });
364
+
365
+ pi.registerTool({
366
+ name: "subagent_status",
367
+ label: "Subagent Status",
368
+ description: [
369
+ "List active background sub-agent runs (id, agent, model, usage, elapsed, current activity) and recently finished results.",
370
+ "Pass id to read the full result of a finished run; pass no id for the overview.",
371
+ "Use it to decide whether to subagent_wait, subagent_stop, or re-dispatch — never to poll: results arrive by themselves.",
372
+ ].join(" "),
373
+ promptSnippet: "Inspect background subagents: active runs, finished results, full result by id.",
374
+ promptGuidelines: [
375
+ "Call subagent_status to see what is running and what already finished.",
376
+ "Never poll subagent_status in a loop to wait for a run: end the turn (you will be woken) or call subagent_wait.",
377
+ "A finished run's id stays available for the session; its full result is one subagent_status call away.",
378
+ ],
379
+ parameters: SubagentStatusParams,
380
+
381
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
382
+ const config = await loadConfig(runtime.configPath);
383
+ const requested = params.id?.trim();
384
+
385
+ if (requested) {
386
+ const settledIds = matchRunIds([...runtime.settledRuns.keys()], requested);
387
+ if (settledIds.length > 0) {
388
+ return {
389
+ content: [
390
+ { type: "text", text: settledIds.map((id) => formatCompletionBlock(runtime.settledRuns.get(id)!, config.maxResultLines, ctx.cwd)).join("\n\n") },
391
+ ],
392
+ details: {},
393
+ };
394
+ }
395
+ const runs = monitor.getRuns();
396
+ const activeId = matchRunIds(runs.map((run) => run.id), requested)[0];
397
+ const active = activeId === undefined ? undefined : runs.find((run) => run.id === activeId);
398
+ if (active) {
399
+ const parked = active.status === "parked";
400
+ const activeThread = runtime.threads.get(active.id);
401
+ const metadata = [
402
+ activeThread?.isolation === "worktree" ? `worktree ${active.integrationStatus ?? activeThread.worktree?.state ?? "active"}` : undefined,
403
+ activeThread?.forkedFromRunId !== undefined ? `forked from #${activeThread.forkedFromRunId}` : undefined,
404
+ (activeThread?.forkChildRunIds.length ?? 0) > 0 ? `forks ${activeThread!.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
405
+ ].filter(Boolean).join(" · ");
406
+ return {
407
+ content: [
408
+ {
409
+ type: "text",
410
+ text: parked
411
+ ? `Run #${active.id} ${active.agent} is parked with retained context${metadata ? ` (${metadata})` : ""}. Use subagent_control resume to restart it, or subagent_stop to retire it.`
412
+ : `Run #${active.id} ${active.agent} is still active (${active.activity ?? statusLabel(active.status)}${metadata ? ` · ${metadata}` : ""}). Use subagent_wait to block for its result, subagent_control to steer/park it, or subagent_stop to cancel it.`,
413
+ },
414
+ ],
415
+ details: {},
416
+ };
417
+ }
418
+ return { content: [{ type: "text", text: `No subagent run matches "${requested}".` }], details: {} };
419
+ }
420
+
421
+ const now = Date.now();
422
+ const activeRuns = monitor.getRuns().filter(
423
+ (run) => isRunActiveStatus(run.status) || run.retained,
424
+ );
425
+ const activeLines = activeRuns.map((run) => {
426
+ const thread = runtime.threads.get(run.id);
427
+ const model = run.modelFallbackFrom
428
+ ? `${run.model ?? "?"} (pool fallback from ${run.modelFallbackFrom})`
429
+ : (run.model ?? "?");
430
+ const parts = [
431
+ `#${run.id} ${run.agent}`,
432
+ run.label,
433
+ model,
434
+ formatUsageCompact(run.usage),
435
+ formatElapsed(run, now),
436
+ thread?.isolation === "worktree" ? `worktree ${run.integrationStatus ?? thread.worktree?.state ?? "active"}` : undefined,
437
+ thread?.forkedFromRunId !== undefined ? `forked from #${thread.forkedFromRunId}` : undefined,
438
+ (thread?.forkChildRunIds.length ?? 0) > 0 ? `forks ${thread!.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
439
+ ].filter(Boolean);
440
+ return `- ${parts.join(" · ")} · ${run.activity ?? statusLabel(run.status)}`;
441
+ });
442
+ const parkedThreads = [...runtime.threads.values()].filter((thread) => thread.state === "parked");
443
+ const parkedLines = parkedThreads.map((thread) => {
444
+ const relations = [
445
+ thread.forkedFromRunId !== undefined ? `forked from #${thread.forkedFromRunId}` : undefined,
446
+ thread.forkChildRunIds.length > 0 ? `forks ${thread.forkChildRunIds.map((id) => `#${id}`).join(",")}` : undefined,
447
+ ].filter(Boolean);
448
+ const relation = relations.length > 0 ? ` · ${relations.join(" · ")}` : "";
449
+ const isolation = thread.isolation === "worktree" ? ` · worktree ${thread.worktree?.state ?? "active"}` : "";
450
+ return `- #${thread.id} ${thread.agentName} · ${runLabel(thread.task)} · parked${thread.sessionDir ? " · context retained" : " · not started"}${isolation}${relation}`;
451
+ });
452
+ const completed = [...runtime.settledRuns.entries()].slice(-5);
453
+ const completedLines = completed.map(([id, result]) => {
454
+ const usage = formatUsage(result.usage);
455
+ const label = runLabel(result.task);
456
+ const model = result.modelFallbackFrom
457
+ ? `${result.model ?? "?"} (pool fallback from ${result.modelFallbackFrom})`
458
+ : (result.model ?? "?");
459
+ const isolation = result.isolation === "worktree" ? ` · worktree ${result.integrationStatus ?? "unknown"}` : "";
460
+ const relations = [
461
+ result.forkedFromRunId !== undefined ? `forked from #${result.forkedFromRunId}` : undefined,
462
+ (result.forkChildRunIds?.length ?? 0) > 0 ? `forks ${result.forkChildRunIds!.map((childId) => `#${childId}`).join(",")}` : undefined,
463
+ ].filter(Boolean);
464
+ const relation = relations.length > 0 ? ` · ${relations.join(" · ")}` : "";
465
+ return `- #${id} ${result.agent}${label ? ` · ${label}` : ""} · ${isFailedResult(result) ? "failed" : "completed"} · ${model}${isolation}${relation}${usage ? ` · ${usage}` : ""}`;
466
+ });
467
+
468
+ const sections: string[] = [];
469
+ sections.push(`### Active subagent runs (${activeRuns.length})`);
470
+ sections.push(activeLines.length > 0 ? activeLines.join("\n") : "(none)");
471
+ sections.push(`### Parked subagent threads (${parkedThreads.length})`);
472
+ sections.push(parkedLines.length > 0 ? parkedLines.join("\n") : "(none)");
473
+ sections.push(`### Finished this session (${runtime.settledRuns.size})`);
474
+ sections.push(completedLines.length > 0 ? completedLines.join("\n") : "(none)");
475
+ sections.push("Pass a run id to subagent_status for the full result, use subagent_control to steer/park/resume/fork, or subagent_wait for active work.");
476
+ return { content: [{ type: "text", text: sections.join("\n\n") }], details: {} };
477
+ },
478
+
479
+ renderCall(args, theme) {
480
+ return new Text(
481
+ `${theme.fg("toolTitle", theme.bold("subagent_status "))}${theme.fg("accent", args.id ? `#${args.id}` : "overview")}`,
482
+ 0,
483
+ 0,
484
+ );
485
+ },
486
+
487
+ renderResult(result, _options, theme) {
488
+ return renderFirstLine(result, "subagent_status ", theme);
489
+ },
490
+ });
491
+
492
+ // Cancel one or more active runs: aborts the queue controller, which
493
+ // terminates the child and delivers an aborted result (with whatever partial
494
+ // output it produced) so the main agent always knows the run stopped.
495
+ const SubagentStopParams = Type.Object({
496
+ id: Type.Optional(
497
+ Type.String({
498
+ description: "Run id or prefix to stop (see subagent dispatch output or subagent_status).",
499
+ }),
500
+ ),
501
+ all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
502
+ });
503
+
504
+ pi.registerTool({
505
+ name: "subagent_stop",
506
+ label: "Subagent Stop",
507
+ description: [
508
+ "Destructively stop a sub-agent thread: terminate active work, deliver its aborted partial result, and retire any retained session so it cannot be resumed.",
509
+ "Pass id (run id or prefix) to stop one active, parked, or completed thread; all: true stops every active run.",
510
+ ].join(" "),
511
+ promptSnippet: "Stop a running background subagent (id from dispatch output/subagent_status; or all: true).",
512
+ promptGuidelines: [
513
+ "Stop a run when its task is obsolete, stuck, or superseded — do not leave it burning tokens.",
514
+ "A stopped run reports as failed with 'aborted' and its partial output, so the next step knows it did not complete.",
515
+ ],
516
+ parameters: SubagentStopParams,
517
+
518
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
519
+ // Start config I/O without yielding: every target below must be claimed
520
+ // synchronously before a resume/fork preflight can cross its next await.
521
+ const configPromise = loadConfig(runtime.configPath).catch(() => undefined);
522
+ const completionResults: SingleResult[] = [];
523
+ const candidateIds = params.all === true
524
+ ? [...new Set([
525
+ ...runtime.runControllers.keys(),
526
+ ...[...runtime.threads.values()]
527
+ .filter((thread) =>
528
+ thread.lifecycleOperation !== undefined ||
529
+ ["queued", "resuming", "running", "steering", "interrupting"].includes(thread.state),
530
+ )
531
+ .map((thread) => thread.id),
532
+ ])]
533
+ : [...runtime.threads.keys()];
534
+ const targets =
535
+ params.all === true
536
+ ? candidateIds
537
+ : params.id !== undefined && params.id.trim() !== ""
538
+ ? matchRunIds(candidateIds, params.id.trim())
539
+ : [];
540
+
541
+ if (targets.length === 0) {
542
+ const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
543
+ return {
544
+ content: [{
545
+ type: "text",
546
+ text: params.all === true
547
+ ? "No active subagent runs to stop."
548
+ : `No subagent thread matches "${params.id}".${available ? ` Known threads: ${available}.` : ""}`,
549
+ }],
550
+ details: {},
551
+ };
552
+ }
553
+
554
+ const claimed: Array<{
555
+ runId: number;
556
+ thread: SubagentThread;
557
+ run: ReturnType<typeof monitor.findRun>;
558
+ previousState: SubagentThread["state"];
559
+ wasQueued: boolean;
560
+ wasResuming: boolean;
561
+ wasActive: boolean;
562
+ generation: number;
563
+ controller: AbortController | undefined;
564
+ completion: Promise<void>;
565
+ stopVersion: number;
566
+ stopMessage: string;
567
+ }> = [];
568
+ for (const runId of targets) {
569
+ const thread = runtime.threads.get(runId);
570
+ if (!thread) continue;
571
+ const previousState = thread.state;
572
+ const wasQueued = previousState === "queued";
573
+ const wasResuming = previousState === "resuming";
574
+ const wasActive =
575
+ thread.lifecycleOperation !== undefined ||
576
+ ["queued", "resuming", "running", "steering", "interrupting"].includes(previousState);
577
+ const stopVersion = ++thread.lifecycleVersion;
578
+ // Stop-all claims every target before the first await. This invalidates
579
+ // all concurrent resume/fork preflights as one synchronous operation.
580
+ thread.lifecycleOperation = "stop";
581
+ thread.retired = true;
582
+ thread.retireOnSettle = true;
583
+ thread.state = "stopped";
584
+ const stopMessage = wasQueued
585
+ ? "Stopped by subagent_stop before the run started."
586
+ : wasResuming
587
+ ? "Stopped by subagent_stop while resume was preparing."
588
+ : wasActive
589
+ ? "Stopped by subagent_stop."
590
+ : previousState === "parked"
591
+ ? "Stopped by subagent_stop from a parked checkpoint."
592
+ : "Retired by subagent_stop.";
593
+ claimed.push({
594
+ runId,
595
+ thread,
596
+ run: monitor.findRun(runId),
597
+ previousState,
598
+ wasQueued,
599
+ wasResuming,
600
+ wasActive,
601
+ generation: thread.generation,
602
+ controller: thread.queueController,
603
+ completion: thread.generationCompletion,
604
+ stopVersion,
605
+ stopMessage,
606
+ });
607
+ }
608
+
609
+ const stopped: string[] = [];
610
+ const retainedIntegration: string[] = [];
611
+ for (const claim of claimed) {
612
+ const {
613
+ runId,
614
+ thread,
615
+ run,
616
+ previousState,
617
+ wasQueued,
618
+ wasResuming,
619
+ wasActive,
620
+ generation,
621
+ controller,
622
+ completion,
623
+ stopVersion,
624
+ stopMessage,
625
+ } = claim;
626
+ await thread.control.stop(stopMessage).catch(() => undefined);
627
+ runtime.backgroundQueue.cancel(controller);
628
+ await completion;
629
+ if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
630
+ if (thread.queueController === controller) thread.queueController = undefined;
631
+
632
+ // Dispatch yields publication ownership as soon as stop claims the
633
+ // lifecycle. Synthesize and publish the one aborted result here only when
634
+ // this stop actually interrupted unfinished work.
635
+ let stoppedResult: SingleResult | undefined;
636
+ if (
637
+ wasQueued ||
638
+ wasResuming ||
639
+ previousState === "parked" ||
640
+ !runtime.settledRuns.has(runId)
641
+ ) {
642
+ const prior = thread.lastResult;
643
+ stoppedResult = prior
644
+ ? {
645
+ ...prior,
646
+ parked: undefined,
647
+ exitCode: 1,
648
+ stopReason: "aborted",
649
+ errorMessage: stopMessage,
650
+ runId,
651
+ }
652
+ : {
653
+ agent: thread.agentName,
654
+ agentSource: "builtin",
655
+ task: thread.task,
656
+ exitCode: 1,
657
+ messages: [],
658
+ stderr: stopMessage,
659
+ usage: emptyUsage(),
660
+ model: run?.model,
661
+ thinking: run?.thinking,
662
+ stopReason: "aborted",
663
+ errorMessage: stopMessage,
664
+ runId,
665
+ isolation: thread.isolation,
666
+ originalCwd: thread.cwd,
667
+ isolationCwd: thread.executionCwd,
668
+ };
669
+ const finalization = await thread.finalizeIsolation(generation, stoppedResult);
670
+ if (finalization?.status === "retained") retainedIntegration.push(`#${runId}`);
671
+ runtime.registerRunResult(runId, stoppedResult);
672
+ thread.lastResult = stoppedResult;
673
+ }
674
+ monitor.setStatus(runId, "failed");
675
+ if (stoppedResult) {
676
+ const trajectoryState = trajectoryStore.get(runId);
677
+ const alreadyStampedStopped = trajectoryState.trajectory.getGenerationEvents().some(
678
+ (event) => event.kind === "settled" && event.status === "stopped",
679
+ );
680
+ if (!alreadyStampedStopped) {
681
+ trajectoryState.trajectory.append({
682
+ kind: "settled",
683
+ status: "stopped",
684
+ model: stoppedResult.model ?? run?.model,
685
+ isolation: thread.isolation,
686
+ ...(stoppedResult.integrationStatus && stoppedResult.integrationStatus !== "pending"
687
+ ? { integrationStatus: stoppedResult.integrationStatus }
688
+ : {}),
689
+ });
690
+ }
691
+ completionResults.push(stoppedResult);
692
+ }
693
+ monitor.removeRun(runId);
694
+ runtime.retireThreadSession(thread);
695
+ if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
696
+ thread.lifecycleOperation = undefined;
697
+ }
698
+ stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
699
+ }
700
+ if (completionResults.length > 0) {
701
+ const maxResultLines = (await configPromise)?.maxResultLines ?? DEFAULT_MAX_RESULT_LINES;
702
+ runtime.sendCompletionGroup(completionResults.map((result) => ({
703
+ agent: result.agent,
704
+ block: formatCompletionBlock(result, maxResultLines, ctx.cwd),
705
+ triggerTurn: true,
706
+ })));
707
+ runtime.completionBatcher.flush();
708
+ }
709
+ return {
710
+ content: [{
711
+ type: "text",
712
+ text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}`,
713
+ }],
714
+ details: {},
715
+ };
716
+ },
717
+
718
+ renderCall(args, theme) {
719
+ return new Text(
720
+ `${theme.fg("toolTitle", theme.bold("subagent_stop "))}${theme.fg("accent", args.all === true ? "all" : args.id ? `#${args.id}` : "?")}`,
721
+ 0,
722
+ 0,
723
+ );
724
+ },
725
+
726
+ renderResult(result, _options, theme) {
727
+ return renderFirstLine(result, "subagent_stop ", theme);
728
+ },
729
+ });
730
+ }