pi-subagents 0.32.0 → 0.33.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +30 -3
  2. package/README.md +147 -58
  3. package/install.mjs +2 -1
  4. package/package.json +3 -2
  5. package/skills/pi-subagents/SKILL.md +70 -14
  6. package/src/agents/agent-management.ts +177 -5
  7. package/src/agents/agent-memory.ts +254 -0
  8. package/src/agents/agent-serializer.ts +11 -0
  9. package/src/agents/agents.ts +142 -12
  10. package/src/agents/chain-serializer.ts +27 -2
  11. package/src/extension/doctor.ts +1 -9
  12. package/src/extension/fanout-child.ts +2 -2
  13. package/src/extension/index.ts +65 -90
  14. package/src/extension/rpc.ts +369 -0
  15. package/src/extension/schemas.ts +52 -8
  16. package/src/extension/tool-description.ts +200 -0
  17. package/src/intercom/intercom-bridge.ts +21 -253
  18. package/src/intercom/native-supervisor-channel.ts +510 -0
  19. package/src/runs/background/async-execution.ts +51 -7
  20. package/src/runs/background/async-job-tracker.ts +12 -2
  21. package/src/runs/background/async-status.ts +27 -2
  22. package/src/runs/background/completion-batcher.ts +166 -0
  23. package/src/runs/background/control-channel.ts +106 -1
  24. package/src/runs/background/fleet-view.ts +515 -0
  25. package/src/runs/background/notify.ts +161 -44
  26. package/src/runs/background/result-watcher.ts +1 -2
  27. package/src/runs/background/run-id-resolver.ts +3 -2
  28. package/src/runs/background/run-status.ts +166 -6
  29. package/src/runs/background/scheduled-runs.ts +514 -0
  30. package/src/runs/background/subagent-runner.ts +409 -35
  31. package/src/runs/background/wait.ts +353 -0
  32. package/src/runs/foreground/chain-execution.ts +95 -21
  33. package/src/runs/foreground/execution.ts +150 -21
  34. package/src/runs/foreground/subagent-executor.ts +378 -64
  35. package/src/runs/shared/dynamic-fanout.ts +1 -1
  36. package/src/runs/shared/model-fallback.ts +167 -20
  37. package/src/runs/shared/model-scope.ts +128 -0
  38. package/src/runs/shared/nested-events.ts +31 -0
  39. package/src/runs/shared/parallel-utils.ts +1 -0
  40. package/src/runs/shared/pi-args.ts +30 -1
  41. package/src/runs/shared/subagent-prompt-runtime.ts +108 -2
  42. package/src/runs/shared/tool-budget.ts +74 -0
  43. package/src/runs/shared/turn-budget.ts +52 -0
  44. package/src/shared/artifacts.ts +1 -0
  45. package/src/shared/atomic-json.ts +15 -2
  46. package/src/shared/child-transcript.ts +212 -0
  47. package/src/shared/settings.ts +3 -1
  48. package/src/shared/types.ts +134 -19
  49. package/src/slash/prompt-workflows.ts +330 -0
  50. package/src/slash/slash-commands.ts +16 -2
  51. package/src/tui/render.ts +16 -8
  52. package/src/extension/companion-suggestions.ts +0 -359
@@ -14,6 +14,7 @@
14
14
  * authoritative.
15
15
  */
16
16
 
17
+ import { randomUUID } from "node:crypto";
17
18
  import * as fs from "node:fs";
18
19
  import * as path from "node:path";
19
20
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
@@ -26,7 +27,7 @@ import { POLL_INTERVAL_MS } from "../../shared/types.ts";
26
27
  */
27
28
  export const INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
28
29
 
29
- export type ControlChannelFs = Pick<typeof fs, "mkdirSync" | "existsSync" | "rmSync" | "watch">;
30
+ export type ControlChannelFs = Pick<typeof fs, "mkdirSync" | "existsSync" | "rmSync" | "watch" | "readdirSync" | "readFileSync">;
30
31
  export type ControlChannelTimers = { setInterval: typeof setInterval; clearInterval: typeof clearInterval };
31
32
  type KillFn = (pid: number, signal?: NodeJS.Signals | 0) => unknown;
32
33
 
@@ -44,6 +45,18 @@ export interface TimeoutRequest {
44
45
  reason?: string;
45
46
  }
46
47
 
48
+ export interface SteerRequest {
49
+ type: "steer";
50
+ id: string;
51
+ ts: number;
52
+ message: string;
53
+ targetIndex?: number;
54
+ source?: string;
55
+ }
56
+
57
+ const STEER_REQUESTS_DIR = "steer-requests";
58
+ const STEER_TARGETS_DIR = "steer-targets";
59
+
47
60
  /** Control inbox directory inside an async run dir. */
48
61
  export function controlInboxDir(asyncDir: string): string {
49
62
  return path.join(asyncDir, "control");
@@ -59,6 +72,26 @@ export function timeoutRequestPath(asyncDir: string): string {
59
72
  return path.join(controlInboxDir(asyncDir), "timeout.json");
60
73
  }
61
74
 
75
+ /** Directory of parent-to-runner steering requests. */
76
+ export function steerRequestsDir(asyncDir: string): string {
77
+ return path.join(controlInboxDir(asyncDir), STEER_REQUESTS_DIR);
78
+ }
79
+
80
+ /** Per-child inbox consumed by the child prompt runtime inside the Pi process. */
81
+ export function stepSteerInboxDir(asyncDir: string, index: number): string {
82
+ return path.join(controlInboxDir(asyncDir), STEER_TARGETS_DIR, String(index));
83
+ }
84
+
85
+ function steerRequestFileName(request: SteerRequest): string {
86
+ return `${String(request.ts).padStart(13, "0")}-${Buffer.from(request.id).toString("base64url")}.json`;
87
+ }
88
+
89
+ export function writeSteerRequestToDir(dir: string, request: SteerRequest): string {
90
+ const requestPath = path.join(dir, steerRequestFileName(request));
91
+ writeAtomicJson(requestPath, request);
92
+ return requestPath;
93
+ }
94
+
62
95
  /**
63
96
  * Parent side: drop a portable interrupt request the runner's inbox watcher will
64
97
  * pick up regardless of OS. Written atomically (temp + rename), dir auto-created.
@@ -85,6 +118,76 @@ export function requestAsyncTimeout(
85
118
  return requestPath;
86
119
  }
87
120
 
121
+ export function requestAsyncSteer(
122
+ asyncDir: string,
123
+ payload: { message: string; targetIndex?: number; source?: string; id?: string; ts?: number },
124
+ deps: { now?: () => number; randomId?: () => string } = {},
125
+ ): string {
126
+ const message = payload.message.trim();
127
+ if (!message) throw new Error("steer message must not be empty.");
128
+ if (payload.targetIndex !== undefined && (!Number.isInteger(payload.targetIndex) || payload.targetIndex < 0)) {
129
+ throw new Error("steer targetIndex must be a non-negative integer.");
130
+ }
131
+ const request: SteerRequest = {
132
+ type: "steer",
133
+ id: payload.id ?? deps.randomId?.() ?? randomUUID(),
134
+ ts: payload.ts ?? deps.now?.() ?? Date.now(),
135
+ message,
136
+ ...(payload.targetIndex !== undefined ? { targetIndex: payload.targetIndex } : {}),
137
+ ...(payload.source ? { source: payload.source } : {}),
138
+ };
139
+ return writeSteerRequestToDir(steerRequestsDir(asyncDir), request);
140
+ }
141
+
142
+ export function enqueueStepSteer(asyncDir: string, index: number, request: SteerRequest): string {
143
+ if (!Number.isInteger(index) || index < 0) throw new Error("steer child index must be a non-negative integer.");
144
+ return writeSteerRequestToDir(stepSteerInboxDir(asyncDir, index), { ...request, targetIndex: index, type: "steer" });
145
+ }
146
+
147
+ function parseSteerRequest(raw: unknown): SteerRequest | undefined {
148
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
149
+ const input = raw as Partial<SteerRequest>;
150
+ if (input.type !== "steer") return undefined;
151
+ if (typeof input.id !== "string" || !input.id.trim()) return undefined;
152
+ if (typeof input.ts !== "number" || !Number.isFinite(input.ts)) return undefined;
153
+ if (typeof input.message !== "string" || !input.message.trim()) return undefined;
154
+ if (input.targetIndex !== undefined && (!Number.isInteger(input.targetIndex) || input.targetIndex < 0)) return undefined;
155
+ return {
156
+ type: "steer",
157
+ id: input.id.trim(),
158
+ ts: input.ts,
159
+ message: input.message.trim(),
160
+ ...(input.targetIndex !== undefined ? { targetIndex: input.targetIndex } : {}),
161
+ ...(typeof input.source === "string" && input.source.trim() ? { source: input.source } : {}),
162
+ };
163
+ }
164
+
165
+ export function consumeSteerRequestsFromDir(dir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
166
+ if (!fsImpl.existsSync(dir)) return [];
167
+ const requests: SteerRequest[] = [];
168
+ for (const entry of fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort()) {
169
+ const requestPath = path.join(dir, entry);
170
+ let parsed: SteerRequest | undefined;
171
+ try {
172
+ parsed = parseSteerRequest(JSON.parse(fsImpl.readFileSync(requestPath, "utf-8")));
173
+ } catch {
174
+ parsed = undefined;
175
+ }
176
+ try {
177
+ fsImpl.rmSync(requestPath, { recursive: true });
178
+ } catch {
179
+ // Already removed by a concurrent check — do not execute it twice.
180
+ continue;
181
+ }
182
+ if (parsed) requests.push(parsed);
183
+ }
184
+ return requests.sort((left, right) => left.ts - right.ts || left.id.localeCompare(right.id));
185
+ }
186
+
187
+ export function consumeSteerRequests(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
188
+ return consumeSteerRequestsFromDir(steerRequestsDir(asyncDir), fsImpl);
189
+ }
190
+
88
191
  /**
89
192
  * Runner side: consume a pending interrupt request. Idempotent — removes the file
90
193
  * so each distinct request fires exactly once. Returns whether one was pending.
@@ -173,6 +276,7 @@ export function watchAsyncControlInbox(
173
276
  opts: {
174
277
  onInterrupt: () => void;
175
278
  onTimeout?: () => void;
279
+ onSteer?: (request: SteerRequest) => void;
176
280
  pollIntervalMs?: number;
177
281
  fs?: ControlChannelFs;
178
282
  timers?: ControlChannelTimers;
@@ -193,6 +297,7 @@ export function watchAsyncControlInbox(
193
297
  try {
194
298
  if (consumeTimeoutRequest(asyncDir, fsImpl)) opts.onTimeout?.();
195
299
  if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
300
+ for (const request of consumeSteerRequests(asyncDir, fsImpl)) opts.onSteer?.(request);
196
301
  } catch {
197
302
  // Never let inbox errors crash the runner.
198
303
  }
@@ -0,0 +1,515 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
5
+ import { formatActivityLabel } from "../../shared/status-format.ts";
6
+ import {
7
+ ASYNC_DIR,
8
+ RESULTS_DIR,
9
+ type ActivityState,
10
+ type AsyncJobStep,
11
+ type AsyncStatus,
12
+ type Details,
13
+ type NestedRunSummary,
14
+ type SubagentRunMode,
15
+ type SubagentState,
16
+ } from "../../shared/types.ts";
17
+ import { readStatus } from "../../shared/utils.ts";
18
+ import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
19
+ import { formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
20
+
21
+ const DEFAULT_TRANSCRIPT_LINES = 80;
22
+ const MAX_TRANSCRIPT_LINES = 500;
23
+ const TRANSCRIPT_TAIL_BYTES = 256 * 1024;
24
+
25
+ type ForegroundControl = SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never;
26
+
27
+ interface FleetViewParams {
28
+ lines?: number;
29
+ }
30
+
31
+ interface FleetViewDeps {
32
+ asyncDirRoot?: string;
33
+ resultsDir?: string;
34
+ kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
35
+ now?: () => number;
36
+ state?: SubagentState;
37
+ childSafe?: boolean;
38
+ }
39
+
40
+ interface TranscriptOptions {
41
+ index?: number;
42
+ lines?: number;
43
+ sessionRoots?: string[];
44
+ }
45
+
46
+ interface TextTailResult {
47
+ path: string;
48
+ lines: string[];
49
+ truncated: boolean;
50
+ error?: string;
51
+ }
52
+
53
+ function transcriptLineLimit(value: number | undefined): number {
54
+ if (value === undefined) return DEFAULT_TRANSCRIPT_LINES;
55
+ if (!Number.isFinite(value)) return DEFAULT_TRANSCRIPT_LINES;
56
+ return Math.max(1, Math.min(MAX_TRANSCRIPT_LINES, Math.trunc(value)));
57
+ }
58
+
59
+ function uniqueStrings(values: Array<string | undefined>): string[] {
60
+ const seen = new Set<string>();
61
+ const result: string[] = [];
62
+ for (const value of values) {
63
+ if (!value || seen.has(value)) continue;
64
+ seen.add(value);
65
+ result.push(value);
66
+ }
67
+ return result;
68
+ }
69
+
70
+ function resolveMaybeRelative(asyncDir: string, filePath: string | undefined): string | undefined {
71
+ if (!filePath) return undefined;
72
+ return path.resolve(asyncDir, filePath);
73
+ }
74
+
75
+ function pathWithin(base: string, candidate: string): boolean {
76
+ const resolvedBase = path.resolve(base);
77
+ const resolvedCandidate = path.resolve(candidate);
78
+ return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
79
+ }
80
+
81
+ function getErrorMessage(error: unknown): string {
82
+ return error instanceof Error ? error.message : String(error);
83
+ }
84
+
85
+ function isNotFoundError(error: unknown): boolean {
86
+ return typeof error === "object"
87
+ && error !== null
88
+ && "code" in error
89
+ && (error as NodeJS.ErrnoException).code === "ENOENT";
90
+ }
91
+
92
+ function readTextTail(filePath: string, maxLines: number): TextTailResult {
93
+ let stat: fs.Stats;
94
+ try {
95
+ stat = fs.statSync(filePath);
96
+ } catch (error) {
97
+ if (isNotFoundError(error)) return { path: filePath, lines: [], truncated: false };
98
+ return { path: filePath, lines: [], truncated: false, error: getErrorMessage(error) };
99
+ }
100
+ if (stat.size === 0) return { path: filePath, lines: [], truncated: false };
101
+
102
+ let fd: number | undefined;
103
+ try {
104
+ const bytesToRead = Math.min(stat.size, TRANSCRIPT_TAIL_BYTES);
105
+ const start = stat.size - bytesToRead;
106
+ const buffer = Buffer.alloc(bytesToRead);
107
+ fd = fs.openSync(filePath, "r");
108
+ const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead, start);
109
+ const content = buffer.subarray(0, bytesRead).toString("utf-8");
110
+ let lines = content.split(/\r?\n/);
111
+ if (start > 0 && lines.length > 0) lines = lines.slice(1);
112
+ if (lines.at(-1) === "") lines = lines.slice(0, -1);
113
+ return { path: filePath, lines: lines.slice(-maxLines), truncated: start > 0 || lines.length > maxLines };
114
+ } catch (error) {
115
+ return { path: filePath, lines: [], truncated: false, error: getErrorMessage(error) };
116
+ } finally {
117
+ if (fd !== undefined) fs.closeSync(fd);
118
+ }
119
+ }
120
+
121
+ function readContainedTextTail(filePath: string, maxLines: number, trustedRoots: string[], label: string): TextTailResult {
122
+ if (trustedRoots.length === 0) return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path without a trusted root: ${filePath}` };
123
+ const resolvedPath = path.resolve(filePath);
124
+ if (!trustedRoots.some((root) => pathWithin(root, resolvedPath))) {
125
+ return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path outside trusted roots: ${filePath}` };
126
+ }
127
+ let lstat: fs.Stats;
128
+ try {
129
+ lstat = fs.lstatSync(resolvedPath);
130
+ } catch (error) {
131
+ if (isNotFoundError(error)) return { path: filePath, lines: [], truncated: false };
132
+ return { path: filePath, lines: [], truncated: false, error: getErrorMessage(error) };
133
+ }
134
+ if (lstat.isSymbolicLink()) return { path: filePath, lines: [], truncated: false, error: `Refusing to read symlink ${label} transcript path: ${filePath}` };
135
+ if (!lstat.isFile()) return { path: filePath, lines: [], truncated: false, error: `Refusing to read non-file ${label} transcript path: ${filePath}` };
136
+ let realPath: string;
137
+ let realRoots: string[];
138
+ try {
139
+ realPath = fs.realpathSync(resolvedPath);
140
+ realRoots = trustedRoots.filter((root) => fs.existsSync(root)).map((root) => fs.realpathSync(root));
141
+ } catch (error) {
142
+ return { path: filePath, lines: [], truncated: false, error: getErrorMessage(error) };
143
+ }
144
+ if (!realRoots.some((root) => pathWithin(root, realPath))) {
145
+ return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path outside trusted roots: ${filePath}` };
146
+ }
147
+ return readTextTail(resolvedPath, maxLines);
148
+ }
149
+
150
+ function stringifyJsonPreview(value: unknown, maxLength = 240): string {
151
+ let raw: string;
152
+ if (typeof value === "string") raw = value;
153
+ else raw = JSON.stringify(value);
154
+ return raw.length > maxLength ? `${raw.slice(0, maxLength)}…` : raw;
155
+ }
156
+
157
+ function contentText(content: unknown): string {
158
+ if (typeof content === "string") return content;
159
+ if (!Array.isArray(content)) return "";
160
+ return content.map((part) => {
161
+ if (!part || typeof part !== "object") return "";
162
+ const entry = part as { type?: unknown; text?: unknown; name?: unknown; toolName?: unknown; args?: unknown; result?: unknown; content?: unknown };
163
+ if (typeof entry.text === "string") return entry.text;
164
+ if (entry.type === "toolCall" || entry.type === "tool_call") {
165
+ const name = typeof entry.name === "string" ? entry.name : typeof entry.toolName === "string" ? entry.toolName : "tool";
166
+ return `[tool: ${name}${entry.args === undefined ? "" : ` ${stringifyJsonPreview(entry.args)}`}]`;
167
+ }
168
+ if (entry.type === "toolResult" || entry.type === "tool_result") {
169
+ return `[tool result${entry.result === undefined ? "" : `: ${stringifyJsonPreview(entry.result)}`}]`;
170
+ }
171
+ if (entry.content !== undefined) return stringifyJsonPreview(entry.content);
172
+ return "";
173
+ }).filter(Boolean).join("\n");
174
+ }
175
+
176
+ function sessionMessageLine(record: unknown): string | undefined {
177
+ if (!record || typeof record !== "object") return undefined;
178
+ const outer = record as { message?: unknown; role?: unknown; content?: unknown; type?: unknown };
179
+ const message = outer.message && typeof outer.message === "object" ? outer.message as { role?: unknown; content?: unknown } : outer;
180
+ const role = typeof message.role === "string" ? message.role : undefined;
181
+ if (!role) return undefined;
182
+ const text = contentText(message.content).trim();
183
+ if (!text) return undefined;
184
+ return `${role}: ${text}`;
185
+ }
186
+
187
+ function readSessionTranscriptTail(sessionFile: string, maxLines: number, trustedRoots: string[]): { lines: string[]; warnings: string[] } {
188
+ const tail = readContainedTextTail(sessionFile, Math.max(maxLines * 4, maxLines), trustedRoots, "session");
189
+ const warnings: string[] = [];
190
+ if (tail.error) warnings.push(`Session read failed for ${sessionFile}: ${tail.error}`);
191
+ const lines: string[] = [];
192
+ let malformed = 0;
193
+ for (const line of tail.lines) {
194
+ if (!line.trim()) continue;
195
+ try {
196
+ const parsed = JSON.parse(line) as unknown;
197
+ const messageLine = sessionMessageLine(parsed);
198
+ if (messageLine) lines.push(messageLine);
199
+ } catch {
200
+ malformed++;
201
+ }
202
+ }
203
+ if (malformed > 0) warnings.push(`Skipped ${malformed} malformed session tail line${malformed === 1 ? "" : "s"}.`);
204
+ return { lines: lines.slice(-maxLines), warnings };
205
+ }
206
+
207
+ function formatActivityFacts(input: {
208
+ activityState?: ActivityState;
209
+ lastActivityAt?: number;
210
+ currentTool?: string;
211
+ currentToolStartedAt?: number;
212
+ currentPath?: string;
213
+ turnCount?: number;
214
+ toolCount?: number;
215
+ tokens?: { total: number };
216
+ }): string | undefined {
217
+ const facts: string[] = [];
218
+ if (input.currentTool && input.currentToolStartedAt !== undefined) facts.push(`tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`);
219
+ else if (input.currentTool) facts.push(`tool ${input.currentTool}`);
220
+ if (input.currentPath) facts.push(shortenPath(input.currentPath));
221
+ if (input.turnCount !== undefined) facts.push(`${input.turnCount} turns`);
222
+ if (input.toolCount !== undefined) facts.push(`${input.toolCount} tools`);
223
+ if (input.tokens?.total) facts.push(`${formatTokens(input.tokens.total)} tok`);
224
+ const activity = formatActivityLabel(input.lastActivityAt, input.activityState);
225
+ return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : undefined;
226
+ }
227
+
228
+ function foregroundModeName(control: ForegroundControl): string {
229
+ if (control.mode === "single" && control.currentAgent) return control.currentAgent;
230
+ return control.mode;
231
+ }
232
+
233
+ function formatForegroundFleetLines(controls: ForegroundControl[]): string[] {
234
+ if (controls.length === 0) return [];
235
+ const lines = ["Foreground runs:"];
236
+ const ordered = [...controls].sort((left, right) => right.updatedAt - left.updatedAt);
237
+ for (const control of ordered) {
238
+ const activity = formatActivityFacts({
239
+ activityState: control.currentActivityState,
240
+ lastActivityAt: control.lastActivityAt,
241
+ currentTool: control.currentTool,
242
+ currentToolStartedAt: control.currentToolStartedAt,
243
+ currentPath: control.currentPath,
244
+ turnCount: control.turnCount,
245
+ toolCount: control.toolCount,
246
+ ...(control.tokens !== undefined ? { tokens: { total: control.tokens } } : {}),
247
+ });
248
+ const current = control.currentAgent ? ` | ${control.currentAgent}${control.currentIndex !== undefined ? ` #${control.currentIndex}` : ""}` : "";
249
+ lines.push(`- ${control.runId} | running | ${foregroundModeName(control)}${current}${activity ? ` | ${activity}` : ""}`);
250
+ lines.push(` status: subagent({ action: "status", id: "${control.runId}" })`);
251
+ lines.push(" transcript: live in the expanded foreground result; persisted session transcript appears after completion when sessions are enabled.");
252
+ lines.push(...formatNestedRunStatusLines(control.nestedChildren, { indent: " ", commandHints: true, maxLines: 12 }));
253
+ }
254
+ return lines;
255
+ }
256
+
257
+ function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
258
+ if (runs.length === 0) return [];
259
+ const lines = ["Async runs:"];
260
+ for (const run of runs) {
261
+ const progress = formatAsyncRunProgressLabel(run);
262
+ const activity = formatActivityFacts(run);
263
+ const cwd = run.cwd ? shortenPath(run.cwd) : shortenPath(run.asyncDir);
264
+ const pending = run.pendingAppends ? ` | ${run.pendingAppends} pending append${run.pendingAppends === 1 ? "" : "s"}` : "";
265
+ lines.push(`- ${run.id} | ${run.state}${activity ? ` | ${activity}` : ""} | ${run.mode} | ${progress}${pending} | ${cwd}`);
266
+ lines.push(` status: subagent({ action: "status", id: "${run.id}" })`);
267
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", view: "transcript" })`);
268
+ for (const step of run.steps) {
269
+ const display = step.label ? `${step.label} (${step.agent})` : step.agent;
270
+ const phase = step.phase ? `[${step.phase}] ` : "";
271
+ const stepActivity = formatActivityFacts(step);
272
+ const modelThinking = formatModelThinking(step.model, step.thinking);
273
+ const parts = [`${step.index}. ${phase}${display}`, step.status, stepActivity, modelThinking].filter(Boolean);
274
+ lines.push(` ${parts.join(" | ")}`);
275
+ const output = path.join(run.asyncDir, `output-${step.index}.log`);
276
+ if (fs.existsSync(output)) lines.push(` output: ${shortenPath(output)}`);
277
+ if (step.sessionFile) lines.push(` session: ${shortenPath(step.sessionFile)}`);
278
+ if (step.status === "running" || step.recentOutput?.length || fs.existsSync(output)) {
279
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", index: ${step.index}, view: "transcript" })`);
280
+ }
281
+ lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 12 }));
282
+ }
283
+ const attached = new Set(run.steps.flatMap((step) => step.children?.map((child) => child.id) ?? []));
284
+ const unattached = run.nestedChildren?.filter((child) => !attached.has(child.id)) ?? [];
285
+ lines.push(...formatNestedRunStatusLines(unattached, { indent: " ", commandHints: true, maxLines: 12 }));
286
+ if (run.error) lines.push(` error: ${run.error}`);
287
+ for (const warning of run.nestedWarnings ?? []) lines.push(` warning: ${warning}`);
288
+ const outputPath = formatAsyncRunOutputPath(run);
289
+ if (outputPath) lines.push(` output: ${shortenPath(outputPath)}`);
290
+ if (run.sessionFile) lines.push(` session: ${shortenPath(run.sessionFile)}`);
291
+ }
292
+ return lines;
293
+ }
294
+
295
+ export function inspectSubagentFleet(_params: FleetViewParams, deps: FleetViewDeps = {}): AgentToolResult<Details> {
296
+ if (deps.childSafe) {
297
+ return {
298
+ content: [{ type: "text", text: "Child-safe subagent fleet view is unavailable without an explicit run id. Use subagent({ action: \"status\", id: \"...\" }) for the delegated run you can see." }],
299
+ isError: true,
300
+ details: { mode: "management", results: [] },
301
+ };
302
+ }
303
+
304
+ let asyncRuns: AsyncRunSummary[];
305
+ try {
306
+ asyncRuns = listAsyncRuns(deps.asyncDirRoot ?? ASYNC_DIR, {
307
+ states: ["queued", "running"],
308
+ sessionId: deps.state?.currentSessionId ?? undefined,
309
+ resultsDir: deps.resultsDir ?? RESULTS_DIR,
310
+ kill: deps.kill,
311
+ now: deps.now,
312
+ });
313
+ } catch (error) {
314
+ const message = error instanceof Error ? error.message : String(error);
315
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
316
+ }
317
+
318
+ const foregroundControls = deps.state ? [...deps.state.foregroundControls.values()] : [];
319
+ const total = foregroundControls.length + asyncRuns.length;
320
+ if (total === 0) {
321
+ return {
322
+ content: [{ type: "text", text: "No active subagent fleet. Background runs that already finished are available through completion notifications or subagent({ action: \"status\", id: \"...\" })." }],
323
+ details: { mode: "management", results: [] },
324
+ };
325
+ }
326
+
327
+ const lines = [`Subagent fleet: ${total} active`, ""];
328
+ const foregroundLines = formatForegroundFleetLines(foregroundControls);
329
+ if (foregroundLines.length) lines.push(...foregroundLines, "");
330
+ const asyncLines = formatAsyncFleetLines(asyncRuns);
331
+ if (asyncLines.length) lines.push(...asyncLines, "");
332
+ lines.push("Commands:");
333
+ lines.push(" Refresh fleet: subagent({ action: \"status\", view: \"fleet\" })");
334
+ lines.push(" Tail run transcript: subagent({ action: \"status\", id: \"<run-id>\", view: \"transcript\" })");
335
+ lines.push(" Tail child transcript: subagent({ action: \"status\", id: \"<run-id>\", index: 0, view: \"transcript\" })");
336
+
337
+ return { content: [{ type: "text", text: lines.join("\n").trimEnd() }], details: { mode: "management", results: [] } };
338
+ }
339
+
340
+ function validateTranscriptIndex(index: number | undefined, steps: AsyncJobStep[]): number | undefined {
341
+ if (index === undefined) return undefined;
342
+ if (!Number.isInteger(index)) throw new Error("Transcript index must be an integer.");
343
+ if (index < 0 || index >= steps.length) throw new Error(`Transcript index ${index} is out of range for ${steps.length} child step${steps.length === 1 ? "" : "s"}.`);
344
+ return index;
345
+ }
346
+
347
+ function selectTranscriptStep(status: AsyncStatus, options: TranscriptOptions): { index?: number; step?: AsyncJobStep; hint?: string } {
348
+ const steps = status.steps ?? [];
349
+ let selectedIndex = validateTranscriptIndex(options.index, steps);
350
+ if (selectedIndex === undefined) {
351
+ if (status.state === "running" && typeof status.currentStep === "number" && status.currentStep >= 0 && status.currentStep < steps.length) {
352
+ selectedIndex = status.currentStep;
353
+ } else if (steps.length === 1) {
354
+ selectedIndex = 0;
355
+ }
356
+ }
357
+ const step = selectedIndex !== undefined ? steps[selectedIndex] : undefined;
358
+ const hint = options.index === undefined && steps.length > 1
359
+ ? `Tip: pass index to inspect a specific child transcript (${steps.map((candidate, index) => `${index}=${candidate.agent}`).join(", ")}).`
360
+ : undefined;
361
+ return { index: selectedIndex, step, hint };
362
+ }
363
+
364
+ function stepStateLine(mode: SubagentRunMode, index: number | undefined, step: AsyncJobStep | undefined): string | undefined {
365
+ if (index === undefined || !step) return undefined;
366
+ const modelThinking = formatModelThinking(step.model, step.thinking);
367
+ const parts = [
368
+ `${mode === "parallel" ? "Agent" : "Step"}: ${index} (${step.agent})`,
369
+ step.status,
370
+ formatActivityFacts(step),
371
+ modelThinking,
372
+ step.error ? `error: ${step.error}` : undefined,
373
+ ].filter(Boolean);
374
+ return parts.join(" | ");
375
+ }
376
+
377
+ function appendKnownArtifacts(lines: string[], input: { outputPaths: string[]; sessionFile?: string; eventsPath?: string; logPath?: string; resultPath?: string }): void {
378
+ const artifacts: string[] = [];
379
+ for (const outputPath of input.outputPaths) artifacts.push(`Output: ${outputPath}`);
380
+ if (input.sessionFile) artifacts.push(`Session: ${input.sessionFile}`);
381
+ if (input.eventsPath) artifacts.push(`Events: ${input.eventsPath}`);
382
+ if (input.logPath) artifacts.push(`Log: ${input.logPath}`);
383
+ if (input.resultPath) artifacts.push(`Result: ${input.resultPath}`);
384
+ if (!artifacts.length) return;
385
+ lines.push("Artifacts:");
386
+ for (const artifact of artifacts) lines.push(` ${artifact}`);
387
+ }
388
+
389
+ function appendTranscriptBody(lines: string[], sourceLabel: string, sourceLines: string[], truncated: boolean): void {
390
+ lines.push(`${sourceLabel}${truncated ? " (tail truncated)" : ""}:`);
391
+ if (sourceLines.length === 0) {
392
+ lines.push(" (no transcript lines available yet)");
393
+ return;
394
+ }
395
+ for (const line of sourceLines) lines.push(` ${line}`);
396
+ }
397
+
398
+ export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string, options: TranscriptOptions = {}): string {
399
+ const lineLimit = transcriptLineLimit(options.lines);
400
+ const selected = selectTranscriptStep(status, options);
401
+ const stepOutputPath = selected.index !== undefined ? path.join(asyncDir, `output-${selected.index}.log`) : undefined;
402
+ const runOutputPath = resolveMaybeRelative(asyncDir, status.outputFile);
403
+ const logPath = path.join(asyncDir, `subagent-log-${status.runId}.md`);
404
+ const outputPaths = selected.index !== undefined
405
+ ? uniqueStrings([stepOutputPath, runOutputPath && stepOutputPath && path.resolve(runOutputPath) === path.resolve(stepOutputPath) ? runOutputPath : undefined])
406
+ : uniqueStrings([runOutputPath]);
407
+ const sessionFile = selected.index !== undefined ? selected.step?.sessionFile : status.sessionFile;
408
+ const eventsPath = path.join(asyncDir, "events.jsonl");
409
+
410
+ const lines = [
411
+ `Run: ${status.runId}`,
412
+ `State: ${status.state}`,
413
+ `Mode: ${status.mode}`,
414
+ stepStateLine(status.mode, selected.index, selected.step),
415
+ selected.hint,
416
+ ].filter((line): line is string => Boolean(line));
417
+ appendKnownArtifacts(lines, { outputPaths, sessionFile, eventsPath: fs.existsSync(eventsPath) ? eventsPath : undefined, logPath: fs.existsSync(logPath) ? logPath : undefined });
418
+
419
+ const warnings: string[] = [];
420
+ let transcriptLines: string[] = [];
421
+ let transcriptSource = "Transcript tail";
422
+ let truncated = false;
423
+ for (const outputPath of outputPaths) {
424
+ const tail = readContainedTextTail(outputPath, lineLimit, [asyncDir], "output");
425
+ if (tail.error) warnings.push(`Output read failed for ${tail.path}: ${tail.error}`);
426
+ if (tail.lines.length === 0) continue;
427
+ transcriptLines = tail.lines;
428
+ transcriptSource = `Transcript tail from ${tail.path}`;
429
+ truncated = tail.truncated;
430
+ break;
431
+ }
432
+ if (transcriptLines.length === 0 && selected.step?.recentOutput?.length) {
433
+ transcriptLines = selected.step.recentOutput.slice(-lineLimit);
434
+ transcriptSource = "Recent output from status.json";
435
+ }
436
+ if (transcriptLines.length === 0 && sessionFile) {
437
+ const sessionTail = readSessionTranscriptTail(sessionFile, lineLimit, options.sessionRoots ?? []);
438
+ transcriptLines = sessionTail.lines;
439
+ warnings.push(...sessionTail.warnings);
440
+ if (transcriptLines.length > 0) transcriptSource = `Session transcript tail from ${sessionFile}`;
441
+ }
442
+
443
+ if (warnings.length) {
444
+ lines.push("Warnings:");
445
+ for (const warning of warnings) lines.push(` ${warning}`);
446
+ }
447
+ appendTranscriptBody(lines, transcriptSource, transcriptLines, truncated);
448
+ return lines.join("\n");
449
+ }
450
+
451
+ export function formatNestedRunTranscript(run: NestedRunSummary, options: TranscriptOptions = {}): string {
452
+ if (run.asyncDir) {
453
+ const status = readStatus(run.asyncDir);
454
+ if (status) return formatAsyncRunTranscript(status, run.asyncDir, options);
455
+ }
456
+ const lineLimit = transcriptLineLimit(options.lines);
457
+ const lines = [
458
+ `Nested run: ${run.id}`,
459
+ `State: ${run.state}`,
460
+ run.mode ? `Mode: ${run.mode}` : undefined,
461
+ run.agent ? `Agent: ${run.agent}` : run.agents?.length ? `Agents: ${run.agents.join(", ")}` : undefined,
462
+ ].filter((line): line is string => Boolean(line));
463
+ appendKnownArtifacts(lines, { outputPaths: [], sessionFile: run.sessionFile });
464
+ if (!run.sessionFile) {
465
+ appendTranscriptBody(lines, "Transcript tail", [], false);
466
+ return lines.join("\n");
467
+ }
468
+ const sessionTail = readSessionTranscriptTail(run.sessionFile, lineLimit, options.sessionRoots ?? []);
469
+ if (sessionTail.warnings.length) {
470
+ lines.push("Warnings:");
471
+ for (const warning of sessionTail.warnings) lines.push(` ${warning}`);
472
+ }
473
+ appendTranscriptBody(lines, `Session transcript tail from ${run.sessionFile}`, sessionTail.lines, false);
474
+ return lines.join("\n");
475
+ }
476
+
477
+ export function formatAsyncResultTranscript(data: {
478
+ id?: string;
479
+ runId?: string;
480
+ state?: string;
481
+ success?: boolean;
482
+ summary?: string;
483
+ output?: string;
484
+ sessionFile?: string;
485
+ agent?: string;
486
+ exitCode?: number | null;
487
+ results?: Array<{ agent?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null }>;
488
+ }, resultPath: string, options: TranscriptOptions = {}): string {
489
+ const lineLimit = transcriptLineLimit(options.lines);
490
+ const runId = data.runId ?? data.id ?? path.basename(resultPath, ".json");
491
+ const children = Array.isArray(data.results)
492
+ ? data.results
493
+ : data.agent
494
+ ? [{ agent: data.agent, output: data.output, summary: data.summary, sessionFile: data.sessionFile, state: data.state, success: data.success, exitCode: data.exitCode }]
495
+ : [];
496
+ let index = options.index;
497
+ if (index !== undefined && !Number.isInteger(index)) throw new Error("Transcript index must be an integer.");
498
+ if (index === undefined && children.length === 1) index = 0;
499
+ if (index !== undefined && (index < 0 || index >= children.length)) throw new Error(`Transcript index ${index} is out of range for ${children.length} result child${children.length === 1 ? "" : "ren"}.`);
500
+ const child = index !== undefined ? children[index] : undefined;
501
+ const output = index !== undefined
502
+ ? child?.output ?? child?.summary ?? (children.length === 1 ? data.output ?? data.summary : undefined) ?? ""
503
+ : data.output ?? data.summary ?? "";
504
+ const transcriptLines = output.split(/\r?\n/).slice(-lineLimit);
505
+ const sessionFile = child?.sessionFile ?? data.sessionFile;
506
+ const lines = [
507
+ `Run: ${runId}`,
508
+ `State: ${data.state ?? (data.success ? "complete" : "failed")}`,
509
+ index !== undefined && child ? `Child: ${index} (${child.agent ?? "subagent"})` : undefined,
510
+ index === undefined && children.length > 1 ? `Tip: pass index to inspect a specific child transcript (${children.map((candidate, childIndex) => `${childIndex}=${candidate.agent ?? "subagent"}`).join(", ")}).` : undefined,
511
+ ].filter((line): line is string => Boolean(line));
512
+ appendKnownArtifacts(lines, { outputPaths: [], sessionFile, resultPath });
513
+ appendTranscriptBody(lines, "Result transcript tail", transcriptLines.filter((line) => line.trim()), output.split(/\r?\n/).length > lineLimit);
514
+ return lines.join("\n");
515
+ }