@ferris1225/pi-subagents 4.3.34 → 5.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +55 -359
  2. package/README.md +163 -553
  3. package/index.ts +28 -3
  4. package/package.json +2 -2
  5. package/skills/workflow/SKILL.md +46 -29
  6. package/src/configuration/config.ts +15 -5
  7. package/src/configuration/setup.ts +79 -228
  8. package/src/configuration/ui.ts +249 -128
  9. package/src/delegation/agents.ts +4 -3
  10. package/src/delegation/builtin-agents.ts +34 -10
  11. package/src/delegation/dispatch.ts +9 -6
  12. package/src/delegation/prompt.ts +13 -9
  13. package/src/execution/cli-run.ts +404 -0
  14. package/src/execution/process-tree.ts +1 -1
  15. package/src/execution/{rpc-control.ts → run-control.ts} +23 -33
  16. package/src/execution/spawn.ts +33 -185
  17. package/src/isolation/cleanup.ts +174 -0
  18. package/src/isolation/temp-hygiene.ts +2 -26
  19. package/src/lifecycle/cancellation.ts +36 -0
  20. package/src/lifecycle/completion.ts +1 -1
  21. package/src/lifecycle/dispatch-core.ts +0 -1
  22. package/src/lifecycle/durable.ts +5 -1
  23. package/src/lifecycle/runtime.ts +42 -29
  24. package/src/lifecycle/stop.ts +176 -0
  25. package/src/lifecycle/thread-lifecycle.ts +14 -14
  26. package/src/lifecycle/thread-restore.ts +12 -15
  27. package/src/lifecycle/thread-shared.ts +2 -0
  28. package/src/lifecycle/tools.ts +145 -181
  29. package/src/presentation/format.ts +2 -5
  30. package/src/presentation/monitor.ts +16 -1
  31. package/src/presentation/widget.ts +141 -175
  32. package/src/workflow/engine.ts +68 -34
  33. package/src/workflow/files.ts +10 -32
  34. package/src/workflow/plan.ts +61 -13
  35. package/src/workflow/state.ts +4 -3
  36. package/src/workflow/tool.ts +23 -12
  37. package/workflows/code-review.md +15 -10
  38. package/workflows/migration.md +14 -26
  39. package/workflows/research.md +6 -5
  40. package/src/execution/rpc-run.ts +0 -889
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
+ import { findDuplicateDispatch } from "../delegation/prompt.ts";
12
13
  import type { PhaseScope } from "../delegation/phase-scope.ts";
13
14
  import { rmSync } from "node:fs";
14
15
  import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
@@ -21,8 +22,8 @@ import {
21
22
  } from "./completion.ts";
22
23
  import { type ThinkingLevel } from "../configuration/config.ts";
23
24
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
24
- import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
25
- import type { RpcRunControl } from "../execution/rpc-control.ts";
25
+ import { isRunActiveStatus, monitor, type RunWorkflowTag } from "../presentation/monitor.ts";
26
+ import type { RunControl } from "../execution/run-control.ts";
26
27
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
27
28
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
28
29
  import type { WorkflowRun } from "../workflow/state.ts";
@@ -40,6 +41,8 @@ export interface SubagentThread {
40
41
  scope?: PhaseScope;
41
42
  /** Capability snapshot used by declared-scope admission, including after restore. */
42
43
  writeCapable?: boolean;
44
+ /** Live graph membership; graph summaries own delivery for these runs. */
45
+ workflow?: RunWorkflowTag;
43
46
  /** Caller-facing cwd in the original worktree. */
44
47
  cwd: string;
45
48
  /** Actual child cwd (the equivalent path inside an isolated worktree). */
@@ -51,7 +54,7 @@ export interface SubagentThread {
51
54
  /** Original durable evidence retained when its worktree handle is unavailable. */
52
55
  restorationRecord?: ThreadRecord;
53
56
  state: ThreadState;
54
- control: RpcRunControl;
57
+ control: RunControl;
55
58
  queueController?: AbortController;
56
59
  /** Resolves after the child, isolation finalization, and queue work fully quiesce. */
57
60
  generationCompletion: Promise<void>;
@@ -83,6 +86,9 @@ export interface SubagentRuntime {
83
86
  getToolInfos: () => ToolInfo[];
84
87
  /** False after session_shutdown; guards delivery and queue work. */
85
88
  sessionActive: boolean;
89
+ /** Cancelling a parent must not wake it again with old child results. */
90
+ suppressCompletions: boolean;
91
+ discardCompletions: () => void;
86
92
  /** Resolves when the load-time durable restore pass has finished. Everything
87
93
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
88
94
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -103,8 +109,6 @@ export interface SubagentRuntime {
103
109
  publishRunCompletion: (runId: number, item: CompletionMessageItem, immediate: boolean) => void;
104
110
  /** Mark awaited results as returned in the tool response. */
105
111
  completeAwaitDelivery: (runIds: readonly number[]) => void;
106
- /** Transfer aborted awaited calls back to completion delivery. */
107
- fallbackAwaitDelivery: (runIds: readonly number[]) => void;
108
112
  completionBatcher: CompletionBatcher<CompletionMessageItem>;
109
113
  /** Abort controllers per active run, so subagent_stop can cancel a run in-turn. */
110
114
  runControllers: Map<number, AbortController>;
@@ -133,6 +137,26 @@ export interface SubagentRuntime {
133
137
  shutdown: () => Promise<void>;
134
138
  }
135
139
 
140
+ /** Pending nodes reserve their phases before they allocate ordinary run ids. */
141
+ export function findPendingWorkflowPhase(
142
+ runtime: Pick<SubagentRuntime, "workflows">,
143
+ task: string,
144
+ cwd: string,
145
+ phaseId?: string,
146
+ excludeWorkflowId?: number,
147
+ ): { workflowId: number; nodeId: string; agent: string } | undefined {
148
+ for (const graph of runtime.workflows.values()) {
149
+ if (graph.state !== "running" || graph.id === excludeWorkflowId) continue;
150
+ for (const node of graph.nodes) {
151
+ if (node.state !== "pending" && !(node.state === "running" && node.runId === undefined)) continue;
152
+ if (findDuplicateDispatch([{ id: graph.id, agentName: node.agent, task: node.task, cwd: node.cwd, phaseId: node.phaseId, state: "queued" }], task, cwd, phaseId)) {
153
+ return { workflowId: graph.id, nodeId: node.id, agent: node.agent };
154
+ }
155
+ }
156
+ }
157
+ return undefined;
158
+ }
159
+
136
160
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
137
161
  const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
138
162
  let nextWorkflowId = 1;
@@ -143,22 +167,24 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
143
167
  let compactionInFlight = false;
144
168
  let heldCompletions: CompletionMessageItem[] = [];
145
169
 
146
- const runDeliveries = new Map<number, {
147
- route: "background" | "await";
148
- completion?: CompletionMessageItem;
149
- immediate: boolean;
150
- }>();
170
+ const runDeliveries = new Map<number, "background" | "await">();
151
171
  const runtime: SubagentRuntime = {
152
172
  configPath,
153
173
  backgroundQueue,
154
174
  getActiveTools: () => pi.getActiveTools(),
155
175
  getToolInfos: () => pi.getAllTools(),
156
176
  sessionActive: true,
177
+ suppressCompletions: false,
178
+ discardCompletions: () => {
179
+ runtime.completionBatcher.dispose();
180
+ heldCompletions = [];
181
+ runDeliveries.clear();
182
+ },
157
183
  durableRestore: Promise.resolve(),
158
184
  restoredRunIds: [],
159
185
  restoredNotified: false,
160
186
  sendCompletionGroup: (items) => {
161
- if (!runtime.sessionActive || items.length === 0) return;
187
+ if (!runtime.sessionActive || runtime.suppressCompletions || items.length === 0) return;
162
188
  // Direct (immediate-failure/stop) delivery must follow successes already
163
189
  // held by the debounce batcher. A batcher's own emit sees an empty batch.
164
190
  runtime.completionBatcher?.flush();
@@ -190,14 +216,11 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
190
216
  pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
191
217
  },
192
218
  claimRunDelivery: (runId, route) => {
193
- runDeliveries.set(runId, { route, immediate: false });
219
+ runDeliveries.set(runId, route);
194
220
  },
195
221
  publishRunCompletion: (runId, item, immediate) => {
196
- const delivery = runDeliveries.get(runId) ?? { route: "background" as const, immediate: false };
197
- delivery.completion = item;
198
- delivery.immediate = immediate;
199
- runDeliveries.set(runId, delivery);
200
- if (delivery.route === "await") return;
222
+ if (runtime.suppressCompletions) { runDeliveries.delete(runId); return; }
223
+ if (runDeliveries.get(runId) === "await") return;
201
224
  runDeliveries.delete(runId);
202
225
  if (immediate) {
203
226
  runtime.sendCompletionGroup([item]);
@@ -207,20 +230,10 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
207
230
  },
208
231
  completeAwaitDelivery: (runIds) => {
209
232
  for (const runId of runIds) {
210
- const delivery = runDeliveries.get(runId);
211
- if (delivery?.route === "await") runDeliveries.delete(runId);
212
- }
213
- },
214
- fallbackAwaitDelivery: (runIds) => {
215
- for (const runId of runIds) {
216
- const delivery = runDeliveries.get(runId);
217
- if (!delivery || delivery.route !== "await") continue;
218
- delivery.route = "background";
219
- if (delivery.completion) {
220
- runtime.publishRunCompletion(runId, delivery.completion, delivery.immediate);
221
- }
233
+ if (runDeliveries.get(runId) === "await") runDeliveries.delete(runId);
222
234
  }
223
235
  },
236
+
224
237
  completionBatcher: undefined as unknown as CompletionBatcher<CompletionMessageItem>,
225
238
  runControllers: new Map<number, AbortController>(),
226
239
  settledRuns: new Map<number, SingleResult>(),
@@ -0,0 +1,176 @@
1
+ /** Shared destructive stop: claim every lifecycle before awaiting child or Git cleanup. */
2
+
3
+ import { existsSync } from "node:fs";
4
+ import { emptyUsage } from "../execution/run-control.ts";
5
+ import type { SingleResult } from "../execution/spawn.ts";
6
+ import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
7
+ import type { WorktreeFinalization } from "../isolation/worktree.ts";
8
+ import { monitor } from "../presentation/monitor.ts";
9
+ import { removeThreadRecord } from "./durable.ts";
10
+ import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
11
+ import { CONTROL_QUIESCE_TIMEOUT_MS, quiesced } from "./thread-shared.ts";
12
+
13
+ export async function stopThreads(runtime: SubagentRuntime, targets: readonly number[], reason?: string) {
14
+ const completionResults: SingleResult[] = [];
15
+ const claimed: Array<{
16
+ runId: number;
17
+ thread: SubagentThread;
18
+ run: ReturnType<typeof monitor.findRun>;
19
+ previousState: SubagentThread["state"];
20
+ wasQueued: boolean;
21
+ wasActive: boolean;
22
+ generation: number;
23
+ controller: AbortController | undefined;
24
+ completion: Promise<void>;
25
+ stopVersion: number;
26
+ stopMessage: string;
27
+ }> = [];
28
+ for (const runId of targets) {
29
+ const thread = runtime.threads.get(runId);
30
+ if (!thread) continue;
31
+ const previousState = thread.state;
32
+ const wasQueued = previousState === "queued";
33
+ const wasActive = thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(previousState);
34
+ const stopVersion = ++thread.lifecycleVersion;
35
+ thread.lifecycleOperation = "stop";
36
+ thread.retired = true;
37
+ thread.retireOnSettle = true;
38
+ thread.state = "stopped";
39
+ const stopMessage = reason ?? (wasQueued
40
+ ? "Stopped by subagent_stop before the run started."
41
+ : wasActive ? "Stopped by subagent_stop."
42
+ : previousState === "parked" ? "Stopped by subagent_stop from an interrupted checkpoint."
43
+ : "Retired by subagent_stop.");
44
+ claimed.push({
45
+ runId, thread, run: monitor.findRun(runId), previousState, wasQueued, wasActive,
46
+ generation: thread.generation,
47
+ controller: thread.queueController,
48
+ completion: thread.generationCompletion,
49
+ stopVersion, stopMessage,
50
+ });
51
+ }
52
+
53
+ // Interrupt every claimed generation before awaiting any one of them.
54
+ // An isolated stop may need the repository lane for final integration;
55
+ // cancelling all holders first prevents stop-all from waiting behind a
56
+ // later shared workflow that this same operation has not interrupted yet.
57
+ const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
58
+ const stopping = thread.control.stop(stopMessage).catch(() => undefined);
59
+ runtime.backgroundQueue.cancel(controller);
60
+ return stopping;
61
+ });
62
+
63
+ const stopped: string[] = [];
64
+ const retainedIntegration: string[] = [];
65
+ const pendingIntegration: string[] = [];
66
+ for (const [claimIndex, claim] of claimed.entries()) {
67
+ const {
68
+ runId,
69
+ thread,
70
+ run,
71
+ previousState,
72
+ wasQueued,
73
+ wasActive,
74
+ generation,
75
+ controller,
76
+ completion,
77
+ stopVersion,
78
+ stopMessage,
79
+ } = claim;
80
+ // Every wait here is bounded: the queue task can sit for minutes in
81
+ // worktree finalization or behind the managed repository lane, and an
82
+ // unkillable child can stall even process termination. Stop owns the
83
+ // lifecycle synchronously, so a stuck tail settles silently after we
84
+ // proceed; none of its late paths can publish a second result.
85
+ await quiesced(interruptionPromises[claimIndex]);
86
+ if (!(await quiesced(completion))) runtime.backgroundQueue.cancel(controller);
87
+ if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
88
+ if (thread.queueController === controller) thread.queueController = undefined;
89
+
90
+ // Dispatch yields publication ownership as soon as stop claims the
91
+ // lifecycle. Synthesize and publish the one aborted result here only when
92
+ // this stop actually interrupted unfinished work.
93
+ let stoppedResult: SingleResult | undefined;
94
+ if (
95
+ wasQueued ||
96
+ previousState === "parked" ||
97
+ !runtime.settledRuns.has(runId)
98
+ ) {
99
+ const prior = thread.lastResult;
100
+ stoppedResult = prior
101
+ ? {
102
+ ...prior,
103
+ exitCode: 1,
104
+ stopReason: "aborted",
105
+ errorMessage: stopMessage,
106
+ runId,
107
+ }
108
+ : {
109
+ agent: thread.agentName,
110
+ task: thread.task,
111
+ exitCode: 1,
112
+ messages: [],
113
+ stderr: stopMessage,
114
+ usage: emptyUsage(),
115
+ model: run?.model,
116
+ thinking: run?.thinking,
117
+ projectCwd: thread.cwd,
118
+ stopReason: "aborted",
119
+ errorMessage: stopMessage,
120
+ runId,
121
+ isolation: thread.isolation,
122
+ };
123
+ const worktree = thread.worktree;
124
+ let finalization: WorktreeFinalization | undefined;
125
+ try {
126
+ finalization = await Promise.race([
127
+ thread.finalizeIsolation(generation, stoppedResult),
128
+ new Promise<undefined>((resolve) => {
129
+ const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
130
+ if (typeof timer.unref === "function") timer.unref();
131
+ }),
132
+ ]);
133
+ } catch {
134
+ /* an unexpected finalize rejection must not block the stop */
135
+ }
136
+ if (finalization === undefined) {
137
+ // Integration is still settling in the background. Point a
138
+ // durable recovery record at the artifacts so the isolated work
139
+ // stays findable even if the background tail later fails; a
140
+ // successful tail removes them and the record self-prunes.
141
+ if (thread.isolation === "worktree" && worktree) {
142
+ stoppedResult.integrationStatus = "pending";
143
+ stoppedResult.integrationWorktreePath = worktree.worktreePath;
144
+ await persistRecoveryRecords(runtime.configPath, [
145
+ recoveryRecordFromFinalization(runId, {
146
+ status: "retained",
147
+ integrated: false,
148
+ hadChanges: false,
149
+ ...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
150
+ ...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
151
+ error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
152
+ }),
153
+ ]).catch(() => undefined);
154
+ pendingIntegration.push(`#${runId}`);
155
+ }
156
+ } else if (finalization.status === "retained") {
157
+ retainedIntegration.push(`#${runId}`);
158
+ }
159
+ runtime.registerRunResult(runId, stoppedResult);
160
+ thread.lastResult = stoppedResult;
161
+ }
162
+ // A stopped run is not a failure. Its result remains available in runtime
163
+ // status and completion, but it must no longer occupy the active widget.
164
+ monitor.removeRun(runId);
165
+ if (stoppedResult) completionResults.push(stoppedResult);
166
+ runtime.retireThreadSession(thread);
167
+ // The destructive retire removes the durable record with the session;
168
+ // an id never resurrects after subagent_stop.
169
+ await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
170
+ if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
171
+ thread.lifecycleOperation = undefined;
172
+ }
173
+ stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
174
+ }
175
+ return { stopped, retainedIntegration, pendingIntegration, completionResults };
176
+ }
@@ -16,15 +16,14 @@ import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
16
16
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
17
17
  import { findWriterLeaseScopeOverlap, normalizePhaseId, normalizePhaseScope } from "../delegation/phase-scope.ts";
18
18
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
19
- import type { SubagentRuntime, SubagentThread, ThreadState } from "./runtime.ts";
19
+ import { findPendingWorkflowPhase, type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
20
20
  import {
21
21
  getProjectRoot,
22
- RpcRunControl,
22
+ RunControl,
23
23
  isFailedResult,
24
24
  isModelLevelFailure,
25
25
  runSingleAgentWithMainFallback,
26
26
  type SingleResult,
27
- type SubagentDetails,
28
27
  type SubagentLiveEvent,
29
28
  } from "../execution/spawn.ts";
30
29
  import {
@@ -66,10 +65,6 @@ interface BackgroundDispatcherOptions {
66
65
  runId: number,
67
66
  generation?: number,
68
67
  ) => (event: SubagentLiveEvent) => void;
69
- makeDetails: (
70
- mode: "single" | "parallel",
71
- background?: boolean,
72
- ) => (results: SingleResult[]) => SubagentDetails;
73
68
  }
74
69
 
75
70
  export function createBackgroundDispatcher(options: BackgroundDispatcherOptions): StartBackgroundInternal {
@@ -78,7 +73,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
78
73
  getEnvironment,
79
74
  finishRun,
80
75
  makeLiveHandler,
81
- makeDetails,
82
76
  } = options;
83
77
 
84
78
  const startBackground: StartBackgroundInternal = async (
@@ -123,6 +117,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
123
117
  isolation,
124
118
  };
125
119
  }
120
+ const pendingOwner = findPendingWorkflowPhase(runtime, task, originalCwd, phaseId, startOptions.workflow?.workflowId);
121
+ if (pendingOwner) return failedStartResult(agentName, task, `Workflow #${pendingOwner.workflowId} node "${pendingOwner.nodeId}" already owns this pending phase. Inspect the graph with subagent_status; main handles follow-up work.`);
126
122
  const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd, phaseId);
127
123
  if (duplicate) {
128
124
  // A phase stays owned across reloads: an interrupted run keeps its claim
@@ -160,7 +156,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
160
156
  isolation,
161
157
  ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
162
158
  });
163
- runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
159
+ if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
164
160
  const generation = 1;
165
161
  const pending: SingleResult = {
166
162
  ...queuedResult(route.agent, task, thinkingLevel),
@@ -171,7 +167,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
171
167
  };
172
168
 
173
169
  let thread!: SubagentThread;
174
- const control = new RpcRunControl(task, generation, (phase) => {
170
+ const control = new RunControl(task, generation, (phase) => {
175
171
  if (runtime.threads.get(runId)?.generation !== generation || phase === "settled") return;
176
172
  const state: ThreadState =
177
173
  phase === "queued" || phase === "starting"
@@ -195,6 +191,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
195
191
  phaseId,
196
192
  scope,
197
193
  writeCapable,
194
+ ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
198
195
  cwd: originalCwd,
199
196
  executionCwd,
200
197
  thinkingLevel,
@@ -204,9 +201,11 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
204
201
  generationCompletion: Promise.resolve(),
205
202
  lifecycleVersion: 0,
206
203
  elapsedMs: 0,
204
+ ...(startOptions.resumeSession ?? {}),
207
205
  finalizeIsolation: async () => undefined,
208
206
  };
209
207
  runtime.threads.set(runId, thread);
208
+ if (thread.sessionDir) runtime.retainSession({ sessionDir: thread.sessionDir });
210
209
  const installCurrentLifecycle = (): void => installThreadLifecycle(thread, {
211
210
  runtime,
212
211
  runCtx,
@@ -270,9 +269,9 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
270
269
  signal: backgroundSignal,
271
270
  onLive,
272
271
  control,
273
- makeDetails: makeDetails("single", true),
274
272
  idleTimeoutMs: activeIdleTimeoutMs,
275
273
  sessionRoot: sessionsRoot,
274
+ ...(startOptions.resumeSession ?? {}),
276
275
  scratchRoot,
277
276
  },
278
277
  activeRoute.mainFallbackRef,
@@ -314,14 +313,14 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
314
313
  // result on the thread for that owner to finalize and deliver once.
315
314
  if (lifecycleInterrupted()) return;
316
315
 
317
- // A shutdown can win in the microtask gap after the child RPC
316
+ // A shutdown can win in the microtask gap after the child
318
317
  // settles. Never replace the stable top-level session with an
319
318
  // aborted partial.
320
319
  if (backgroundSignal.aborted || !runtime.sessionActive) return;
321
320
 
322
321
  if (thread.retireOnSettle) runtime.retireThreadSession(thread);
323
322
  // Claim terminal settlement synchronously before the first slow await.
324
- // Park therefore either wins while RPC is still active, or is rejected
323
+ // Shutdown therefore either wins while the child is still active, or is rejected
325
324
  // once settlement owns the generation. Destructive stop may supersede
326
325
  // this reservation; publication is revalidated after Git finalization.
327
326
  const settlementVersion = ++thread.lifecycleVersion;
@@ -376,7 +375,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
376
375
  runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
377
376
  } else if (dispatchFailed) {
378
377
  runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
379
- }
378
+ }
379
+ runtime.publishRunCompletion(runId, completion, failed);
380
380
  }
381
381
  } finally {
382
382
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
@@ -13,18 +13,18 @@ import {
13
13
  type ThreadRecord,
14
14
  } from "./durable.ts";
15
15
  import { monitor } from "../presentation/monitor.ts";
16
- import { emptyUsage } from "../execution/rpc-control.ts";
16
+ import { emptyUsage } from "../execution/run-control.ts";
17
17
  import type { SubagentRuntime, SubagentThread, ThreadState } from "./runtime.ts";
18
18
  import {
19
19
  getProjectRoot,
20
20
  getSubagentsRoot,
21
- RpcRunControl,
21
+ RunControl,
22
22
  sessionExists,
23
23
  sweepProjectResultArtifacts,
24
24
  type SingleResult,
25
25
  } from "../execution/spawn.ts";
26
26
  import { samePath } from "../isolation/managed-paths.ts";
27
- import { isProcessAlive, killProcessTree, sweepProjectDurableDirs, sweepProjectTempDirs } from "../isolation/temp-hygiene.ts";
27
+ import { isProcessAlive, sweepProjectDurableDirs, sweepProjectTempDirs } from "../isolation/temp-hygiene.ts";
28
28
  import {
29
29
  isPathInside,
30
30
  restoreWorktreeIsolation,
@@ -60,7 +60,7 @@ function createRestoredThread(
60
60
  isolation: record.isolation,
61
61
  worktree,
62
62
  state,
63
- control: new RpcRunControl(record.task, record.generation),
63
+ control: new RunControl(record.task, record.generation),
64
64
  generationCompletion: Promise.resolve(),
65
65
  lifecycleVersion: 0,
66
66
  elapsedMs: record.elapsedMs,
@@ -79,8 +79,8 @@ function belongsToSessionProject(configPath: string, cwd: string, record: Thread
79
79
 
80
80
  /** Rebuild interrupted records for this session's checkout after reload.
81
81
  * Other projects' parked threads stay on disk for their own window; this process
82
- * must not restore them or kill their children. Orphaned children of *this*
83
- * checkout are stopped first; missing session files do not discard isolated
82
+ * must not restore them or kill their children. Records with a live owner or
83
+ * child are left alone; missing session files do not discard isolated
84
84
  * edits. Already-settled records from older versions are removed with their
85
85
  * managed artifacts. */
86
86
  export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: string): Promise<number[]> {
@@ -89,19 +89,16 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
89
89
  for (const record of records) {
90
90
  if (!belongsToSessionProject(runtime.configPath, cwd, record)) continue;
91
91
  if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) continue;
92
+ // Another Pi window may own this checkpoint, and PID reuse means a live
93
+ // recorded child is not proof of ownership. Never kill either on restore.
94
+ if (isCurrentBoot(record) && (
95
+ (record.ownerPid !== undefined && record.ownerPid !== process.pid && isProcessAlive(record.ownerPid)) ||
96
+ record.childPids.some(isProcessAlive)
97
+ )) continue;
92
98
  if (record.state !== "parked") {
93
99
  await discardRestoredRecord(runtime, record);
94
100
  continue;
95
101
  }
96
- // A child orphaned by reload/crash may still hold the retained session.
97
- // The on-disk session checkpoint is what survives; kill the writer — but
98
- // only while the recorded pids are still ours. Across a reboot the same
99
- // numbers belong to unrelated processes.
100
- if (isCurrentBoot(record)) {
101
- for (const pid of record.childPids) {
102
- if (isProcessAlive(pid)) killProcessTree(pid);
103
- }
104
- }
105
102
  const sessionValid =
106
103
  record.sessionId !== undefined &&
107
104
  record.sessionDir !== undefined &&
@@ -151,6 +151,8 @@ export interface DispatchEnvironment {
151
151
 
152
152
  /** Admission metadata for a fresh one-shot run. */
153
153
  export interface StartBackgroundOptions {
154
+ /** A private copy of a settled session used for a follow-up run. */
155
+ resumeSession?: { sessionId: string; sessionDir: string };
154
156
  phaseId?: string;
155
157
  scope?: PhaseScope;
156
158
  /** A false hint cannot downgrade a live write-capable role. */