@ferris1225/pi-subagents 6.0.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ /** Shared in-turn completion delivery for dispatches and completed-run follow-ups. */
2
+
3
+ import { Type } from "typebox";
4
+ import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
5
+ import { formatCompletionBlock } from "../presentation/format.ts";
6
+ import { monitor, statusLabel } from "../presentation/monitor.ts";
7
+ import type { SubagentRuntime } from "./runtime.ts";
8
+ import { projectResultsRoot } from "./thread-shared.ts";
9
+
10
+ export const WaitSchema = Type.Optional(Type.Boolean({
11
+ description: "Wait for runs started by this call and return their results once, after integration. Defaults to true in one-shot print/JSON sessions, false in TUI/RPC. Use true when the next step depends on the result; false to continue independent work. Cancelling the parent stops unfinished runs without background wake-ups.",
12
+ }));
13
+
14
+ /** In-turn wait for a new run or completed-run follow-up. Registration resolves it without a model-chosen
15
+ * timer; parent abort ends the wait and cancels its owned work. */
16
+ export async function awaitRunResults(
17
+ runtime: SubagentRuntime,
18
+ runIds: number[],
19
+ signal: AbortSignal | undefined,
20
+ maxResultLines: number,
21
+ fallbackCwd: string,
22
+ onProgress?: (text: string) => void,
23
+ ): Promise<string> {
24
+ const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
25
+ const already = runtime.settledRuns.get(runId);
26
+ if (already) return Promise.resolve({ result: already });
27
+ if (monitor.findRun(runId)?.status === "parked") {
28
+ return Promise.resolve({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
29
+ }
30
+ return new Promise((resolve) => {
31
+ let done = false;
32
+ let unsub: (() => void) | undefined;
33
+ const cleanup = (): void => {
34
+ if (unsub) unsub();
35
+ signal?.removeEventListener("abort", onAbort);
36
+ const listeners = runtime.settledListeners.get(runId);
37
+ if (listeners) {
38
+ listeners.delete(onSettled);
39
+ if (listeners.size === 0) runtime.settledListeners.delete(runId);
40
+ }
41
+ };
42
+ const finish = (outcome: { result?: SingleResult; note?: string }): void => {
43
+ if (done) return;
44
+ done = true;
45
+ cleanup();
46
+ resolve(outcome);
47
+ };
48
+ const onSettled = (result: SingleResult): void => finish({ result });
49
+ const onMonitor = (): void => {
50
+ const current = runtime.settledRuns.get(runId);
51
+ if (current) {
52
+ finish({ result: current });
53
+ return;
54
+ }
55
+ const live = monitor.findRun(runId);
56
+ if (live?.status === "parked") {
57
+ finish({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
58
+ return;
59
+ }
60
+ if (!live) {
61
+ // Removal is followed synchronously by registerRunResult in the
62
+ // finishing task; re-check on the next tick so the result wins.
63
+ setTimeout(() => {
64
+ const late = runtime.settledRuns.get(runId);
65
+ if (late) finish({ result: late });
66
+ else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
67
+ }, 0);
68
+ }
69
+ };
70
+ const onAbort = (): void => finish({ note: `Parent wait cancelled for run #${runId}; automatic cancellation stops unfinished child work. No additional subagent_stop is needed.` });
71
+ let listeners = runtime.settledListeners.get(runId);
72
+ if (!listeners) {
73
+ listeners = new Set();
74
+ runtime.settledListeners.set(runId, listeners);
75
+ }
76
+ listeners.add(onSettled);
77
+ unsub = monitor.subscribe(onMonitor);
78
+ if (signal?.aborted) onAbort();
79
+ else signal?.addEventListener("abort", onAbort, { once: true });
80
+ });
81
+ };
82
+ // One shared subscription drives the progress line: each waiter already
83
+ // subscribes for its own settlement, and the tool card wants a single
84
+ // rolled-up line rather than one per run.
85
+ let lastProgress: string | undefined;
86
+ const emitProgress = onProgress
87
+ ? (): void => {
88
+ const parts = runIds.map((id) => {
89
+ const settled = runtime.settledRuns.get(id);
90
+ if (settled) return `#${id} ${isFailedResult(settled) ? "failed" : "done"}`;
91
+ const live = monitor.findRun(id);
92
+ return live ? `#${id} ${statusLabel(live.status)}` : `#${id} …`;
93
+ });
94
+ const text = `Waiting in-turn on ${runIds.length} run${runIds.length === 1 ? "" : "s"} · ${parts.join(", ")}`;
95
+ // The monitor notifies on every usage and activity change; this line
96
+ // names only statuses, so most notifications leave it identical.
97
+ if (text === lastProgress) return;
98
+ lastProgress = text;
99
+ onProgress(text);
100
+ }
101
+ : undefined;
102
+ const progressUnsub = emitProgress ? monitor.subscribe(emitProgress) : undefined;
103
+ try {
104
+ emitProgress?.();
105
+ const outcomes = await Promise.all(runIds.map(waitForRun));
106
+ return outcomes.map((outcome) =>
107
+ outcome.result
108
+ ? formatCompletionBlock(outcome.result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, outcome.result.projectCwd ?? fallbackCwd) })
109
+ : (outcome.note ?? "(no outcome)"),
110
+ ).join("\n\n");
111
+ } finally {
112
+ progressUnsub?.();
113
+ }
114
+ }
@@ -28,6 +28,10 @@ export interface DispatchCore {
28
28
 
29
29
  export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
30
30
  const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
31
+ // Sweeps outlive the queue task which starts them. Drain every started pass
32
+ // before shutdown releases this runtime and its filesystem ownership.
33
+ let cleanupPending: Promise<void> = Promise.resolve();
34
+ runtime.shutdownHooks.push(() => cleanupPending);
31
35
 
32
36
  // Terminal rows stay in the monitor until the next beginTurn so the footer
33
37
  // can count them beside siblings that are still live. The widget ignores
@@ -46,7 +50,9 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
46
50
  if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
47
51
  // Settlement is the natural moment to reclaim disk: a burst of runs costs
48
52
  // one paced sweep, and every live or parked thread stays protected.
49
- void runAutomaticCleanup(runtime).catch(() => undefined);
53
+ if (runtime.sessionActive) {
54
+ cleanupPending = Promise.allSettled([cleanupPending, runAutomaticCleanup(runtime)]).then(() => undefined);
55
+ }
50
56
  if (opts?.silent || !runtime.sessionActive) return;
51
57
  const icon = status === "done" ? "✓" : "✗";
52
58
  const result = runtime.threads.get(runId)?.lastResult;
@@ -14,9 +14,9 @@
14
14
  */
15
15
 
16
16
  import { createHash, randomUUID } from "node:crypto";
17
- import { withManifestMutation } from "../isolation/manifest-mutation.ts";
17
+ import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
18
18
  import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
19
- import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
19
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
20
20
  import { uptime } from "node:os";
21
21
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
22
22
  import type { UsageStats } from "../execution/run-control.ts";
@@ -26,6 +26,7 @@ import type { SubagentThread } from "./runtime.ts";
26
26
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
27
27
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
28
28
  import { readRecoveryRecords, referencedRecoveryPaths } from "../isolation/recovery.ts";
29
+ import { isProcessAlive, readTempOwnerMarker } from "../isolation/temp-hygiene.ts";
29
30
  import {
30
31
  isPathInside,
31
32
  normalizeWorktreeSnapshot,
@@ -215,7 +216,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
215
216
  }
216
217
 
217
218
  interface ThreadManifestRead {
218
- valid: boolean;
219
219
  rolesMigrated?: boolean;
220
220
  sourceCount: number;
221
221
  records: ThreadRecord[];
@@ -223,12 +223,11 @@ interface ThreadManifestRead {
223
223
 
224
224
  async function readManifest(path: string): Promise<ThreadManifestRead> {
225
225
  try {
226
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
227
- if (!Array.isArray(parsed.records)) return { valid: false, sourceCount: 0, records: [] };
226
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
227
+ if (!Array.isArray(parsed?.records)) throw new Error(`Invalid thread manifest: ${path}`);
228
228
  let rolesMigrated = false;
229
229
  for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
230
230
  return {
231
- valid: true,
232
231
  rolesMigrated,
233
232
  sourceCount: parsed.records.length,
234
233
  records: parsed.records.flatMap((record) => {
@@ -236,8 +235,10 @@ async function readManifest(path: string): Promise<ThreadManifestRead> {
236
235
  return normalized ? [normalized] : [];
237
236
  }),
238
237
  };
239
- } catch {
240
- return { valid: false, sourceCount: 0, records: [] };
238
+ } catch (error) {
239
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { sourceCount: 0, records: [] };
240
+ // A failed read or corrupt document is not evidence that no records exist.
241
+ throw error;
241
242
  }
242
243
  }
243
244
 
@@ -277,8 +278,9 @@ async function validateThreadRecord(
277
278
  try {
278
279
  const [realWorktree, realCwd] = await Promise.all([realpath(worktree.worktreePath), realpath(worktree.cwd)]);
279
280
  if (!samePath(realCwd, join(realWorktree, relative(worktree.originalRoot, worktree.originalCwd)))) return false;
280
- } catch {
281
- return false;
281
+ } catch (error) {
282
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
283
+ throw error;
282
284
  }
283
285
  }
284
286
  // Managed recovery references survive a missing checkout or failed Git
@@ -329,8 +331,9 @@ function projectManifestPaths(durableRoot: string): string[] {
329
331
  return readdirSync(durableRoot, { withFileTypes: true })
330
332
  .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
331
333
  .map((entry) => join(durableRoot, entry.name, THREADS_MANIFEST_FILE_NAME));
332
- } catch {
333
- return [];
334
+ } catch (error) {
335
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
336
+ throw error;
334
337
  }
335
338
  }
336
339
 
@@ -342,7 +345,7 @@ export async function readThreadRecords(configPath: string): Promise<ThreadRecor
342
345
  .map((path) => withManifestMutation(path, async () => {
343
346
  const manifest = await readManifest(path);
344
347
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
345
- if (!manifest.valid || manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
348
+ if (manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
346
349
  return validated;
347
350
  })),
348
351
  );
@@ -362,7 +365,7 @@ async function writeManifest(path: string, records: readonly ThreadRecord[]): Pr
362
365
  records: [...records],
363
366
  };
364
367
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
365
- await rename(temporaryPath, path);
368
+ await replaceManifestFile(temporaryPath, path);
366
369
  } finally {
367
370
  await rm(temporaryPath, { force: true }).catch(() => undefined);
368
371
  }
@@ -500,13 +503,16 @@ export async function pruneThreadRecords(
500
503
  await withManifestMutation(path, async () => {
501
504
  const manifest = await readManifest(path);
502
505
  const records = manifest.records;
503
- if (manifest.valid && records.length === 0) return;
506
+ if (manifest.sourceCount === 0) return;
504
507
  const validity = await Promise.all(records.map((record) => validateThreadRecord(configPath, path, record)));
505
- let changed = !manifest.valid || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
508
+ let changed = Boolean(manifest.rolesMigrated) || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
506
509
  const kept: ThreadRecord[] = [];
507
510
  for (const [index, record] of records.entries()) {
508
511
  if (!validity[index]) continue;
509
- if (now - record.updatedAt <= PARKED_RECORD_MAX_AGE_MS) {
512
+ const live = isCurrentBoot(record) && (
513
+ (record.ownerPid !== undefined && isProcessAlive(record.ownerPid)) || record.childPids.some(isProcessAlive)
514
+ );
515
+ if (live || now - record.updatedAt <= PARKED_RECORD_MAX_AGE_MS) {
510
516
  kept.push(record);
511
517
  continue;
512
518
  }
@@ -556,6 +562,8 @@ function isIdleSince(root: string, cutoffMs: number, now: number): boolean {
556
562
  const stack: string[] = [root];
557
563
  while (stack.length > 0) {
558
564
  const dir = stack.pop()!;
565
+ const owner = readTempOwnerMarker(dir);
566
+ if (owner && isProcessAlive(owner.pid)) return false;
559
567
  let entries: Dirent[];
560
568
  try {
561
569
  entries = readdirSync(dir, { withFileTypes: true });
@@ -24,7 +24,7 @@ import {
24
24
  import { type ThinkingLevel } from "../configuration/config.ts";
25
25
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
26
26
  import { isRunActiveStatus, monitor, type RunWorkflowTag } from "../presentation/monitor.ts";
27
- import type { RunControl } from "../execution/run-control.ts";
27
+ import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
28
28
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
29
29
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
30
30
  import type { WorkflowRun } from "../workflow/state.ts";
@@ -58,6 +58,8 @@ export interface SubagentThread {
58
58
  restorationRecord?: ThreadRecord;
59
59
  state: ThreadState;
60
60
  control: RunControl;
61
+ /** Last child acknowledgement; queued delivery does not prove model execution. */
62
+ lastSteering?: SteeringReceipt & { message: string };
61
63
  queueController?: AbortController;
62
64
  /** Resolves after the child, isolation finalization, and queue work fully quiesce. */
63
65
  generationCompletion: Promise<void>;
@@ -129,10 +129,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
129
129
  // owner and leaves the caller with no way forward.
130
130
  const owner = duplicate.source;
131
131
  const remedy = owner.state === "parked" || owner.retired
132
- ? `That run was interrupted (possibly in an earlier session) and keeps the phase claimed; retire it with subagent_stop({ id: ${owner.id} }) to reuse the phase, or give this work a different phaseId. Main handles follow-up work.`
133
- : owner.state === "completed" || owner.state === "failed"
134
- ? "Inspect it with subagent_status; a different deliverable needs a different phaseId. Main handles follow-up work."
135
- : "Do not redispatch it; inspect its result or let it finish. Main handles follow-up work.";
132
+ ? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused. Changing only phaseId cannot bypass equal-task ownership.`
133
+ : owner.state === "completed"
134
+ ? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief and phaseId.`
135
+ : owner.state === "failed"
136
+ ? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
137
+ : "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
136
138
  return failedStartResult(agentName, task,
137
139
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
138
140
  }
@@ -21,7 +21,6 @@ import {
21
21
  getProjectRoot,
22
22
  getSubagentsRoot,
23
23
  RunControl,
24
- sessionExists,
25
24
  sweepProjectResultArtifacts,
26
25
  type SingleResult,
27
26
  } from "../execution/spawn.ts";
@@ -107,18 +106,14 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
107
106
  if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) {
108
107
  record = { ...record, durableId: identity, runId: monitor.reserveRunId() };
109
108
  }
110
- // Freeze a legacy identity before dropping missing session metadata.
109
+ // Keep validated recovery paths even when their files are temporarily
110
+ // missing or unreadable. Availability is checked when a session is used.
111
111
  record = { ...record, durableId: identity };
112
- const sessionValid =
113
- record.sessionId !== undefined &&
114
- record.sessionDir !== undefined &&
115
- sessionExists(record.sessionDir, record.sessionId);
116
- const restoredRecord = sessionValid ? record : { ...record, sessionId: undefined, sessionDir: undefined };
117
112
  const worktree = record.worktree && await isThreadSourceAvailable(record)
118
113
  ? await restoreWorktreeIsolation(record.worktree).catch(() => undefined)
119
114
  : undefined;
120
115
  const restorationFailed = record.isolation === "worktree" && record.worktree !== undefined && !worktree;
121
- const thread = createRestoredThread(runtime, restoredRecord, worktree, restorationFailed ? "failed" : "parked");
116
+ const thread = createRestoredThread(runtime, record, worktree, restorationFailed ? "failed" : "parked");
122
117
  runtime.threads.set(record.runId, thread);
123
118
  if (thread.sessionDir) runtime.sessionDirs.add(thread.sessionDir);
124
119
  if (restorationFailed) {
@@ -184,16 +179,17 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
184
179
  return restoredIds;
185
180
  }
186
181
 
187
- /** Session-start durable bootstrap: restore threads, age out expired records, and
188
- * sweep leaked temp/state directories. Every stage is best-effort so a broken
189
- * manifest never blocks the session.
190
- *
191
- * Restore is published on the runtime as `durableRestore` before this returns,
192
- * so callers that must see restored threads await that pass alone and never the
193
- * hygiene sweeps behind it. Hygiene still runs after restore: pruning decides
194
- * what to delete from the records restore has already claimed. */
182
+ /** Age out expired records before restoring threads, then sweep leaked state.
183
+ * Each stage is best-effort so a broken manifest never blocks the session.
184
+ * `durableRestore` includes pruning: callers cannot see a restored owner whose
185
+ * checkpoint the same startup is about to delete. Later sweeps run separately. */
195
186
  export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Promise<void> {
196
187
  const restore = (async () => {
188
+ try {
189
+ await pruneThreadRecords(runtime.configPath);
190
+ } catch {
191
+ /* unreadable recovery references remain protected */
192
+ }
197
193
  try {
198
194
  runtime.restoredRunIds = await restoreDurableThreads(runtime, cwd);
199
195
  } catch {
@@ -203,11 +199,6 @@ export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Pr
203
199
  runtime.durableRestore = restore;
204
200
  return (async () => {
205
201
  await restore;
206
- try {
207
- await pruneThreadRecords(runtime.configPath);
208
- } catch {
209
- /* retention is best-effort */
210
- }
211
202
  const projectRoots = getSubagentsRoot(runtime.configPath);
212
203
  try {
213
204
  sweepProjectTempDirs(projectRoots);
@@ -1,17 +1,19 @@
1
- /** Read-only run inspection and destructive cancellation of one-shot runs. */
1
+ /** Run inspection, steering, completed-run follow-ups, and destructive cancellation. */
2
2
 
3
3
  import { randomUUID } from "node:crypto";
4
- import { copyFile, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
5
- import { join } from "node:path";
4
+ import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
5
+ import { basename, join } from "node:path";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import { Text } from "@earendil-works/pi-tui";
9
9
  import { Type } from "typebox";
10
10
  import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
11
11
  import { loadBuiltinAgents } from "../delegation/agents.ts";
12
- import { getProjectRoot, getResultOutput, sessionExists } from "../execution/spawn.ts";
12
+ import { findSessionFile, getProjectRoot, getResultOutput, isFailedResult, sessionExists } from "../execution/spawn.ts";
13
13
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
14
14
  import type { DispatchCore } from "./dispatch-core.ts";
15
+ import { awaitRunResults, WaitSchema } from "./await-results.ts";
16
+ import { cancelActiveWork } from "./cancellation.ts";
15
17
  import { stopThreads } from "./stop.ts";
16
18
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
17
19
  import { emptyUsage } from "../execution/run-control.ts";
@@ -124,6 +126,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
124
126
  waitReason: state === "queued" ? live?.waitReason : undefined,
125
127
  activity: live?.activity,
126
128
  recentActivity: live?.recentActivity ?? [],
129
+ lastSteering: thread.lastSteering,
127
130
  elapsedMs: monitor.getElapsedMs(thread.id) ?? thread.elapsedMs,
128
131
  model: live?.model ?? result?.model,
129
132
  thinking: live?.thinking ?? result?.thinking ?? thread.thinkingLevel,
@@ -133,6 +136,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
133
136
  errorMessage: result ? getResultError(result) : state === "failed" ? "No failure reason was recorded." : undefined,
134
137
  resultFile: result?.resultFile,
135
138
  sessionDir: thread.retired ? undefined : thread.sessionDir ?? result?.sessionDir,
139
+ followUpContext: state === "completed"
140
+ ? thread.sessionDir && thread.sessionId && sessionExists(thread.sessionDir, thread.sessionId) ? "session" : "summary"
141
+ : undefined,
136
142
  isolation: thread.isolation,
137
143
  isolationNote: result?.isolationNote,
138
144
  integrationStatus: live?.integrationStatus ?? result?.integrationStatus ?? thread.worktree?.state,
@@ -149,6 +155,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
149
155
  if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
150
156
  if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
151
157
  if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
158
+ if (run.lastSteering) lines.push(` last steering: ${run.lastSteering.disposition} · acknowledged ${formatDuration(Math.max(0, Date.now() - run.lastSteering.acknowledgedAt))} ago${run.lastSteering.requestId ? ` · request ${run.lastSteering.requestId}` : ""} · ${run.lastSteering.message}`);
159
+ if (run.followUpContext) lines.push(` follow-up: ${run.followUpContext}${run.followUpContext === "summary" ? " (retained session unavailable)" : " available"}`);
152
160
  // The trail is the progress answer: what the run has been doing,
153
161
  // newest last. It replaces pointing the parent at child session
154
162
  // files, which it cannot usefully read mid-run.
@@ -216,65 +224,114 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
216
224
  pi.registerTool({
217
225
  name: "subagent_message",
218
226
  label: "Subagent Message",
219
- description: "Send a steering message to a running subagent, or continue a completed run. Use context \"session\" (default) to redo or revise the same work: it continues a private copy of the retained session, so earlier reasoning and the provider prompt-cache key survive. Use context \"summary\" for a new next step: it starts fresh with a bounded summary (objective, result, touched files) instead of loading the old transcript. Running messages are queued by Pi and acknowledged, not guaranteed to have been acted on yet.",
227
+ description: "Send a steering message to a running subagent, or continue a successfully completed run. Omit context or use \"auto\" to reuse its retained session when available and otherwise start from a bounded summary, reporting the fallback. Use \"session\" only when full history is required; missing history is an error. Use \"summary\" for a new next step with only the earlier objective, result, and touched files. Session copies preserve history and the provider cache key; summary runs have neither. Use wait:true to receive a completed-run follow-up in this call; one-shot print/JSON sessions wait by default. Steering waits for the child RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown. Receipt is not proof of model execution; status retains the latest acknowledgement.",
220
228
  exposure: "model-only",
221
- executionMode: "sequential",
229
+ executionMode: "parallel",
222
230
  parameters: Type.Object({
223
231
  id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
224
232
  message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
225
- context: Type.Optional(Type.String({ enum: ["session", "summary"], description: "session (default) continues the retained session, preserving its history and provider prompt-cache key. summary starts a fresh run briefed with a bounded summary of the earlier work: cheaper context, no cache reuse, and no access to details the summary omits." })),
233
+ context: Type.Optional(Type.String({ enum: ["auto", "session", "summary"], description: "auto (default) uses the retained session when available, otherwise a bounded summary and reports the fallback. session requires the full retained history and fails if unavailable. summary always starts fresh with the earlier objective, result, and touched files; no history or cache reuse." })),
234
+ wait: WaitSchema,
226
235
  }),
227
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
236
+ async execute(_toolCallId, params, _signal, onUpdate, ctx) {
228
237
  await runtime.durableRestore;
229
238
  const thread = runtime.threads.get(params.id);
230
239
  const fail = (message: string) => ({ content: [{ type: "text" as const, text: message }], details: {}, isError: true });
240
+ if (_signal?.aborted) return fail("Subagent message cancelled before delivery.");
231
241
  if (!thread || thread.retired) return fail(`No available run matches #${params.id} in this session.`);
232
242
  if (thread.state === "running" && !thread.lifecycleOperation) {
233
243
  try {
234
- await thread.control.steer(params.message);
235
- return { content: [{ type: "text" as const, text: `Steering queued for #${thread.id}; it has not necessarily been acted on yet.` }], details: { id: thread.id } };
236
- } catch (error) { return fail(`Could not send to #${thread.id}: ${error instanceof Error ? error.message : String(error)}`); }
244
+ const receipt = await thread.control.steer(params.message);
245
+ thread.lastSteering = { ...receipt, message: formatTaskSummary(params.message, 160, false) };
246
+ const status = receipt.disposition === "queued"
247
+ ? `Received by #${thread.id} · queued for the next steering boundary. Model execution is not yet confirmed.`
248
+ : receipt.disposition === "handled"
249
+ ? `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`
250
+ : `Accepted by #${thread.id} · queue state unconfirmed. Model execution is not yet confirmed.`;
251
+ monitor.setActivity(thread.id, `steering ${receipt.disposition}`);
252
+ return {
253
+ content: [{ type: "text" as const, text: `${status}${receipt.requestId ? `\nChild RPC acknowledgement: ${receipt.requestId}` : ""}` }],
254
+ details: { id: thread.id, steering: thread.lastSteering },
255
+ };
256
+ } catch (error) { return fail(`Steering to #${thread.id} was not confirmed: ${error instanceof Error ? error.message : String(error)}`); }
237
257
  }
238
258
  if (thread.state !== "completed" || thread.lifecycleOperation) {
239
- return fail(`Run #${thread.id} is ${thread.state}; wait for a running or successfully completed run.`);
259
+ const state = thread.state === "parked" ? "interrupted" : thread.state;
260
+ const terminal = !thread.lifecycleOperation && ["parked", "failed", "stopped"].includes(thread.state);
261
+ return fail(`Run #${thread.id} is ${state}; ${terminal
262
+ ? "inspect retained results with subagent_status and handle unfinished work in main. This run cannot be continued with subagent_message."
263
+ : "messages require a running or successfully completed run. Results arrive automatically."}`);
240
264
  }
241
265
  if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
242
- const useSummary = params.context === "summary";
243
- if (!useSummary && (!thread.sessionDir || !thread.sessionId || !sessionExists(thread.sessionDir, thread.sessionId))) {
244
- return fail(`Run #${thread.id} has no available session to continue; retry with context: "summary".`);
266
+ const context = params.context ?? "auto";
267
+ const sourceFile = context !== "summary" && thread.sessionDir && thread.sessionId
268
+ ? findSessionFile(thread.sessionDir, thread.sessionId) : undefined;
269
+ if (context === "session" && !sourceFile) {
270
+ return fail(`Run #${thread.id} has no available session to continue; use context: "auto" or "summary" for a bounded summary without the earlier history.`);
245
271
  }
272
+ let fallbackReason = context === "auto" && !sourceFile ? "Retained session is unavailable." : undefined;
246
273
  let copyDir: string | undefined;
247
274
  try {
248
275
  dispatchCore.setEnvironment({ ctx, config: await loadConfig(runtime.configPath), agents: loadBuiltinAgents() });
249
- if (useSummary) {
250
- const task = buildSummaryFollowUp(thread, params.message);
251
- const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
252
- phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
253
- });
254
- if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
255
- return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with a summary only; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
276
+ if (sourceFile) {
277
+ const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
278
+ await mkdir(root, { recursive: true });
279
+ copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
280
+ writeTempOwnerMarker(copyDir);
281
+ try {
282
+ await copyFile(sourceFile, join(copyDir, basename(sourceFile)));
283
+ } catch (error) {
284
+ const code = (error as NodeJS.ErrnoException).code;
285
+ if (context !== "auto" || (code !== "ENOENT" && code !== "ENOTDIR")) throw error;
286
+ await rm(copyDir, { recursive: true, force: true });
287
+ copyDir = undefined;
288
+ fallbackReason = "Retained session became unavailable before it could be copied.";
289
+ }
256
290
  }
257
- const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
258
- await mkdir(root, { recursive: true });
259
- copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
260
- writeTempOwnerMarker(copyDir);
261
- const file = (await readdir(thread.sessionDir!)).find((name) => name.endsWith(`_${thread.sessionId}.jsonl`));
262
- if (!file) throw new Error("The retained session file is missing; retry with context: \"summary\".");
263
- await copyFile(join(thread.sessionDir!, file), join(copyDir, file));
264
- if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while its session was copied.");
265
- const task = `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`;
291
+ if (_signal?.aborted) throw new Error("Follow-up cancelled before dispatch.");
292
+ if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while the follow-up was prepared.");
293
+ const selectedContext = copyDir ? "session" : "summary";
294
+ const task = copyDir
295
+ ? `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`
296
+ : buildSummaryFollowUp(thread, params.message);
297
+ const wait = params.wait ?? (ctx.hasUI === false);
266
298
  const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
267
299
  phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
268
- resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir },
300
+ deliveryRoute: wait ? "await" : "background",
301
+ ...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
269
302
  });
270
303
  if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
271
304
  copyDir = undefined;
272
- return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with its retained session; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
305
+ const contextNote = selectedContext === "session" ? "its retained session" : "a summary only";
306
+ const receipt = `Follow-up #${result.runId} from #${thread.id} with ${contextNote}${fallbackReason ? ` (${fallbackReason})` : ""}`;
307
+ const details = { id: result.runId, sourceId: thread.id, context: selectedContext, ...(fallbackReason ? { fallbackReason } : {}) };
308
+ if (wait) {
309
+ const blocks = await awaitRunResults(runtime, [result.runId], _signal, DEFAULT_MAX_RESULT_LINES, thread.cwd, (text) => {
310
+ onUpdate?.({ content: [{ type: "text", text }], details });
311
+ });
312
+ if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
313
+ else runtime.completeAwaitDelivery([result.runId]);
314
+ const settled = runtime.settledRuns.get(result.runId);
315
+ return {
316
+ content: [{ type: "text" as const, text: `${receipt}\n\n${blocks}` }], details,
317
+ ...(_signal?.aborted || !settled || isFailedResult(settled) ? { isError: true } : {}),
318
+ };
319
+ }
320
+ return {
321
+ content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically. Continue independent work, then use the result to finish the task.` }], details,
322
+ };
273
323
  } catch (error) {
274
324
  if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
275
325
  return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
276
326
  }
277
327
  },
328
+ renderCall(args, theme) {
329
+ return new Text(`${theme.fg("toolTitle", theme.bold("subagent_message "))}${theme.fg("accent", `#${args.id ?? "?"}`)} ${theme.fg("dim", formatTaskSummary(args.message ?? "", 80, false))}`, 0, 0);
330
+ },
331
+ renderResult(result, options, theme) {
332
+ if (options.expanded) return new Text(result.content.map((part) => part.type === "text" ? part.text : "").join("\n"), 0, 0);
333
+ return renderFirstLine(result, "subagent_message ", theme);
334
+ },
278
335
  });
279
336
 
280
337
  // Cancel one or more active runs: aborts the queue controller, which
@@ -35,8 +35,14 @@ async function removeUnavailableAgentModels(
35
35
  export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
36
36
  pi.on("session_start", async (_event, ctx) => {
37
37
  await ensureDefaultConfig(ctx, runtime.configPath);
38
- await relocateRecoveryManifest(runtime.configPath);
39
- await announceRecoveryRecords(runtime.configPath, ctx);
38
+ try {
39
+ await relocateRecoveryManifest(runtime.configPath);
40
+ await announceRecoveryRecords(runtime.configPath, ctx);
41
+ } catch (error) {
42
+ // Recovery readers must fail closed for cleanup, but a failed notice
43
+ // must not prevent the rest of the session UI from being installed.
44
+ ctx.ui.notify(`pi-subagents: recovery inspection failed; continuing startup: ${error instanceof Error ? error.message : String(error)}`, "warning");
45
+ }
40
46
  await removeUnavailableAgentModels(ctx, runtime);
41
47
  // Bootstrap also runs on session_start; wait so this notice sees restored
42
48
  // threads instead of racing an empty list.
@@ -15,9 +15,9 @@
15
15
  */
16
16
 
17
17
  import { createHash } from "node:crypto";
18
- import { withManifestMutation } from "../isolation/manifest-mutation.ts";
18
+ import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
19
19
  import { readdirSync } from "node:fs";
20
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
20
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
21
21
  import { dirname, isAbsolute, join, resolve } from "node:path";
22
22
  import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
23
23
  import { PARKED_RECORD_MAX_AGE_MS } from "../lifecycle/durable.ts";
@@ -154,7 +154,7 @@ async function writeManifest(path: string, records: readonly WorkflowRecord[]):
154
154
  try {
155
155
  const manifest: WorkflowsManifest = { version: WORKFLOWS_MANIFEST_VERSION, records: [...records] };
156
156
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
157
- await rename(temporaryPath, path);
157
+ await replaceManifestFile(temporaryPath, path);
158
158
  } finally {
159
159
  await rm(temporaryPath, { force: true }).catch(() => undefined);
160
160
  }