@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
@@ -1,18 +1,24 @@
1
1
  /** Read-only run inspection and destructive cancellation of one-shot runs. */
2
2
 
3
+ import { randomUUID } from "node:crypto";
4
+ import { copyFile, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import type { Message } from "@earendil-works/pi-ai";
3
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
8
  import { Text } from "@earendil-works/pi-tui";
5
- import { existsSync } from "node:fs";
6
9
  import { Type } from "typebox";
7
- import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
8
- import { removeThreadRecord } from "./durable.ts";
10
+ import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
11
+ import { loadBuiltinAgents } from "../delegation/agents.ts";
12
+ import { getProjectRoot, getResultOutput, sessionExists } from "../execution/spawn.ts";
13
+ import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
14
+ import type { DispatchCore } from "./dispatch-core.ts";
15
+ import { stopThreads } from "./stop.ts";
9
16
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
10
- import { emptyUsage } from "../execution/rpc-control.ts";
17
+ import { emptyUsage } from "../execution/run-control.ts";
11
18
  import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
12
- import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
13
19
  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";
20
+ import { projectResultsRoot } from "./thread-shared.ts";
21
+ import { getResultError } from "../execution/spawn.ts";
16
22
  import {
17
23
  formatRetainedWorkflow,
18
24
  formatWorkflowStatus,
@@ -20,7 +26,6 @@ import {
20
26
  stopWorkflow,
21
27
  workflowStatus,
22
28
  } from "../workflow/engine.ts";
23
- import type { WorktreeFinalization } from "../isolation/worktree.ts";
24
29
 
25
30
  function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
26
31
  const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
@@ -32,7 +37,53 @@ function renderFirstLine(result: { content?: unknown }, label: string, theme: an
32
37
  return new Text(`${theme.fg("toolTitle", theme.bold(label))}${theme.fg("dim", firstLine.slice(0, 60))}`, 0, 0);
33
38
  }
34
39
 
35
- export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime): void {
40
+ /** Files a finished run read or changed, recovered from its recorded tool
41
+ * calls. A new child cannot see that history, so naming the paths is the
42
+ * difference between a useful brief and a blind restart. */
43
+ function touchedPaths(messages: readonly Message[] | undefined): string[] {
44
+ const paths = new Set<string>();
45
+ const visit = (value: unknown, depth: number): void => {
46
+ if (depth > 3 || !value || typeof value !== "object") return;
47
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
48
+ if (/^(path|paths|file|files|file_path|target|pattern)$/u.test(key)) {
49
+ for (const candidate of Array.isArray(child) ? child : [child]) {
50
+ if (typeof candidate === "string" && candidate.length <= 200 && /[\\/.]/u.test(candidate)) paths.add(candidate);
51
+ }
52
+ continue;
53
+ }
54
+ visit(child, depth + 1);
55
+ }
56
+ };
57
+ for (const message of messages ?? []) {
58
+ const content = (message as { content?: unknown }).content;
59
+ if (Array.isArray(content)) for (const part of content) visit(part, 0);
60
+ }
61
+ return [...paths].slice(0, 20);
62
+ }
63
+
64
+ /** Brief for a summary follow-up: what the run was asked, what it delivered,
65
+ * which files it touched, and the new instruction — bounded so a long result
66
+ * cannot become the whole context. */
67
+ function buildSummaryFollowUp(thread: SubagentThread, message: string): string {
68
+ const prior = thread.lastResult ? getResultOutput(thread.lastResult) : "(no recorded result)";
69
+ const bounded = prior.length > 4_000 ? prior.slice(0, 4_000) + "\n…(truncated; read the files for detail)" : prior;
70
+ const files = touchedPaths(thread.lastResult?.messages);
71
+ return [
72
+ `Earlier run #${thread.id} (${thread.agentName}) was briefed with:`,
73
+ formatTaskSummary(thread.task, 1_200, false),
74
+ "",
75
+ "It finished with:",
76
+ bounded,
77
+ ...(files.length ? ["", "Files it touched:", files.map((path) => `- ${path}`).join("\n")] : []),
78
+ "",
79
+ "Continue with this instruction:",
80
+ message,
81
+ "",
82
+ "You did not witness the earlier session. Verify the files before relying on them, and state any assumption this summary does not support.",
83
+ ].join("\n");
84
+ }
85
+
86
+ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime, dispatchCore?: DispatchCore): void {
36
87
  pi.registerTool({
37
88
  name: "subagent_status",
38
89
  label: "Subagent Status",
@@ -114,18 +165,19 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
114
165
  // Workflow graphs are reported beside individual runs: which nodes have
115
166
  // started, which one is waiting on a dependency, and what a graph that
116
167
  // outlived its session left behind.
168
+ const workflowId = params.id === undefined ? params.workflow : undefined;
117
169
  const workflowRuns = [...runtime.workflows.values()]
118
- .filter((run) => params.workflow === undefined || run.id === params.workflow)
170
+ .filter((run) => workflowId === undefined || run.id === workflowId)
119
171
  .sort((left, right) => left.id - right.id);
120
172
  const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
121
- .filter((record) => params.workflow === undefined || record.id === params.workflow)
173
+ .filter((record) => workflowId === undefined || record.id === workflowId)
122
174
  .filter((record) => !workflowRuns.some((run) => run.id === record.id));
123
- const workflowSections = [
175
+ const workflowSections = params.id === undefined ? [
124
176
  ...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
125
177
  ...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
126
- ];
178
+ ] : [];
127
179
  const sections = [text, ...workflowSections].filter((section) => section.trim().length > 0);
128
- const unknownWorkflow = params.workflow !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
180
+ const unknownWorkflow = workflowId !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
129
181
  return {
130
182
  content: [{
131
183
  type: "text",
@@ -150,6 +202,70 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
150
202
  },
151
203
  });
152
204
 
205
+ pi.registerTool({
206
+ name: "subagent_message",
207
+ label: "Subagent Message",
208
+ 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.",
209
+ exposure: "model-only",
210
+ executionMode: "sequential",
211
+ parameters: Type.Object({
212
+ id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
213
+ message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
214
+ 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." })),
215
+ }),
216
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
217
+ await runtime.durableRestore;
218
+ const thread = runtime.threads.get(params.id);
219
+ const fail = (message: string) => ({ content: [{ type: "text" as const, text: message }], details: {}, isError: true });
220
+ if (!thread || thread.retired) return fail(`No available run matches #${params.id} in this session.`);
221
+ if (thread.state === "running" && !thread.lifecycleOperation) {
222
+ try {
223
+ await thread.control.steer(params.message);
224
+ return { content: [{ type: "text" as const, text: `Steering queued for #${thread.id}; it has not necessarily been acted on yet.` }], details: { id: thread.id } };
225
+ } catch (error) { return fail(`Could not send to #${thread.id}: ${error instanceof Error ? error.message : String(error)}`); }
226
+ }
227
+ if (thread.state !== "completed" || thread.lifecycleOperation) {
228
+ return fail(`Run #${thread.id} is ${thread.state}; wait for a running or successfully completed run.`);
229
+ }
230
+ if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
231
+ const useSummary = params.context === "summary";
232
+ if (!useSummary && (!thread.sessionDir || !thread.sessionId || !sessionExists(thread.sessionDir, thread.sessionId))) {
233
+ return fail(`Run #${thread.id} has no available session to continue; retry with context: "summary".`);
234
+ }
235
+ let copyDir: string | undefined;
236
+ try {
237
+ dispatchCore.setEnvironment({ ctx, config: await loadConfig(runtime.configPath), agents: loadBuiltinAgents() });
238
+ if (useSummary) {
239
+ const task = buildSummaryFollowUp(thread, params.message);
240
+ const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
241
+ phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
242
+ });
243
+ if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
244
+ 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 } };
245
+ }
246
+ const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
247
+ await mkdir(root, { recursive: true });
248
+ copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
249
+ writeTempOwnerMarker(copyDir);
250
+ const file = (await readdir(thread.sessionDir!)).find((name) => name.endsWith(`_${thread.sessionId}.jsonl`));
251
+ if (!file) throw new Error("The retained session file is missing; retry with context: \"summary\".");
252
+ await copyFile(join(thread.sessionDir!, file), join(copyDir, file));
253
+ if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while its session was copied.");
254
+ const task = `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`;
255
+ const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
256
+ phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
257
+ resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir },
258
+ });
259
+ if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
260
+ copyDir = undefined;
261
+ 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 } };
262
+ } catch (error) {
263
+ if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
264
+ return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
265
+ }
266
+ },
267
+ });
268
+
153
269
  // Cancel one or more active runs: aborts the queue controller, which
154
270
  // terminates the child and delivers an aborted result (with whatever partial
155
271
  // output it produced) so the main agent always knows the run stopped.
@@ -169,7 +285,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
169
285
  pi.registerTool({
170
286
  name: "subagent_stop",
171
287
  label: "Subagent Stop",
172
- description: "Destructively stop and retire one run by id/prefix, or all active runs with all: true. Delivers partial results; stopped runs cannot resume.",
288
+ description: "Destructively stop and retire one run by id/prefix, one workflow by workflow id, or this session’s active runs and workflows with all: true. all takes precedence over id and workflow; id takes precedence over workflow. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
173
289
  exposure: "model-only",
174
290
  executionMode: "sequential",
175
291
  annotations: {
@@ -185,7 +301,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
185
301
  // A graph stop owns its own lifecycle: dependents must not start, and the
186
302
  // graph's own summary reports what had already completed. Stopping the
187
303
  // nodes one by one first would let the runner dispatch the next layer.
188
- if (params.workflow !== undefined) {
304
+ if (params.all !== true && !params.id?.trim() && params.workflow !== undefined) {
189
305
  const graph = runtime.workflows.get(params.workflow);
190
306
  if (!graph) {
191
307
  const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
@@ -207,16 +323,18 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
207
323
  };
208
324
  }
209
325
  const graphStops: string[] = [];
326
+ const graphStopPromises: Array<Promise<void>> = [];
327
+ const graphRunIds = new Set<number>();
210
328
  if (params.all === true) {
211
- for (const graph of [...runtime.workflows.values()]) {
212
- if (graph.state !== "running") continue;
329
+ const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
330
+ for (const graph of graphs) for (const node of graph.nodes) { if (node.runId !== undefined) graphRunIds.add(node.runId); }
331
+ graphStopPromises.push(...graphs.map(async (graph) => {
213
332
  const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
214
333
  graphStops.push(
215
334
  `workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
216
335
  );
217
- }
336
+ }));
218
337
  }
219
- const completionResults: SingleResult[] = [];
220
338
  const candidateIds = params.all === true
221
339
  ? [...new Set([
222
340
  ...runtime.runControllers.keys(),
@@ -228,8 +346,10 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
228
346
  const targets = params.all === true
229
347
  ? candidateIds
230
348
  : params.id?.trim() ? matchRunIds(candidateIds, params.id.trim()) : [];
349
+ const threadTargets = targets.filter((id) => !graphRunIds.has(id));
231
350
 
232
- if (targets.length === 0) {
351
+ if (threadTargets.length === 0) {
352
+ await Promise.all(graphStopPromises);
233
353
  const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
234
354
  if (graphStops.length > 0) {
235
355
  return {
@@ -245,167 +365,11 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
245
365
  };
246
366
  }
247
367
 
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
- }
368
+ const stopping = stopThreads(runtime, threadTargets);
369
+ await Promise.all(graphStopPromises);
370
+ const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopping;
407
371
  if (completionResults.length > 0) {
408
- runtime.sendCompletionGroup(completionResults.map((result) => ({
372
+ runtime.sendCompletionGroup(completionResults.filter((result) => !runtime.threads.get(result.runId!)?.workflow).map((result) => ({
409
373
  agent: result.agent,
410
374
  block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
411
375
  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