@ferris1225/pi-subagents 4.3.33 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -349
  2. package/README.md +130 -549
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +52 -31
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +21 -15
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +101 -32
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +38 -10
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
@@ -0,0 +1,175 @@
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
+ monitor.setStatus(runId, "failed");
163
+ if (stoppedResult) completionResults.push(stoppedResult);
164
+ // Leave the terminal row for the footer; beginTurn sweeps it.
165
+ runtime.retireThreadSession(thread);
166
+ // The destructive retire removes the durable record with the session;
167
+ // an id never resurrects after subagent_stop.
168
+ await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
169
+ if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
170
+ thread.lifecycleOperation = undefined;
171
+ }
172
+ stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
173
+ }
174
+ return { stopped, retainedIntegration, pendingIntegration, completionResults };
175
+ }
@@ -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,10 +117,21 @@ 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) {
124
+ // A phase stays owned across reloads: an interrupted run keeps its claim
125
+ // until it is retired, so "let it finish" is wrong advice for a parked
126
+ // owner and leaves the caller with no way forward.
127
+ const owner = duplicate.source;
128
+ const remedy = owner.state === "parked" || owner.retired
129
+ ? `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.`
130
+ : owner.state === "completed" || owner.state === "failed"
131
+ ? "Inspect it with subagent_status; a different deliverable needs a different phaseId. Main handles follow-up work."
132
+ : "Do not redispatch it; inspect its result or let it finish. Main handles follow-up work.";
128
133
  return failedStartResult(agentName, task,
129
- `Run #${duplicate.source.id} (${duplicate.source.agentName}) already owns this logical phase (${duplicate.source.state}). Do not redispatch it; inspect its result or let it finish. Main handles follow-up work.`);
134
+ `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
130
135
  }
131
136
  if (writeCapable && scope) {
132
137
  const conflict = findWriterLeaseScopeOverlap(scope, runtime.threads.values());
@@ -151,7 +156,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
151
156
  isolation,
152
157
  ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
153
158
  });
154
- runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
159
+ if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
155
160
  const generation = 1;
156
161
  const pending: SingleResult = {
157
162
  ...queuedResult(route.agent, task, thinkingLevel),
@@ -162,7 +167,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
162
167
  };
163
168
 
164
169
  let thread!: SubagentThread;
165
- const control = new RpcRunControl(task, generation, (phase) => {
170
+ const control = new RunControl(task, generation, (phase) => {
166
171
  if (runtime.threads.get(runId)?.generation !== generation || phase === "settled") return;
167
172
  const state: ThreadState =
168
173
  phase === "queued" || phase === "starting"
@@ -186,6 +191,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
186
191
  phaseId,
187
192
  scope,
188
193
  writeCapable,
194
+ ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
189
195
  cwd: originalCwd,
190
196
  executionCwd,
191
197
  thinkingLevel,
@@ -261,7 +267,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
261
267
  signal: backgroundSignal,
262
268
  onLive,
263
269
  control,
264
- makeDetails: makeDetails("single", true),
265
270
  idleTimeoutMs: activeIdleTimeoutMs,
266
271
  sessionRoot: sessionsRoot,
267
272
  scratchRoot,
@@ -305,14 +310,14 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
305
310
  // result on the thread for that owner to finalize and deliver once.
306
311
  if (lifecycleInterrupted()) return;
307
312
 
308
- // A shutdown can win in the microtask gap after the child RPC
313
+ // A shutdown can win in the microtask gap after the child
309
314
  // settles. Never replace the stable top-level session with an
310
315
  // aborted partial.
311
316
  if (backgroundSignal.aborted || !runtime.sessionActive) return;
312
317
 
313
318
  if (thread.retireOnSettle) runtime.retireThreadSession(thread);
314
319
  // Claim terminal settlement synchronously before the first slow await.
315
- // Park therefore either wins while RPC is still active, or is rejected
320
+ // Shutdown therefore either wins while the child is still active, or is rejected
316
321
  // once settlement owns the generation. Destructive stop may supersede
317
322
  // this reservation; publication is revalidated after Git finalization.
318
323
  const settlementVersion = ++thread.lifecycleVersion;
@@ -367,7 +372,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
367
372
  runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
368
373
  } else if (dispatchFailed) {
369
374
  runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
370
- }
375
+ }
376
+ runtime.publishRunCompletion(runId, completion, failed);
371
377
  }
372
378
  } finally {
373
379
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
@@ -13,12 +13,12 @@ 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,
@@ -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,
@@ -2,17 +2,15 @@
2
2
 
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
- import { existsSync } from "node:fs";
6
5
  import { Type } from "typebox";
7
6
  import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
8
- import { removeThreadRecord } from "./durable.ts";
7
+ import { stopThreads } from "./stop.ts";
9
8
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
10
- import { emptyUsage } from "../execution/rpc-control.ts";
9
+ import { emptyUsage } from "../execution/run-control.ts";
11
10
  import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
12
- import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
13
- import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
14
- import { CONTROL_QUIESCE_TIMEOUT_MS, projectResultsRoot, quiesced } from "./thread-shared.ts";
15
- import { getResultError, type SingleResult } from "../execution/spawn.ts";
11
+ import type { SubagentRuntime } from "./runtime.ts";
12
+ import { projectResultsRoot } from "./thread-shared.ts";
13
+ import { getResultError } from "../execution/spawn.ts";
16
14
  import {
17
15
  formatRetainedWorkflow,
18
16
  formatWorkflowStatus,
@@ -20,7 +18,6 @@ import {
20
18
  stopWorkflow,
21
19
  workflowStatus,
22
20
  } from "../workflow/engine.ts";
23
- import type { WorktreeFinalization } from "../isolation/worktree.ts";
24
21
 
25
22
  function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
26
23
  const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
@@ -207,16 +204,18 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
207
204
  };
208
205
  }
209
206
  const graphStops: string[] = [];
207
+ const graphStopPromises: Array<Promise<void>> = [];
208
+ const graphRunIds = new Set<number>();
210
209
  if (params.all === true) {
211
- for (const graph of [...runtime.workflows.values()]) {
212
- if (graph.state !== "running") continue;
210
+ const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
211
+ for (const graph of graphs) for (const node of graph.nodes) { if (node.runId !== undefined) graphRunIds.add(node.runId); }
212
+ graphStopPromises.push(...graphs.map(async (graph) => {
213
213
  const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
214
214
  graphStops.push(
215
215
  `workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
216
216
  );
217
- }
217
+ }));
218
218
  }
219
- const completionResults: SingleResult[] = [];
220
219
  const candidateIds = params.all === true
221
220
  ? [...new Set([
222
221
  ...runtime.runControllers.keys(),
@@ -228,8 +227,10 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
228
227
  const targets = params.all === true
229
228
  ? candidateIds
230
229
  : params.id?.trim() ? matchRunIds(candidateIds, params.id.trim()) : [];
230
+ const threadTargets = targets.filter((id) => !graphRunIds.has(id));
231
231
 
232
- if (targets.length === 0) {
232
+ if (threadTargets.length === 0) {
233
+ await Promise.all(graphStopPromises);
233
234
  const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
234
235
  if (graphStops.length > 0) {
235
236
  return {
@@ -245,167 +246,11 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
245
246
  };
246
247
  }
247
248
 
248
- const claimed: Array<{
249
- runId: number;
250
- thread: SubagentThread;
251
- run: ReturnType<typeof monitor.findRun>;
252
- previousState: SubagentThread["state"];
253
- wasQueued: boolean;
254
- wasActive: boolean;
255
- generation: number;
256
- controller: AbortController | undefined;
257
- completion: Promise<void>;
258
- stopVersion: number;
259
- stopMessage: string;
260
- }> = [];
261
- for (const runId of targets) {
262
- const thread = runtime.threads.get(runId);
263
- if (!thread) continue;
264
- const previousState = thread.state;
265
- const wasQueued = previousState === "queued";
266
- const wasActive = thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(previousState);
267
- const stopVersion = ++thread.lifecycleVersion;
268
- thread.lifecycleOperation = "stop";
269
- thread.retired = true;
270
- thread.retireOnSettle = true;
271
- thread.state = "stopped";
272
- const stopMessage = wasQueued
273
- ? "Stopped by subagent_stop before the run started."
274
- : wasActive ? "Stopped by subagent_stop."
275
- : previousState === "parked" ? "Stopped by subagent_stop from an interrupted checkpoint."
276
- : "Retired by subagent_stop.";
277
- claimed.push({
278
- runId, thread, run: monitor.findRun(runId), previousState, wasQueued, wasActive,
279
- generation: thread.generation,
280
- controller: thread.queueController,
281
- completion: thread.generationCompletion,
282
- stopVersion, stopMessage,
283
- });
284
- }
285
-
286
- // Interrupt every claimed generation before awaiting any one of them.
287
- // An isolated stop may need the repository lane for final integration;
288
- // cancelling all holders first prevents stop-all from waiting behind a
289
- // later shared workflow that this same operation has not interrupted yet.
290
- const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
291
- const stopping = thread.control.stop(stopMessage).catch(() => undefined);
292
- runtime.backgroundQueue.cancel(controller);
293
- return stopping;
294
- });
295
-
296
- const stopped: string[] = [];
297
- const retainedIntegration: string[] = [];
298
- const pendingIntegration: string[] = [];
299
- for (const [claimIndex, claim] of claimed.entries()) {
300
- const {
301
- runId,
302
- thread,
303
- run,
304
- previousState,
305
- wasQueued,
306
- wasActive,
307
- generation,
308
- controller,
309
- completion,
310
- stopVersion,
311
- stopMessage,
312
- } = claim;
313
- // Every wait here is bounded: the queue task can sit for minutes in
314
- // worktree finalization or behind the managed repository lane, and an
315
- // unkillable child can stall even the RPC-level stop. Stop owns the
316
- // lifecycle synchronously, so a stuck tail settles silently after we
317
- // proceed; none of its late paths can publish a second result.
318
- await quiesced(interruptionPromises[claimIndex]);
319
- if (!(await quiesced(completion))) runtime.backgroundQueue.cancel(controller);
320
- if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
321
- if (thread.queueController === controller) thread.queueController = undefined;
322
-
323
- // Dispatch yields publication ownership as soon as stop claims the
324
- // lifecycle. Synthesize and publish the one aborted result here only when
325
- // this stop actually interrupted unfinished work.
326
- let stoppedResult: SingleResult | undefined;
327
- if (
328
- wasQueued ||
329
- previousState === "parked" ||
330
- !runtime.settledRuns.has(runId)
331
- ) {
332
- const prior = thread.lastResult;
333
- stoppedResult = prior
334
- ? {
335
- ...prior,
336
- exitCode: 1,
337
- stopReason: "aborted",
338
- errorMessage: stopMessage,
339
- runId,
340
- }
341
- : {
342
- agent: thread.agentName,
343
- task: thread.task,
344
- exitCode: 1,
345
- messages: [],
346
- stderr: stopMessage,
347
- usage: emptyUsage(),
348
- model: run?.model,
349
- thinking: run?.thinking,
350
- projectCwd: thread.cwd,
351
- stopReason: "aborted",
352
- errorMessage: stopMessage,
353
- runId,
354
- isolation: thread.isolation,
355
- };
356
- const worktree = thread.worktree;
357
- let finalization: WorktreeFinalization | undefined;
358
- try {
359
- finalization = await Promise.race([
360
- thread.finalizeIsolation(generation, stoppedResult),
361
- new Promise<undefined>((resolve) => {
362
- const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
363
- if (typeof timer.unref === "function") timer.unref();
364
- }),
365
- ]);
366
- } catch {
367
- /* an unexpected finalize rejection must not block the stop */
368
- }
369
- if (finalization === undefined) {
370
- // Integration is still settling in the background. Point a
371
- // durable recovery record at the artifacts so the isolated work
372
- // stays findable even if the background tail later fails; a
373
- // successful tail removes them and the record self-prunes.
374
- if (thread.isolation === "worktree" && worktree) {
375
- stoppedResult.integrationStatus = "pending";
376
- stoppedResult.integrationWorktreePath = worktree.worktreePath;
377
- await persistRecoveryRecords(runtime.configPath, [
378
- recoveryRecordFromFinalization(runId, {
379
- status: "retained",
380
- integrated: false,
381
- hadChanges: false,
382
- ...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
383
- ...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
384
- error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
385
- }),
386
- ]).catch(() => undefined);
387
- pendingIntegration.push(`#${runId}`);
388
- }
389
- } else if (finalization.status === "retained") {
390
- retainedIntegration.push(`#${runId}`);
391
- }
392
- runtime.registerRunResult(runId, stoppedResult);
393
- thread.lastResult = stoppedResult;
394
- }
395
- monitor.setStatus(runId, "failed");
396
- if (stoppedResult) completionResults.push(stoppedResult);
397
- // Leave the terminal row for the footer; beginTurn sweeps it.
398
- runtime.retireThreadSession(thread);
399
- // The destructive retire removes the durable record with the session;
400
- // an id never resurrects after subagent_stop.
401
- await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
402
- if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
403
- thread.lifecycleOperation = undefined;
404
- }
405
- stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
406
- }
249
+ const stopping = stopThreads(runtime, threadTargets);
250
+ await Promise.all(graphStopPromises);
251
+ const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopping;
407
252
  if (completionResults.length > 0) {
408
- runtime.sendCompletionGroup(completionResults.map((result) => ({
253
+ runtime.sendCompletionGroup(completionResults.filter((result) => !runtime.threads.get(result.runId!)?.workflow).map((result) => ({
409
254
  agent: result.agent,
410
255
  block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
411
256
  triggerTurn: true,
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { AgentConfig } from "../delegation/agents.ts";
8
8
  import { formatUsageCompact, runLabel, shrinkRunLabel } from "./monitor.ts";
9
- import { emptyUsage } from "../execution/rpc-control.ts";
9
+ import { emptyUsage } from "../execution/run-control.ts";
10
10
  import {
11
11
  RESULT_LINE_MAX,
12
12
  getResultError,
@@ -87,16 +87,13 @@ export function formatCompletionBlock(
87
87
  const fallbackNote = result.modelFallbackFrom
88
88
  ? ` (selected model ${result.modelFallbackFrom} failed → main ${result.model ?? "dynamic default"})`
89
89
  : "";
90
- const startupRetryNote = result.startupRetries
91
- ? ` (recovered after ${result.startupRetries} startup retr${result.startupRetries === 1 ? "y" : "ies"} — concurrent pi startup race)`
92
- : "";
93
90
  const runNote = result.runId !== undefined ? ` · run #${result.runId}` : "";
94
91
  // A short task-derived label, not the task itself: the parent authored the
95
92
  // task and still has it in context, but a wide fan-out of same-agent runs
96
93
  // needs more than a run id to tell completions apart.
97
94
  const label = shrinkRunLabel(runLabel(result.task), COMPLETION_LABEL_MAX);
98
95
  const lines = [
99
- `### [${result.agent}${label ? `·${label}` : ""}] ${status}${usage ? ` (${usage})` : ""}${fallbackNote}${startupRetryNote}${runNote}`,
96
+ `### [${result.agent}${label ? `·${label}` : ""}] ${status}${usage ? ` (${usage})` : ""}${fallbackNote}${runNote}`,
100
97
  "",
101
98
  ];
102
99
  if (result.isolation === "worktree") {
@@ -12,7 +12,8 @@
12
12
  import { stripVTControlCharacters } from "node:util";
13
13
  import type { Theme } from "@earendil-works/pi-coding-agent";
14
14
  import { visibleWidth } from "@earendil-works/pi-tui";
15
- import { emptyUsage, type UsageStats } from "../execution/rpc-control.ts";
15
+ import { emptyUsage, type UsageStats } from "../execution/run-control.ts";
16
+ import type { WorkflowRun } from "../workflow/state.ts";
16
17
  import type { IsolationMode, WorktreeFinalizationStatus } from "../isolation/worktree.ts";
17
18
 
18
19
  // ---------------------------------------------------------------------------
@@ -462,10 +463,23 @@ export function formatToolActivity(toolName: string, args: unknown): string {
462
463
 
463
464
  export class MonitorStore {
464
465
  private runs: RunView[] = [];
466
+ private workflows = new Map<number, WorkflowRun>();
467
+
468
+ updateWorkflow(run: WorkflowRun): void {
469
+ this.workflows.set(run.id, run);
470
+ this.notify();
471
+ }
472
+
473
+ getWorkflows(): WorkflowRun[] {
474
+ return [...this.workflows.values()];
475
+ }
465
476
  private nextId = 1;
466
477
  private subscribers = new Set<() => void>();
467
478
 
468
479
  beginTurn(): void {
480
+ for (const [id, run] of this.workflows) {
481
+ if (run.state !== "running") this.workflows.delete(id);
482
+ }
469
483
  // Clear finished runs from a previous turn, but keep active and parked
470
484
  // threads so concurrent work is not wiped between parent turns.
471
485
  this.runs = this.runs.filter(
@@ -645,6 +659,7 @@ export class MonitorStore {
645
659
  * finishRun calls from the old session remain safe no-ops. */
646
660
  clear(): void {
647
661
  this.runs = [];
662
+ this.workflows.clear();
648
663
  this.notify();
649
664
  }
650
665