@xzzpig/pi-subagents 0.14.0 → 0.15.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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -3,13 +3,18 @@ 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 { writeAtomicJson } from "../../shared/atomic-json.ts";
6
- import type { AsyncStatus, Details, SubagentState, ToolBudgetConfig } from "../../shared/types.ts";
6
+ import type { AsyncStatus, Details, SteerActionResult, SubagentState, ToolBudgetConfig } from "../../shared/types.ts";
7
7
  import { readStatus } from "../../shared/utils.ts";
8
8
  import { deliverInterruptRequest, queueRevivalBrief, requestAsyncSteer, type SteerDeliveryMode, type SteerRequest } from "../background/control-channel.ts";
9
9
  import { resolveAsyncResumeTarget } from "../background/async-resume.ts";
10
10
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
11
11
  import { actionResultFromSteeringStatus, claimSteeringRecovery, createSteeringStatus, recordSteeringRequest, remainingSteeringRecoveryLimits, steeringReceipt, updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
12
12
 
13
+ function steerTargetsAccepted(result: Pick<SteerActionResult, "targets"> | undefined): boolean {
14
+ const targets = result?.targets ?? [];
15
+ return targets.length > 0 && targets.every((target) => target.state === "queued" || target.state === "delivered");
16
+ }
17
+
13
18
  export function canQueueRetainedAsyncFollowUp(status: AsyncStatus, index?: number): boolean {
14
19
  const steps = status.steps ?? [];
15
20
  return status.state === "complete"
@@ -26,6 +31,7 @@ export async function steerAsyncRun(input: {
26
31
  message: string;
27
32
  mode?: SteerDeliveryMode;
28
33
  index?: number;
34
+ findPendingAsks?: (target: { runId: string; agent: string; childIndex: number }) => string[];
29
35
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
30
36
  location: { asyncDir: string | null };
31
37
  signal?: AbortSignal;
@@ -44,6 +50,24 @@ export async function steerAsyncRun(input: {
44
50
  };
45
51
  }
46
52
  const asyncDir = input.location.asyncDir;
53
+ const snapshot = input.findPendingAsks ? readStatus(asyncDir) : null;
54
+ if (snapshot?.mode === "single"
55
+ && (!input.state.currentSessionId || snapshot.sessionId === input.state.currentSessionId)
56
+ && (snapshot.state === "running" || snapshot.state === "queued")
57
+ && snapshot.steps?.length === 1 && (input.index === undefined || input.index === 0)
58
+ && (snapshot.steps[0]?.status === "running" || snapshot.steps[0]?.status === "pending")) {
59
+ const asks = input.findPendingAsks?.({ runId: snapshot.runId, agent: snapshot.steps[0].agent, childIndex: 0 }) ?? [];
60
+ if (asks.length > 0) {
61
+ const replies = asks.map(replyTo => `subagent_supervisor(${JSON.stringify({ action: "reply", replyTo, message: "<explicit answer>" })})`).join("\n");
62
+ return {
63
+ content: [{ type: "text", text: `Steering not delivered or queued: async run ${snapshot.runId} is blocked on ${asks.length === 1 ? "a pending supervisor ask" : "ambiguous pending supervisor asks"}. No reply or recovery was attempted. Reply explicitly${asks.length > 1 ? " to the intended request ID" : ""}:\n${replies}` }],
64
+ isError: true,
65
+ details: { mode: "management", results: [] },
66
+ };
67
+ }
68
+ }
69
+ // The read-only snapshot precedes even stale-run reconciliation. An ask arriving
70
+ // later does not make a runner acknowledgement proof of consumption or unblocking.
47
71
  const status = reconcileAsyncRun(asyncDir, { kill: input.kill }).status;
48
72
  if (input.state.currentSessionId && status?.sessionId !== input.state.currentSessionId) {
49
73
  return {
@@ -151,9 +175,11 @@ export async function steerAsyncRun(input: {
151
175
  }
152
176
  const finalStatus = readStatus(asyncDir);
153
177
  const finalResult = finalStatus?.steering ? actionResultFromSteeringStatus(finalStatus.steering, status.runId, requestId) : undefined;
154
- if (finalResult?.state === "delivered") {
155
- return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering delivered for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: finalResult } };
156
- }
178
+ const acceptedReply = (accepted: SteerActionResult): AgentToolResult<Details> => {
179
+ const acceptedState = accepted.state === "delivered" ? "delivered" : "queued";
180
+ return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering ${acceptedState} for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: accepted } };
181
+ };
182
+ if (finalResult && steerTargetsAccepted(finalResult)) return acceptedReply(finalResult);
157
183
  const running = (finalStatus?.steps ?? status.steps ?? []).filter((step) => step.status === "running");
158
184
  const recoveryAllowed = (input.mode ?? "steer") === "steer" && status.mode === "single" && status.isNested !== true && running.length === 1 && Boolean(finalStatus?.steering) && (input.index === undefined || input.index === 0);
159
185
  if (recoveryAllowed && finalResult?.state !== "scheduled" && input.recover) {
@@ -167,17 +193,21 @@ export async function steerAsyncRun(input: {
167
193
  try {
168
194
  const latest = readStatus(asyncDir);
169
195
  const latestResult = latest?.steering ? actionResultFromSteeringStatus(latest.steering, status.runId, requestId) : undefined;
170
- if (latestResult?.state === "delivered") return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering delivered for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: latestResult } };
196
+ if (latestResult && steerTargetsAccepted(latestResult)) return acceptedReply(latestResult);
171
197
  const committedAt = Date.now();
172
198
  input.onBeforeRecoveryClaim?.(requestId, committedAt);
173
199
  const { claimPath, markerPath } = claimSteeringRecovery(asyncDir, { requestId, sourceRunId: status.runId, committedAt });
174
200
  input.onRecoveryCommitted?.(requestId, committedAt);
175
201
  const preCommitStatus = readStatus(asyncDir);
176
202
  const preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : undefined;
177
- if (preCommitResult?.state === "delivered" && preCommitResult.targets.every((target) => target.deliveredAt !== undefined && target.deliveredAt <= committedAt)) {
203
+ if (
204
+ preCommitResult
205
+ && preCommitResult.targets.length > 0
206
+ && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))
207
+ ) {
178
208
  fs.rmSync(markerPath, { force: true });
179
209
  fs.rmSync(claimPath, { force: true });
180
- return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering delivered for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: preCommitResult } };
210
+ return acceptedReply(preCommitResult);
181
211
  }
182
212
  try {
183
213
  deliverInterruptRequest({ asyncDir, source: "steering-recovery" });
@@ -1,7 +1,12 @@
1
+ import * as fs from "node:fs";
1
2
  import * as path from "node:path";
2
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
- import type { Details, SubagentState } from "../../shared/types.ts";
4
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../shared/types.ts";
6
+ import { updateActiveRunIndex } from "../background/active-run-index.ts";
4
7
  import { deliverStopRequest } from "../background/control-channel.ts";
8
+ import { readProcessTerminal } from "../background/process-terminal.ts";
9
+ import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
5
10
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
6
11
  import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
7
12
 
@@ -21,6 +26,80 @@ function getAsyncStopTarget(
21
26
  return direct ? { asyncId: direct.asyncId, asyncDir: direct.asyncDir } : undefined;
22
27
  }
23
28
 
29
+ const STOP_MESSAGE = "Subagent stopped by user.";
30
+
31
+ function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefined {
32
+ const runnerProcessInstanceId = status.processTerminal?.runnerProcessInstanceId;
33
+ if (!runnerProcessInstanceId) return "runner process identity is missing";
34
+ const proof = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId });
35
+ if (proof?.state !== "observed" || proof.runId !== status.runId || proof.runnerProcessInstanceId !== runnerProcessInstanceId) {
36
+ return `process-terminal proof is ${proof?.state === "unknown" ? `unknown (${proof.reason})` : proof?.state ?? "missing"}`;
37
+ }
38
+ if (!status.sessionId) return "session identity is missing";
39
+ const existingResultPath = resultPayloadPathForSessionRun(DIRS.results, status.sessionId, status.runId);
40
+ if (!existingResultPath) return "paused result is missing";
41
+ let existingResult: Record<string, unknown>;
42
+ try {
43
+ const parsed: unknown = JSON.parse(fs.readFileSync(existingResultPath, "utf-8"));
44
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("result is not an object");
45
+ existingResult = parsed as Record<string, unknown>;
46
+ } catch (error) {
47
+ return `paused result is unavailable: ${error instanceof Error ? error.message : String(error)}`;
48
+ }
49
+ const resultRunId = typeof existingResult.runId === "string" ? existingResult.runId : existingResult.id;
50
+ if (resultRunId !== status.runId || existingResult.sessionId !== status.sessionId) {
51
+ return "paused result identity does not match the run";
52
+ }
53
+
54
+ const now = Date.now();
55
+ const steps = (status.steps ?? []).map((step) => {
56
+ if (step.status !== "pending" && step.status !== "running" && step.status !== "paused") return step;
57
+ const { activityState: _activityState, ...rest } = step;
58
+ return {
59
+ ...rest,
60
+ status: "stopped" as const,
61
+ error: STOP_MESSAGE,
62
+ exitCode: 1,
63
+ stopped: true,
64
+ endedAt: now,
65
+ durationMs: step.startedAt ? now - step.startedAt : 0,
66
+ lastActivityAt: now,
67
+ };
68
+ });
69
+ const results = Array.isArray(existingResult.results)
70
+ ? existingResult.results.map((entry, index) => {
71
+ const stepState = status.steps?.[index]?.status;
72
+ if ((stepState !== "pending" && stepState !== "running" && stepState !== "paused") || !entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
73
+ const { interrupted: _interrupted, ...result } = entry as Record<string, unknown>;
74
+ return { ...result, output: STOP_MESSAGE, error: STOP_MESSAGE, success: false, exitCode: 1, stopped: true };
75
+ })
76
+ : existingResult.results;
77
+ const stoppedResult = {
78
+ ...existingResult,
79
+ success: false,
80
+ state: "stopped",
81
+ summary: STOP_MESSAGE,
82
+ error: STOP_MESSAGE,
83
+ stopped: true,
84
+ exitCode: 1,
85
+ timestamp: now,
86
+ ...(Array.isArray(existingResult.results) ? { results } : {}),
87
+ };
88
+ const stoppedStatus: AsyncStatus = {
89
+ ...status,
90
+ state: "stopped",
91
+ stopped: true,
92
+ error: STOP_MESSAGE,
93
+ endedAt: now,
94
+ lastUpdate: now,
95
+ steps,
96
+ };
97
+ delete stoppedStatus.activityState;
98
+ writeAsyncResultFile(resultFilePath(DIRS.results, status.runId), stoppedResult);
99
+ writeAtomicJson(path.join(asyncDir, "status.json"), stoppedStatus);
100
+ updateActiveRunIndex(asyncDir, "stopped", status.toolCallId, { retryCapacityErrors: true, terminalIndexBeforeRelease: true });
101
+ }
102
+
24
103
  export function stopAsyncRun(
25
104
  state: SubagentState,
26
105
  runId: string | undefined,
@@ -38,7 +117,8 @@ export function stopAsyncRun(
38
117
  details: { mode: "management", results: [] },
39
118
  };
40
119
  }
41
- if (!status || (status.state !== "running" && status.state !== "queued")) {
120
+ const pausedWholeRun = status?.state === "paused" && childId === undefined;
121
+ if (!status || (status.state !== "running" && status.state !== "queued" && !pausedWholeRun)) {
42
122
  return {
43
123
  content: [{ type: "text", text: `No running or queued async run was found for '${runId ?? "current"}'.` }],
44
124
  isError: true,
@@ -66,13 +146,23 @@ export function stopAsyncRun(
66
146
  }
67
147
  try {
68
148
  deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
149
+ if (pausedWholeRun) {
150
+ const failure = sealPausedRun(target.asyncDir, status);
151
+ if (failure) {
152
+ return {
153
+ 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.` }],
154
+ isError: true,
155
+ details: { mode: "management", results: [] },
156
+ };
157
+ }
158
+ }
69
159
  const tracked = state.asyncJobs.get(target.asyncId);
70
160
  if (tracked) {
71
161
  tracked.activityState = undefined;
72
162
  tracked.updatedAt = Date.now();
73
163
  }
74
164
  return {
75
- content: [{ type: "text", text: child ? `Stop requested for child ${child.id} in async run ${target.asyncId}.` : `Stop requested for async run ${target.asyncId}.` }],
165
+ content: [{ type: "text", text: pausedWholeRun ? `Stopped paused async run ${target.asyncId}.` : child ? `Stop requested for child ${child.id} in async run ${target.asyncId}.` : `Stop requested for async run ${target.asyncId}.` }],
76
166
  details: { mode: "management", results: [] },
77
167
  };
78
168
  } catch (error) {