@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -4,11 +4,14 @@ import type { AsyncStatus } from "../../shared/types.ts";
4
4
  import { readStatus } from "../../shared/utils.ts";
5
5
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
6
6
  import { encodeIndexSegment } from "./index-segment.ts";
7
+ import { isSafeNestedPathId } from "../shared/nested-path.ts";
7
8
 
8
9
  export const TERMINAL_RUN_INDEX_DIR = ".terminal-runs";
9
10
 
10
11
  const TERMINAL_RUN_INDEX_VERSION = 1;
11
12
  const TIMESTAMP_WIDTH = 16;
13
+ // Literal @ cannot occur in an encoded session key.
14
+ const TOOL_CALL_INDEX_DIR = "@tool-calls";
12
15
 
13
16
  interface TerminalRunIndexEntry {
14
17
  version: 1;
@@ -29,6 +32,14 @@ function sessionIndexDir(asyncDirRoot: string, sessionId: string): string {
29
32
  return path.join(indexRoot(asyncDirRoot), encodeIndexSegment(sessionId));
30
33
  }
31
34
 
35
+ function toolCallIndexDir(asyncDirRoot: string, toolCallId: string): string {
36
+ return path.join(indexRoot(asyncDirRoot), TOOL_CALL_INDEX_DIR, encodeIndexSegment(toolCallId));
37
+ }
38
+
39
+ function toolCallMarkerName(runId: string): string {
40
+ return `${encodeIndexSegment(runId, 250)}.json`;
41
+ }
42
+
32
43
  function markerName(endedAt: number, runId: string): string {
33
44
  return `${Math.max(0, Math.floor(endedAt)).toString().padStart(TIMESTAMP_WIDTH, "0")}-${encodeIndexSegment(runId)}.json`;
34
45
  }
@@ -58,6 +69,14 @@ export function updateTerminalRunIndex(asyncDir: string, status: AsyncStatus): v
58
69
  endedAt,
59
70
  };
60
71
  writeAtomicJson(marker, entry);
72
+ if (status.toolCallId) {
73
+ try {
74
+ writeAtomicJson(path.join(toolCallIndexDir(path.dirname(asyncDir), status.toolCallId), toolCallMarkerName(entry.runId)), entry);
75
+ } catch (error) {
76
+ // Optional aliases must not block authoritative terminal indexing or capacity release.
77
+ console.error(`Failed to write async terminal-run tool-call index for '${asyncDir}':`, error);
78
+ }
79
+ }
61
80
  }
62
81
 
63
82
  function removeInvalidMarker(marker: string): void {
@@ -89,7 +108,7 @@ function sessionDirs(asyncDirRoot: string, sessionId: string | undefined): strin
89
108
  if (sessionId) return [sessionIndexDir(asyncDirRoot, sessionId)];
90
109
  try {
91
110
  return fs.readdirSync(indexRoot(asyncDirRoot), { withFileTypes: true })
92
- .filter((entry) => entry.isDirectory())
111
+ .filter((entry) => entry.isDirectory() && entry.name !== TOOL_CALL_INDEX_DIR)
93
112
  .map((entry) => path.join(indexRoot(asyncDirRoot), entry.name));
94
113
  } catch (error) {
95
114
  const code = (error as NodeJS.ErrnoException).code;
@@ -105,6 +124,32 @@ function recentMarkerFiles(dirs: string[], limit: number): string[] {
105
124
  .map((marker) => path.join(marker.dir, marker.name));
106
125
  }
107
126
 
127
+ export function readTerminalRunToolCallIndex(asyncDirRoot: string, toolCallId: string): string[] {
128
+ const runIds: string[] = [];
129
+ for (const file of markerFiles(toolCallIndexDir(asyncDirRoot, toolCallId))) {
130
+ const marker = path.join(file.dir, file.name);
131
+ let entry: TerminalRunIndexEntry | undefined;
132
+ try {
133
+ entry = parseEntry(JSON.parse(fs.readFileSync(marker, "utf-8")));
134
+ } catch (error) {
135
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
136
+ if (!(error instanceof SyntaxError)) throw error;
137
+ }
138
+ if (!entry || !isSafeNestedPathId(entry.runId) || file.name !== toolCallMarkerName(entry.runId)) {
139
+ removeInvalidMarker(marker);
140
+ continue;
141
+ }
142
+ const status = readStatus(path.join(asyncDirRoot, entry.runId));
143
+ if (!status || !isTerminalState(status.state) || status.runId !== entry.runId
144
+ || status.sessionId !== entry.sessionId || status.toolCallId !== toolCallId) {
145
+ removeInvalidMarker(marker);
146
+ continue;
147
+ }
148
+ runIds.push(entry.runId);
149
+ }
150
+ return runIds;
151
+ }
152
+
108
153
  export function readRecentTerminalRunIndex(asyncDirRoot: string, options: { sessionId?: string; limit?: number } = {}): string[] {
109
154
  const limit = options.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.floor(options.limit));
110
155
  const candidates = recentMarkerFiles(sessionDirs(asyncDirRoot, options.sessionId), limit);
@@ -106,6 +106,7 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
106
106
  ...(sessionFile ? { sessionFile } : {}),
107
107
  ...(typeof child.success === "boolean" ? { success: child.success } : {}),
108
108
  ...(outputState ? { outputState } : {}),
109
+ ...(child.outputPartial === true ? { outputPartial: true } : {}),
109
110
  ...(structuredOutput !== undefined ? { structuredOutput } : {}),
110
111
  ...(structuredOutputPath ? { structuredOutputPath } : {}),
111
112
  ...(error ? { error } : {}),
@@ -4,6 +4,7 @@ import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
5
5
  import type { WaitSubscriptionManager } from "./wait-subscriptions.ts";
6
6
  import { finalizeToolResult } from "../../extension/tool-result.ts";
7
+ import { registerPinnedTool } from "../../extension/declaration-pinning.ts";
7
8
 
8
9
  export function registerWaitTool(
9
10
  pi: ExtensionAPI,
@@ -14,28 +15,37 @@ export function registerWaitTool(
14
15
  child?: { nestedRootRunId?: string },
15
16
  hasPendingSupervisorRequest?: () => boolean,
16
17
  ): void {
17
- const description = `Wait for background, provider, or detached work that has no native completion notification, then return.
18
-
19
- ${child ? "This child runtime does not install the root session's native completion notifier. Use blocking bg_wait to collect your owned descendants during this turn, then read the returned result references before synthesizing findings. Automatic draining at agent_end keeps owned work alive but does not synthesize its results." : "Ordinary async subagent runs already notify this session natively when they complete or need attention. In an interactive chat, return control instead of calling this merely to wait. Use this tool for provider jobs, remembered detached foreground runs, or other background work without a native notification path. Headless runs auto-drain current-session subagent work at agent_end; use this tool only when the current turn must receive non-notifying background work results."}
20
-
21
- • { } — return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
22
- • { all: true } — wait for every async run, provider item, and remembered detached foreground descendant that was active when the call began.
23
- • { id: "..." } — wait for one async or remembered detached foreground subagent run (id or prefix). Named async runs that already finished return their terminal result references.
24
- • { id: "...", nonBlocking: true } — resolve the prefix once, persist an exact-run wake subscription, and return immediately. Use this for detached work without native completion delivery; the originating interactive session wakes on completion, failure, attention, reconciliation failure, or timeout.
25
- • { stopOnAttention: false } — for blocking waits only, keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.
26
- • { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running. Omitted values use waitTool.defaultTimeoutMs, then 30 minutes. Window expiry returns a non-error window_elapsed result with active work identities.
27
-
28
- Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`bg_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : "\n\nConfigured behavior: bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`;
29
- const execute: ToolDefinition<typeof SubagentWaitParams, Details>["execute"] = async (_id, params, signal, onUpdate, ctx) => finalizeToolResult(await waitForSubagents(params, signal, {
30
- state,
31
- nestedRootRunId: child?.nestedRootRunId,
32
- events: pi.events,
33
- enabled,
34
- hasPendingSupervisorRequest,
35
- ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
36
- onUpdate,
37
- ...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
38
- }));
18
+ const description = `Wait for background work, then return. ${child ? "This child runtime has no native completion notifier: use blocking bg_wait to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results." : "Ordinary async subagent runs already wake this session natively; use bg_wait only for provider, detached, or other background work without native notification, when a same-turn result is needed."}
19
+ {} — first active run or provider item to finish or need attention.
20
+ {all:true} — all work active at call time.
21
+ {id} — one run; a finished async run returns its result references.
22
+ {id,nonBlocking:true} — subscribe to that run's wake and return now.
23
+ Timeout or a user message ends the wait without error; work keeps running.${enabled ? "" : "\nDisabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED: returns immediately."}`;
24
+ // Messages typed while the agent is busy (steer or follow-up) end open waits so they reach the model.
25
+ const userInputWaits = new Set<AbortController>();
26
+ pi.on("input", (event) => {
27
+ if (event.source === "extension" || !event.streamingBehavior) return;
28
+ for (const controller of userInputWaits) controller.abort();
29
+ });
30
+ const execute: ToolDefinition<typeof SubagentWaitParams, Details>["execute"] = async (_id, params, signal, onUpdate, ctx) => {
31
+ const userInput = new AbortController();
32
+ userInputWaits.add(userInput);
33
+ try {
34
+ return finalizeToolResult(await waitForSubagents(params, signal, {
35
+ state,
36
+ nestedRootRunId: child?.nestedRootRunId,
37
+ events: pi.events,
38
+ enabled,
39
+ hasPendingSupervisorRequest,
40
+ userInputSignal: userInput.signal,
41
+ ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
42
+ onUpdate,
43
+ ...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
44
+ }));
45
+ } finally {
46
+ userInputWaits.delete(userInput);
47
+ }
48
+ };
39
49
  const primaryTool: ToolDefinition<typeof SubagentWaitParams, Details> = {
40
50
  name: "bg_wait",
41
51
  label: "Background Wait",
@@ -43,5 +53,5 @@ Non-blocking subscriptions are visible in subagent status and differ from disabl
43
53
  parameters: SubagentWaitParams,
44
54
  execute,
45
55
  };
46
- pi.registerTool(primaryTool);
56
+ registerPinnedTool(pi, primaryTool);
47
57
  }
@@ -14,40 +14,57 @@ export type WorkflowChildProcessEvidence =
14
14
  | { state: "observed"; children: ProcessTerminal[] }
15
15
  | { state: "pending" | "unknown"; reason: string };
16
16
 
17
+ /** `unresolvedProof` is set only when a terminal child's status matches its roster run id and runner identity, and just its process proof is missing. */
18
+ export type WorkflowChildEvidence =
19
+ | { state: "resolved"; proof: ProcessTerminal }
20
+ | { state: "pending" | "unknown"; reason: string; unresolvedProof?: { status: AsyncStatus; proofState: string } };
21
+
17
22
  /**
18
23
  * Process evidence for a workflow's async children. Status proofs and capacity
19
24
  * release both use this so they cannot disagree about the same workflow.
20
- * Synchronous children run inside the workflow host and have no process of their own.
21
25
  */
22
26
  export function readWorkflowChildProcessEvidence(workflowAsyncDir: string, steps: AsyncStatus["steps"]): WorkflowChildProcessEvidence {
23
27
  if (!steps) return { state: "unknown", reason: "workflow child roster is missing" };
24
28
  const children: ProcessTerminal[] = [];
25
29
  for (const step of steps) {
26
- const label = step.workflowKey ?? step.agent;
27
- if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
28
- if (!step.async) continue;
29
- if (!step.runId || path.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
30
- const childDir = path.join(path.dirname(workflowAsyncDir), step.runId);
31
- if (!fs.existsSync(childDir)) return { state: "unknown", reason: `async workflow child ${label} directory is missing` };
32
- const childStatus = readStatus(childDir);
33
- if (!childStatus) return { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
34
- if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
35
- const recorded = childStatus.processTerminal;
36
- if (!recorded?.runnerProcessInstanceId) return { state: "unknown", reason: `async workflow child ${label} has no runner process identity` };
37
- // A runner startup failure records `not-started` in status and never writes a process-terminal sidecar.
38
- if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
39
- children.push(recorded);
40
- continue;
41
- }
42
- const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
43
- if (proof?.state !== "observed" || proof.runId !== step.runId) {
44
- return { state: !proof || proof.state === "pending" ? "pending" : "unknown", reason: `async workflow child ${label} process-terminal proof is ${proof?.state ?? "missing"}` };
45
- }
46
- children.push(proof);
30
+ const child = readWorkflowChildEvidence(workflowAsyncDir, step);
31
+ if (!child) continue;
32
+ if (child.state !== "resolved") return { state: child.state, reason: child.reason };
33
+ children.push(child.proof);
47
34
  }
48
35
  return { state: "observed", children };
49
36
  }
50
37
 
38
+ /** Evidence for one roster entry; undefined for synchronous children, which run inside the workflow host and have no process of their own. */
39
+ export function readWorkflowChildEvidence(workflowAsyncDir: string, step: NonNullable<AsyncStatus["steps"]>[number]): WorkflowChildEvidence | undefined {
40
+ const label = step.workflowKey ?? step.agent;
41
+ if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
42
+ if (!step.async) return undefined;
43
+ if (!step.runId || path.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
44
+ const childDir = path.join(path.dirname(workflowAsyncDir), step.runId);
45
+ if (!fs.existsSync(childDir)) return { state: "unknown", reason: `async workflow child ${label} directory is missing` };
46
+ const childStatus = readStatus(childDir);
47
+ if (!childStatus) return { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
48
+ if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
49
+ const recorded = childStatus.processTerminal;
50
+ if (!recorded?.runnerProcessInstanceId) return { state: "unknown", reason: `async workflow child ${label} has no runner process identity` };
51
+ // A runner startup failure records `not-started` in status and never writes a process-terminal sidecar.
52
+ if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
53
+ return { state: "resolved", proof: recorded };
54
+ }
55
+ const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
56
+ if (proof?.state !== "observed" || proof.runId !== step.runId) {
57
+ const proofState = proof?.state ?? "missing";
58
+ const bound = childStatus.runId === step.runId && typeof recorded.runnerProcessInstanceId === "string";
59
+ return {
60
+ state: !proof || proof.state === "pending" ? "pending" : "unknown",
61
+ reason: `async workflow child ${label} process-terminal proof is ${proofState}`,
62
+ ...(bound ? { unresolvedProof: { status: childStatus, proofState } } : {}),
63
+ };
64
+ }
65
+ return { state: "resolved", proof };
66
+ }
67
+
51
68
  function unresolved(runId: string, state: "pending" | "unknown", dispatchClosed: boolean, reason: string): WorkflowTerminalProof {
52
69
  return { version: 1, kind: "workflow", runId, state, dispatchClosed, reason };
53
70
  }
@@ -6,7 +6,7 @@ import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../
6
6
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
7
7
  import { deliverStopRequest, stopInboxClosedPath } from "../background/control-channel.ts";
8
8
  import { readProcessTerminal } from "../background/process-terminal.ts";
9
- import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
9
+ import { resultFilePath, resultPayloadFileForSessionRun, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
10
10
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
11
11
  import { readStatus } from "../../shared/utils.ts";
12
12
  import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
@@ -29,7 +29,7 @@ function getAsyncStopTarget(
29
29
 
30
30
  const STOP_MESSAGE = "Subagent stopped by user.";
31
31
 
32
- function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefined {
32
+ function sealPausedRun(asyncDir: string, status: AsyncStatus, resultsDir: string): string | undefined {
33
33
  const runnerProcessInstanceId = status.processTerminal?.runnerProcessInstanceId;
34
34
  if (!runnerProcessInstanceId) return "runner process identity is missing";
35
35
  const proof = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId });
@@ -37,15 +37,34 @@ function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefine
37
37
  return `process-terminal proof is ${proof?.state === "unknown" ? `unknown (${proof.reason})` : proof?.state ?? "missing"}`;
38
38
  }
39
39
  if (!status.sessionId) return "session identity is missing";
40
- const existingResultPath = resultPayloadPathForSessionRun(DIRS.results, status.sessionId, status.runId);
41
- if (!existingResultPath) return "paused result is missing";
40
+ // The validated lookup skips unreadable or foreign files; those must be refused below, not replaced.
41
+ const existingResultPath = resultPayloadPathForSessionRun(resultsDir, status.sessionId, status.runId)
42
+ ?? resultPayloadFileForSessionRun(resultsDir, status.sessionId, status.runId);
42
43
  let existingResult: Record<string, unknown>;
43
- try {
44
- const parsed: unknown = JSON.parse(fs.readFileSync(existingResultPath, "utf-8"));
45
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("result is not an object");
46
- existingResult = parsed as Record<string, unknown>;
47
- } catch (error) {
48
- return `paused result is unavailable: ${error instanceof Error ? error.message : String(error)}`;
44
+ if (!existingResultPath) {
45
+ // Delivery deletes the paused result, and an interrupted parent may never have received one; seal from status.
46
+ existingResult = {
47
+ id: status.runId,
48
+ mode: status.mode,
49
+ sessionId: status.sessionId,
50
+ asyncDir,
51
+ ...(status.completionOwnerId ? { completionOwnerId: status.completionOwnerId } : {}),
52
+ ...(status.toolCallId ? { toolCallId: status.toolCallId } : {}),
53
+ results: (status.steps ?? []).map((step) => ({
54
+ agent: step.agent,
55
+ success: step.status === "complete" || step.status === "completed",
56
+ ...(step.error ? { error: step.error } : {}),
57
+ ...(step.exitCode !== undefined ? { exitCode: step.exitCode } : {}),
58
+ })),
59
+ };
60
+ } else {
61
+ try {
62
+ const parsed: unknown = JSON.parse(fs.readFileSync(existingResultPath, "utf-8"));
63
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("result is not an object");
64
+ existingResult = parsed as Record<string, unknown>;
65
+ } catch (error) {
66
+ return `paused result is unavailable: ${error instanceof Error ? error.message : String(error)}`;
67
+ }
49
68
  }
50
69
  const resultRunId = typeof existingResult.runId === "string" ? existingResult.runId : existingResult.id;
51
70
  if (resultRunId !== status.runId || existingResult.sessionId !== status.sessionId) {
@@ -96,11 +115,22 @@ function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefine
96
115
  steps,
97
116
  };
98
117
  delete stoppedStatus.activityState;
99
- writeAsyncResultFile(resultFilePath(DIRS.results, status.runId), stoppedResult);
118
+ writeAsyncResultFile(resultFilePath(resultsDir, status.runId), stoppedResult);
100
119
  writeAtomicJson(path.join(asyncDir, "status.json"), stoppedStatus);
101
120
  updateActiveRunIndex(asyncDir, "stopped", status.toolCallId, { retryCapacityErrors: true, terminalIndexBeforeRelease: true });
102
121
  }
103
122
 
123
+ /** After ownership/state checks, deliver stop and seal paused whole runs only with native terminal proof. */
124
+ export function deliverAsyncRunStop(
125
+ input: Parameters<typeof deliverStopRequest>[0] & { status: AsyncStatus; resultsDir?: string },
126
+ ): string | undefined {
127
+ const { status, resultsDir = DIRS.results, ...delivery } = input;
128
+ const pausedWholeRun = status.state === "paused" && delivery.childId === undefined && delivery.targetIndex === undefined;
129
+ // A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
130
+ if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(delivery.asyncDir)))) deliverStopRequest(delivery);
131
+ if (pausedWholeRun) return sealPausedRun(delivery.asyncDir, status, resultsDir);
132
+ }
133
+
104
134
  export function stopAsyncRun(
105
135
  state: SubagentState,
106
136
  runId: string | undefined,
@@ -158,17 +188,13 @@ export function stopAsyncRun(
158
188
  }
159
189
  }
160
190
  try {
161
- // A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
162
- if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(target.asyncDir)))) deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
163
- if (pausedWholeRun) {
164
- const failure = sealPausedRun(target.asyncDir, status);
165
- if (failure) {
166
- return {
167
- content: [{ type: "text", text: `Stop request persisted for paused async run ${target.asyncId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.` }],
168
- isError: true,
169
- details: { mode: "management", results: [] },
170
- };
171
- }
191
+ const failure = deliverAsyncRunStop({ asyncDir: target.asyncDir, status, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
192
+ if (failure) {
193
+ return {
194
+ content: [{ type: "text", text: `Stop request persisted for paused async run ${target.asyncId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.` }],
195
+ isError: true,
196
+ details: { mode: "management", results: [] },
197
+ };
172
198
  }
173
199
  const tracked = state.asyncJobs.get(target.asyncId);
174
200
  if (tracked) {
@@ -0,0 +1,41 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { Details, SubagentState } from "../../shared/types.ts";
3
+ import { readStatus } from "../../shared/utils.ts";
4
+ import type { ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
5
+ import { supervisorChannelDir } from "../shared/child-tool-plan.ts";
6
+ import { controlChildCommand, type CommandOperation } from "../shared/child-commands.ts";
7
+
8
+ function commandChildren(state: SubagentState, target: ResolvedSubagentRunId): Array<{ index: number; agent: string }> {
9
+ if (!state.currentSessionId) throw new Error("Command controls require an owning parent session.");
10
+ if (target.kind === "nested") throw new Error("Command controls support direct local Pi children only.");
11
+ if (target.kind === "foreground") {
12
+ const live = state.foregroundControls.get(target.id);
13
+ const retained = state.foregroundRuns?.get(target.id);
14
+ if ((live?.sessionId ?? retained?.sessionId) !== state.currentSessionId) throw new Error("Run is not owned by this session.");
15
+ if (live?.activeChildren?.size) return [...live.activeChildren.values()].map(({ index, agent }) => ({ index, agent }));
16
+ if (live?.currentAgent) return [{ index: live.currentIndex ?? 0, agent: live.currentAgent }];
17
+ return retained?.children.map(({ index, agent }) => ({ index, agent })) ?? [];
18
+ }
19
+ const status = target.location.asyncDir ? readStatus(target.location.asyncDir) : undefined;
20
+ if (status?.sessionId !== state.currentSessionId) throw new Error("Run is not owned by this session.");
21
+ return status.steps?.map((step, index) => ({ index, agent: step.agent })) ?? [];
22
+ }
23
+
24
+ export async function commandAction(input: {
25
+ state: SubagentState;
26
+ target: ResolvedSubagentRunId;
27
+ operation: CommandOperation;
28
+ index?: number;
29
+ toolCallId?: string;
30
+ signal?: AbortSignal;
31
+ }): Promise<AgentToolResult<Details>> {
32
+ const children = commandChildren(input.state, input.target);
33
+ if (input.index === undefined && children.length !== 1) throw new Error("Command controls require an explicit child index for multi-child runs.");
34
+ const child = input.index === undefined ? children[0] : children.find(({ index }) => index === input.index);
35
+ if (!child) throw new Error(`No child index ${input.index ?? 0} in this run.`);
36
+ const result = await controlChildCommand(supervisorChannelDir(input.target.id, child.agent, child.index), input.operation, input.toolCallId, input.signal);
37
+ return {
38
+ content: [{ type: "text", text: JSON.stringify({ runId: input.target.id, index: child.index, commands: result.commands, closed: result.closed }) }],
39
+ details: { mode: "management", results: [], commands: result.commands },
40
+ };
41
+ }