@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -0,0 +1,53 @@
1
+ import * as fs from "node:fs";
2
+ import type { AsyncRunSummary } from "./async-status.ts";
3
+
4
+ const INTERCOM_DETACH_ERROR = "detached for intercom coordination";
5
+
6
+ function isIntercomDetached(run: AsyncRunSummary): boolean {
7
+ return run.steps.some((step) => step.execution?.status === "detached"
8
+ || step.error?.toLowerCase().includes(INTERCOM_DETACH_ERROR) === true)
9
+ || run.error?.toLowerCase().includes(INTERCOM_DETACH_ERROR) === true;
10
+ }
11
+
12
+ function formatIntercomDetachGuidance(run: AsyncRunSummary): string | undefined {
13
+ if (!isIntercomDetached(run)) return undefined;
14
+ return `Run "${run.id}" detached for intercom coordination. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.id}" }). Use subagent({ action: "status", id: "${run.id}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
15
+ }
16
+
17
+ export function formatAsyncReviveCommand(run: AsyncRunSummary): string | undefined {
18
+ const step = run.steps.find((candidate) => candidate.status === "failed" && candidate.sessionFile && fs.existsSync(candidate.sessionFile));
19
+ if (!step) {
20
+ if (run.steps.length === 1 && run.sessionFile && fs.existsSync(run.sessionFile)) {
21
+ return `subagent({ action: "resume", id: "${run.id}", message: "Continue from the persisted child session and report the result." })`;
22
+ }
23
+ return undefined;
24
+ }
25
+ const index = run.steps.length === 1 ? "" : `, index: ${step.index}`;
26
+ return `subagent({ action: "resume", id: "${run.id}"${index}, message: "Continue from the persisted child session and report the result." })`;
27
+ }
28
+
29
+ export function formatResumeFirstFailedRunDetail(run: AsyncRunSummary): string | undefined {
30
+ if (run.state !== "failed") return undefined;
31
+ const detachGuidance = formatIntercomDetachGuidance(run);
32
+ if (detachGuidance) return detachGuidance;
33
+ const command = formatAsyncReviveCommand(run);
34
+ if (!command) return undefined;
35
+ return `Resume-first: failed run "${run.id}" has a persisted child session. Revive the original run with ${command} before reporting failure or launching a replacement. Launch a replacement only if revive fails or the user explicitly asks for one.`;
36
+ }
37
+
38
+ export function formatResumeFirstFailedRunsNote(runs: AsyncRunSummary[]): string {
39
+ const failedRuns = runs.filter((run) => run.state === "failed");
40
+ const detachGuidance = failedRuns
41
+ .map(formatIntercomDetachGuidance)
42
+ .filter((guidance): guidance is string => Boolean(guidance));
43
+ const resumable = failedRuns
44
+ .filter((run) => !isIntercomDetached(run))
45
+ .map((run) => ({ run, command: formatAsyncReviveCommand(run) }))
46
+ .filter((entry): entry is { run: AsyncRunSummary; command: string } => Boolean(entry.command));
47
+ const resumeGuidance = resumable.length === 0
48
+ ? ""
49
+ : resumable.length === 1
50
+ ? ` Resume-first: failed run "${resumable[0]!.run.id}" has a persisted child session. Revive the original run with ${resumable[0]!.command} before reporting failure or launching a replacement. Launch a replacement only if revive fails or the user explicitly asks for one.`
51
+ : ` Resume-first: ${resumable.length} failed runs have persisted child sessions. Inspect status and revive each original run before reporting failure or launching a replacement. Launch a replacement only if revive fails or the user explicitly asks for one.`;
52
+ return `${detachGuidance.length > 0 ? ` ${detachGuidance.join(" ")}` : ""}${resumeGuidance}`;
53
+ }
@@ -8,6 +8,8 @@ const MAX_TASK_SUMMARY_LENGTH = 120;
8
8
  export interface RetainedChild {
9
9
  runId: string;
10
10
  parentRunId?: string;
11
+ workflowKey?: string;
12
+ state: "complete" | "failed" | "paused";
11
13
  agent: string;
12
14
  taskSummary: string;
13
15
  completedAt: number;
@@ -33,16 +35,20 @@ function boundedTaskSummary(value: string | undefined): string {
33
35
  }
34
36
 
35
37
  export function listRetainedChildren(asyncDirRoot: string, sessionId: string): RetainedChild[] {
36
- return listAsyncRuns(asyncDirRoot, { sessionId, states: ["complete"], reconcile: false })
38
+ return listAsyncRuns(asyncDirRoot, { sessionId, states: ["complete", "failed", "paused"], reconcile: false })
37
39
  .flatMap((run) => {
38
40
  if (!run.parentWorkflowRunId || run.steps.length !== 1) return [];
41
+ if (run.state !== "complete" && run.state !== "failed" && run.state !== "paused") return [];
39
42
  const step = run.steps[0]!;
40
- if ((step.status !== "complete" && step.status !== "completed") || !retainedSessionFile(step.sessionFile ?? run.sessionFile)) return [];
41
- const completedAt = run.endedAt;
43
+ const terminalStep = step.status === "complete" || step.status === "completed" || step.status === "failed" || step.status === "paused";
44
+ if (!terminalStep || !retainedSessionFile(step.sessionFile ?? run.sessionFile)) return [];
45
+ const completedAt = run.endedAt ?? run.lastUpdate;
42
46
  if (completedAt === undefined) return [];
43
47
  return [{
44
48
  runId: run.id,
45
49
  ...(run.parentWorkflowRunId ? { parentRunId: run.parentWorkflowRunId } : {}),
50
+ ...(run.workflowKey ? { workflowKey: run.workflowKey } : {}),
51
+ state: run.state,
46
52
  agent: step.agent,
47
53
  taskSummary: boundedTaskSummary(step.description),
48
54
  completedAt,
@@ -55,13 +61,15 @@ export function listRetainedChildren(asyncDirRoot: string, sessionId: string): R
55
61
  }
56
62
 
57
63
  export function formatRetainedChildren(children: RetainedChild[]): string {
58
- if (children.length === 0) return "No completed retained children in the active parent session.";
64
+ if (children.length === 0) return "No recoverable retained children in the active parent session.";
59
65
  return [
60
- `Completed retained children (newest first, last ${MAX_RETAINED_CHILDREN}):`,
66
+ `Recoverable retained children (newest first, last ${MAX_RETAINED_CHILDREN}):`,
61
67
  ...children.flatMap((child) => [
62
- `- ${child.runId} | ${child.agent} | ${new Date(child.completedAt).toISOString()}`,
68
+ `- ${child.runId} | ${child.agent} | ${child.state} | ${new Date(child.completedAt).toISOString()}`,
69
+ ...(child.parentRunId ? [` workflow: ${child.parentRunId}${child.workflowKey ? ` (${child.workflowKey})` : ""}`] : []),
63
70
  ` task: ${child.taskSummary || "(no task summary)"}`,
64
71
  ` session: ${child.sessionPath}`,
72
+ ` resume: subagent({ action: "resume", id: "${child.runId}", message: "..." })`,
65
73
  ...(child.tokenTotals ? [` tokens: input ${child.tokenTotals.input}, output ${child.tokenTotals.output}, total ${child.tokenTotals.total}`] : []),
66
74
  ]),
67
75
  ].join("\n");
@@ -1,12 +1,15 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { safeTerminalText } from "../../shared/display-text.ts";
4
5
  import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns } from "./async-status.ts";
5
6
  import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.ts";
6
7
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
7
8
  import { formatModelThinking } from "../../shared/formatters.ts";
8
9
  import { formatActivityLabel } from "../../shared/status-format.ts";
9
10
  import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type NestedRunSummary, type SteeringStatus, type SubagentState } from "../../shared/types.ts";
11
+ import { inspectActiveAsyncCapacityOwner, type ActiveAsyncCapacityInspection } from "./active-async-capacity.ts";
12
+ import { readStatus } from "../../shared/utils.ts";
10
13
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
11
14
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
12
15
  import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
@@ -18,6 +21,7 @@ import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-
18
21
  import { attachRootChildrenToSteps, findNestedRouteForRootId, projectNestedRegistryForRoot, type NestedRunResolutionScope } from "../shared/nested-events.ts";
19
22
  import { readMissionBinding } from "../../missions/lifecycle.ts";
20
23
  import { formatWorkflowJsonPreview } from "../../workflows/scripted-workflow.ts";
24
+ import { formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
21
25
 
22
26
  interface RunStatusParams {
23
27
  action?: string;
@@ -29,6 +33,66 @@ interface RunStatusParams {
29
33
  lines?: number;
30
34
  }
31
35
 
36
+ function formatProcessTerminal(value: AsyncStatus["processTerminal"] | undefined): string {
37
+ if (!value) return "missing";
38
+ return `${value.state}${value.reason ? ` (${value.reason})` : ""}${value.runnerProcessInstanceId ? ` · runner ${value.runnerProcessInstanceId}` : ""}`;
39
+ }
40
+
41
+ function debugProcessTerminal(asyncDir: string, status: AsyncStatus): { sidecar?: AsyncStatus["processTerminal"]; overlay?: AsyncStatus["processTerminal"] } {
42
+ const expected = { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId };
43
+ return {
44
+ sidecar: readProcessTerminal(asyncDir, expected),
45
+ overlay: sanitizeProcessTerminal(status.processTerminal, expected, path.join(asyncDir, "status.json")),
46
+ };
47
+ }
48
+
49
+ function formatCapacityOwner(inspect: ActiveAsyncCapacityInspection): string[] {
50
+ if (!inspect.owner) return [`Active capacity: ${inspect.release.state} — ${inspect.release.reason}`];
51
+ const owner = inspect.owner;
52
+ return [
53
+ `Active capacity: ${inspect.release.state} — ${inspect.release.reason}`,
54
+ `Capacity owner: ${inspect.relation} slot ${owner.slot}, ${owner.kind}, generation ${owner.generation}`,
55
+ `Capacity session: ${owner.ownerSessionId}`,
56
+ owner.sourceRunId ? `Capacity source run: ${owner.sourceRunId}` : undefined,
57
+ `Capacity async dir: ${owner.asyncDir}`,
58
+ owner.runnerProcessInstanceId ? `Capacity runner: ${owner.runnerProcessInstanceId}` : undefined,
59
+ owner.runnerStartedAt !== undefined ? `Capacity runner started: ${new Date(owner.runnerStartedAt).toISOString()}` : undefined,
60
+ ].filter((line): line is string => line !== undefined);
61
+ }
62
+
63
+ function formatWorkflowDebug(status: AsyncStatus): string[] {
64
+ if (status.mode !== "workflow" && !status.parentWorkflowRunId && !status.workflowKey) return [];
65
+ const lines = [
66
+ status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
67
+ status.mode === "workflow" ? `Workflow children: ${(status.steps ?? []).length}` : undefined,
68
+ ].filter((line): line is string => line !== undefined);
69
+ for (const [index, step] of (status.steps ?? []).entries()) {
70
+ lines.push(` ${index + 1}. key ${step.workflowKey ?? "n/a"} · ${step.agent} · ${step.status} · async ${step.async === undefined ? "unknown" : step.async ? "yes" : "no"}${step.runId ? ` · run ${step.runId}` : ""}`);
71
+ }
72
+ return lines;
73
+ }
74
+
75
+ function formatRunLifecycleDebug(input: { status: AsyncStatus; asyncDir: string; sidecarProcessTerminal: AsyncStatus["processTerminal"] | undefined; overlayProcessTerminal: AsyncStatus["processTerminal"] | undefined; capacity: ActiveAsyncCapacityInspection }): string {
76
+ const { status, asyncDir, sidecarProcessTerminal, overlayProcessTerminal, capacity } = input;
77
+ const lines = [
78
+ "Run lifecycle debug",
79
+ `Run: ${status.runId}`,
80
+ `Dir: ${asyncDir}`,
81
+ `Status file: ${path.join(asyncDir, "status.json")}`,
82
+ `Process terminal file: ${path.join(asyncDir, "process-terminal.json")}`,
83
+ `Session: ${status.sessionId ?? "unknown"}`,
84
+ `State: ${status.state}`,
85
+ `Mode: ${status.mode}`,
86
+ status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}` : undefined,
87
+ status.workflowKey ? `Workflow key: ${status.workflowKey}` : undefined,
88
+ `Status process terminal: ${formatProcessTerminal(overlayProcessTerminal)}`,
89
+ `Sidecar process terminal: ${formatProcessTerminal(sidecarProcessTerminal)}`,
90
+ ...formatCapacityOwner(capacity),
91
+ ...formatWorkflowDebug(status),
92
+ ].filter((line): line is string => line !== undefined);
93
+ return lines.join("\n");
94
+ }
95
+
32
96
  interface RunStatusDeps {
33
97
  asyncDirRoot?: string;
34
98
  resultsDir?: string;
@@ -37,6 +101,7 @@ interface RunStatusDeps {
37
101
  state?: SubagentState;
38
102
  nested?: NestedRunResolutionScope;
39
103
  sessionRoots?: string[];
104
+ activeCapacityRoot?: string;
40
105
  }
41
106
 
42
107
  function hasExistingSessionFile(value: unknown): value is string {
@@ -48,12 +113,16 @@ function formatCheckpointGuidance(runId: string | undefined, checkpoint: AsyncSt
48
113
  return `Checkpoint: ${checkpoint.name}${checkpoint.message ? ` — ${checkpoint.message}` : ""}\nApprove: subagent({ action: "approve-checkpoint", id: "${runId}" })\nReject: subagent({ action: "reject-checkpoint", id: "${runId}" })`;
49
114
  }
50
115
 
51
- function formatResumeGuidance(runId: string | undefined, children: Array<{ agent?: unknown; sessionFile?: unknown }>, fallbackSessionFile?: unknown, options: { stopped?: boolean } = {}): string {
116
+ function formatResumeGuidance(runId: string | undefined, children: Array<{ agent?: unknown; sessionFile?: unknown; runId?: unknown; workflowKey?: unknown }>, fallbackSessionFile?: unknown, options: { stopped?: boolean } = {}): string {
52
117
  if (options.stopped) return "Resume: unavailable; stopped runs are not resumable. Start a new run instead.";
53
118
  const knownChildren = children
54
119
  .map((child, index) => ({ child, index }))
55
120
  .filter(({ child }) => typeof child.agent === "string");
56
121
  if (!runId || knownChildren.length === 0) return "Resume: unavailable; no child session file was persisted.";
122
+ const workflowChildren = knownChildren.filter(({ child }) => typeof child.runId === "string" && child.runId.trim() && hasExistingSessionFile(child.sessionFile));
123
+ if (workflowChildren.length > 0) {
124
+ return workflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`).join("\n");
125
+ }
57
126
  const singleSessionFile = knownChildren[0]?.child.sessionFile ?? fallbackSessionFile;
58
127
  if (children.length === 1 && knownChildren.length === 1 && hasExistingSessionFile(singleSessionFile)) {
59
128
  return `Revive: subagent({ action: "resume", id: "${runId}", message: "..." })`;
@@ -176,7 +245,7 @@ function formatRememberedForegroundTranscript(run: ForegroundResumeRun, options:
176
245
  lines.push("Result transcript tail:");
177
246
  if (outputLines.length === 0) lines.push(" (no recovered final output available yet)");
178
247
  else for (const line of outputLines) lines.push(` ${line}`);
179
- return lines.join("\n");
248
+ return lines.map((line) => safeTerminalText(line)).join("\n");
180
249
  }
181
250
 
182
251
  function formatNestedExactStatus(rootRunId: string, run: NestedRunSummary): string {
@@ -261,7 +330,9 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
261
330
  let location;
262
331
  try {
263
332
  const requestedId = params.id ?? params.runId;
264
- if (!params.dir && requestedId) {
333
+ if (params.action === "debug.run") {
334
+ location = resolveAsyncRunLocation(params, asyncDirRoot, resultsDir);
335
+ } else if (!params.dir && requestedId) {
265
336
  const resolved = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
266
337
  if (resolved?.kind === "foreground") {
267
338
  const run = deps.state?.foregroundRuns?.get(resolved.id);
@@ -315,6 +386,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
315
386
  }
316
387
 
317
388
  if (asyncDir) {
389
+ const diskStatus = readStatus(asyncDir);
318
390
  let reconciliation;
319
391
  try {
320
392
  reconciliation = reconcileAsyncRun(asyncDir, { resultsDir, kill: deps.kill, now: deps.now });
@@ -327,10 +399,42 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
327
399
  };
328
400
  }
329
401
  const status = reconciliation.status;
402
+ if (!status && diskStatus?.displayDismissedAt !== undefined) {
403
+ if (params.action === "debug.run") {
404
+ const { sidecar, overlay } = debugProcessTerminal(asyncDir, diskStatus);
405
+ const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
406
+ return {
407
+ content: [{ type: "text", text: formatRunLifecycleDebug({ status: diskStatus, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
408
+ details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
409
+ };
410
+ }
411
+ if (params.view === "transcript") {
412
+ if (currentSessionId && diskStatus.sessionId !== currentSessionId) {
413
+ return {
414
+ content: [{ type: "text", text: "Transcript view is only available for async runs owned by the current session." }],
415
+ isError: true,
416
+ details: { mode: "single", results: [] },
417
+ };
418
+ }
419
+ return { content: [{ type: "text", text: formatAsyncRunTranscript(diskStatus, asyncDir, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
420
+ }
421
+ return {
422
+ content: [{ type: "text", text: `Run: ${diskStatus.runId}\nState: display-dismissed\nDismissed: ${new Date(diskStatus.displayDismissedAt).toISOString()}\nNo running work was terminated.` }],
423
+ details: { mode: "single", results: [] },
424
+ };
425
+ }
330
426
  const effectiveRunId = status?.runId ?? resolvedId ?? "unknown";
331
427
  const logPath = path.join(asyncDir, `subagent-log-${effectiveRunId}.md`);
332
428
  const eventsPath = path.join(asyncDir, "events.jsonl");
333
429
  if (status) {
430
+ if (params.action === "debug.run") {
431
+ const { sidecar, overlay } = debugProcessTerminal(asyncDir, status);
432
+ const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
433
+ return {
434
+ content: [{ type: "text", text: formatRunLifecycleDebug({ status, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
435
+ details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
436
+ };
437
+ }
334
438
  if (params.view === "transcript") {
335
439
  if (currentSessionId && status.sessionId !== currentSessionId) {
336
440
  return {
@@ -371,6 +475,8 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
371
475
  const steeringText = formatSteeringSummary(status);
372
476
  const processTerminal = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId })
373
477
  ?? sanitizeProcessTerminal(status.processTerminal, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId }, path.join(asyncDir, "status.json"));
478
+ const runFanoutBudgetDescriptor = readRunFanoutBudgetDescriptor(asyncDir);
479
+ const runFanoutBudget = runFanoutBudgetDescriptor ? getRunFanoutBudgetSnapshot(runFanoutBudgetDescriptor) : status.runFanoutBudget;
374
480
  let missionId: string | undefined;
375
481
  try {
376
482
  missionId = readMissionBinding(asyncDir)?.missionId;
@@ -392,6 +498,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
392
498
  statusActivityText ? `Activity: ${statusActivityText}` : undefined,
393
499
  steeringText ? `Steering: ${steeringText}` : undefined,
394
500
  `Mode: ${status.mode}`,
501
+ runFanoutBudget ? formatRunFanoutBudget(runFanoutBudget) : undefined,
395
502
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
396
503
  status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
397
504
  status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
@@ -448,14 +555,21 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
448
555
  if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
449
556
  if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
450
557
 
451
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
558
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
452
559
  }
453
560
  }
454
561
 
455
562
  if (resultPath) {
563
+ if (params.action === "debug.run") {
564
+ return {
565
+ content: [{ type: "text", text: "Run lifecycle debug needs an async run directory with status.json." }],
566
+ isError: true,
567
+ details: { mode: "single", results: [] },
568
+ };
569
+ }
456
570
  try {
457
571
  const raw = fs.readFileSync(resultPath, "utf-8");
458
- const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null }> };
572
+ const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; runId?: string; workflowKey?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null }> };
459
573
  if (params.view === "transcript") {
460
574
  try {
461
575
  return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
@@ -3,6 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
6
7
  import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
7
8
  import { shortenPath } from "../../shared/formatters.ts";
8
9
  import type { AsyncStatus, Details, ExtensionConfig } from "../../shared/types.ts";
@@ -87,7 +88,7 @@ export function scheduledRunsEnabled(config: ExtensionConfig): boolean {
87
88
  }
88
89
 
89
90
  export function scheduledRunStorePath(cwd: string, _sessionId?: string, root?: string): string {
90
- if (!root) return path.join(path.resolve(cwd), ".pi-subagents", "schedules");
91
+ if (!root) return path.join(getProjectSubagentsDir(path.resolve(cwd)), "schedules");
91
92
  const projectKey = createHash("sha256").update(path.resolve(cwd)).digest("hex").slice(0, 20);
92
93
  return path.join(root, projectKey);
93
94
  }
@@ -405,6 +406,29 @@ export class ScheduledRunManager {
405
406
  }
406
407
  }
407
408
 
409
+ observedCompletionRunIds(): Set<string> {
410
+ const runIds = new Set<string>();
411
+ for (const store of this.stores.values()) {
412
+ let ids: string[];
413
+ try {
414
+ ids = store.ids();
415
+ } catch (error) {
416
+ console.error(`Failed to inspect schedule store '${store.root}' during async completion discovery:`, error);
417
+ continue;
418
+ }
419
+ for (const id of ids) {
420
+ try {
421
+ for (const run of store.history(id)) {
422
+ if (run.state === "running" && run.asyncId) runIds.add(run.asyncId);
423
+ }
424
+ } catch (error) {
425
+ console.error(`Failed to inspect schedule '${id}' in '${store.root}' during async completion discovery:`, error);
426
+ }
427
+ }
428
+ }
429
+ return runIds;
430
+ }
431
+
408
432
  handleAsyncCompletion(payload: unknown): void {
409
433
  if (!payload || typeof payload !== "object") return;
410
434
  const data = payload as { id?: unknown; runId?: unknown; success?: unknown; state?: unknown; summary?: unknown };
@@ -1,6 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
4
+ import { releaseActiveRunIndex, updateActiveRunIndex } from "./active-run-index.ts";
5
+ import { readStatus } from "../../shared/utils.ts";
4
6
  import { DIRS, type AsyncParallelGroupStatus, type AsyncStatus, type NestedRunSummary, type SubagentRunMode } from "../../shared/types.ts";
5
7
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
6
8
  import { normalizeParallelGroups } from "./parallel-groups.ts";
@@ -84,26 +86,6 @@ function appendJsonlBestEffort(filePath: string, payload: object): void {
84
86
  }
85
87
  }
86
88
 
87
- function readStatusFile(asyncDir: string): AsyncStatus | null {
88
- const statusPath = path.join(asyncDir, "status.json");
89
- let content: string;
90
- try {
91
- content = fs.readFileSync(statusPath, "utf-8");
92
- } catch (error) {
93
- if (isNotFoundError(error)) return null;
94
- throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage(error)}`, {
95
- cause: error instanceof Error ? error : undefined,
96
- });
97
- }
98
- try {
99
- return JSON.parse(content) as AsyncStatus;
100
- } catch (error) {
101
- throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage(error)}`, {
102
- cause: error instanceof Error ? error : undefined,
103
- });
104
- }
105
- }
106
-
107
89
  interface ResultChildOutcome {
108
90
  agent?: string;
109
91
  success?: boolean;
@@ -172,7 +154,7 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
172
154
  modelAttempts: child?.modelAttempts ?? step.modelAttempts,
173
155
  };
174
156
  });
175
- return {
157
+ const terminalStatus: AsyncStatus = {
176
158
  ...status,
177
159
  state: repair.state,
178
160
  ...(status.lifecycleArtifactVersion === 3 && (!status.processTerminal || status.processTerminal.state === "pending") ? {
@@ -184,6 +166,8 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
184
166
  endedAt: status.endedAt ?? now,
185
167
  steps,
186
168
  };
169
+ delete terminalStatus.displayDismissedAt;
170
+ return terminalStatus;
187
171
  }
188
172
 
189
173
  function buildStartedStatus(asyncDir: string, startedRun: StartedRunMetadata, now: number): AsyncStatus {
@@ -277,6 +261,7 @@ function writeFailedRepair(asyncDir: string, status: AsyncStatus, resultPath: st
277
261
  const repair = buildFailedRepair(status, asyncDir, now, reason);
278
262
  writeAtomicJson(resultPath, repair.result);
279
263
  writeAtomicJson(path.join(asyncDir, "status.json"), repair.status);
264
+ if (repair.status.processTerminal?.state === "observed") releaseActiveRunIndex(asyncDir);
280
265
  appendJsonlBestEffort(path.join(asyncDir, "events.jsonl"), {
281
266
  type: "subagent.run.repaired_stale",
282
267
  ts: now,
@@ -348,7 +333,7 @@ export function checkPidLiveness(pid: number, kill: KillFn = process.kill): PidL
348
333
 
349
334
  export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOptions = {}): ReconcileAsyncRunResult {
350
335
  const now = options.now?.() ?? Date.now();
351
- const status = readStatusFile(asyncDir);
336
+ const status = readStatus(asyncDir);
352
337
  const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : undefined;
353
338
  const effectiveStatus = status ?? startedStatus;
354
339
  if (!effectiveStatus) return { status: null, repaired: false };
@@ -358,7 +343,6 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
358
343
  if (stepRecord.model !== undefined && typeof stepRecord.model !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
359
344
  if (stepRecord.thinking !== undefined && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
360
345
  }
361
-
362
346
  const runId = effectiveStatus.runId || path.basename(asyncDir);
363
347
  const resultPath = path.join(options.resultsDir ?? DIRS.results, `${runId}.json`);
364
348
  if (fs.existsSync(resultPath)) {
@@ -367,9 +351,13 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
367
351
  : undefined;
368
352
  if (terminalStatus) {
369
353
  writeAtomicJson(path.join(asyncDir, "status.json"), terminalStatus);
354
+ if (terminalStatus.processTerminal?.state === "observed") releaseActiveRunIndex(asyncDir);
370
355
  return { status: terminalStatus, repaired: true, resultPath, message: "Existing async result file was used to repair stale running status." };
371
356
  }
372
- return { status: effectiveStatus, repaired: false, resultPath };
357
+ if (effectiveStatus.displayDismissedAt === undefined) return { status: effectiveStatus, repaired: false, resultPath };
358
+ }
359
+ if (effectiveStatus.displayDismissedAt !== undefined) {
360
+ return { status: null, repaired: false, resultPath };
373
361
  }
374
362
 
375
363
  if (effectiveStatus.state !== "running" || typeof effectiveStatus.pid !== "number") {