pi-subagents 0.84.0 → 0.86.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 (210) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-JG4QKI5M.js → chunk-2IYBCYFU.js} +214 -97
  5. package/bundle/{chunk-V2BZYLEP.js → chunk-374MZFF4.js} +7 -2
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-3RKFH2UZ.js} +11 -156
  7. package/bundle/{chunk-F4ASL6OV.js → chunk-5H4BICQZ.js} +1 -1
  8. package/bundle/{chunk-PALJGGYC.js → chunk-6VD7BGIC.js} +6 -3
  9. package/bundle/{chunk-C5P5CHYK.js → chunk-77ASNIEM.js} +1 -1
  10. package/bundle/{chunk-XDQORLZ5.js → chunk-7ADDXUGF.js} +15 -6
  11. package/bundle/{chunk-PV63UFUR.js → chunk-7QA7ZA46.js} +183 -28
  12. package/bundle/{chunk-NKQ6JNAS.js → chunk-7ZUFN6ME.js} +2 -1
  13. package/bundle/{chunk-SSG7IEP5.js → chunk-A637IMAO.js} +2 -2
  14. package/bundle/{chunk-L3WFKBEI.js → chunk-BGXEAYUM.js} +247 -153
  15. package/bundle/{chunk-J5YL7LYR.js → chunk-BU6PFPVX.js} +59 -27
  16. package/bundle/{chunk-DZDETGRJ.js → chunk-BWC2LVII.js} +259 -216
  17. package/bundle/{chunk-CGN2TVE7.js → chunk-GJGTMLPE.js} +322 -18
  18. package/bundle/{chunk-D3JAFGMO.js → chunk-GRJHIXYF.js} +1 -1
  19. package/bundle/chunk-HXRB42AF.js +108 -0
  20. package/bundle/{chunk-LFDBD4PW.js → chunk-LGINOOY5.js} +2 -2
  21. package/bundle/{chunk-G2Z6ZH26.js → chunk-NAFLUJ26.js} +1 -1
  22. package/bundle/{chunk-235AWJUQ.js → chunk-O3YH7XIY.js} +324 -111
  23. package/bundle/{chunk-2DHZTCOL.js → chunk-PYOAIN3V.js} +2 -2
  24. package/bundle/{chunk-LNRJCP2Y.js → chunk-QGO6HXHG.js} +417 -242
  25. package/bundle/{chunk-VQVVHSY6.js → chunk-QM3JGE4W.js} +22 -11
  26. package/bundle/{chunk-2S4K53MV.js → chunk-S2Q75LP3.js} +1 -1
  27. package/bundle/{chunk-NENDSQUY.js → chunk-UR7OW5S7.js} +9 -6
  28. package/bundle/{chunk-AKOIVLA5.js → chunk-WN2E5XHN.js} +135 -77
  29. package/bundle/{chunk-2D52JFLF.js → chunk-YK3QYNLE.js} +41 -117
  30. package/bundle/{chunk-7BWGNDNK.js → chunk-ZJJCPV3L.js} +190 -1177
  31. package/bundle/chunk-ZPY5QZCS.js +1067 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +23 -2
  38. package/docs/configuration.md +4 -4
  39. package/docs/extension-api.md +16 -1
  40. package/docs/tool-reference.md +2 -0
  41. package/docs/workflows.md +30 -2
  42. package/package.json +1 -1
  43. package/src/agents/agent-management.js +27 -11
  44. package/src/agents/agent-memory.d.ts +1 -4
  45. package/src/agents/agent-memory.js +1 -4
  46. package/src/agents/agents.d.ts +1 -3
  47. package/src/agents/agents.js +7 -6
  48. package/src/agents/frontmatter.js +1 -8
  49. package/src/agents/global-npm-root.d.ts +1 -0
  50. package/src/agents/global-npm-root.js +11 -3
  51. package/src/agents/skills.d.ts +0 -3
  52. package/src/agents/skills.js +0 -3
  53. package/src/extension/config.js +7 -1
  54. package/src/extension/herdr-pi-bridge.js +10 -2
  55. package/src/extension/index.d.ts +0 -13
  56. package/src/extension/index.js +43 -32
  57. package/src/extension/public-execution.d.ts +1 -0
  58. package/src/extension/public-execution.js +4 -0
  59. package/src/extension/reply-workflow-script.js +24 -4
  60. package/src/extension/schemas.d.ts +8 -3
  61. package/src/extension/schemas.js +5 -3
  62. package/src/extension/session-switch.d.ts +25 -0
  63. package/src/extension/session-switch.js +138 -0
  64. package/src/extension/subagent-guide.d.ts +1 -1
  65. package/src/extension/subagent-guide.js +1 -1
  66. package/src/extension/subagent-launch-tool.d.ts +25 -0
  67. package/src/extension/subagent-launch-tool.js +48 -0
  68. package/src/extension/tool-activation.js +35 -12
  69. package/src/extension/tool-description.d.ts +1 -1
  70. package/src/extension/tool-description.js +14 -8
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -9
  80. package/src/runs/background/async-execution.js +62 -27
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.js +2 -1
  86. package/src/runs/background/boot-id.d.ts +1 -3
  87. package/src/runs/background/boot-id.js +1 -3
  88. package/src/runs/background/completion-batcher.d.ts +3 -4
  89. package/src/runs/background/completion-batcher.js +2 -3
  90. package/src/runs/background/control-channel.d.ts +0 -6
  91. package/src/runs/background/control-channel.js +0 -6
  92. package/src/runs/background/fleet-view.js +2 -3
  93. package/src/runs/background/notify.d.ts +0 -2
  94. package/src/runs/background/notify.js +0 -2
  95. package/src/runs/background/result-watcher.d.ts +1 -0
  96. package/src/runs/background/result-watcher.js +59 -29
  97. package/src/runs/background/resume-guidance.js +4 -2
  98. package/src/runs/background/retained-children.js +2 -1
  99. package/src/runs/background/run-child-session.d.ts +0 -1
  100. package/src/runs/background/run-child-session.js +1 -1
  101. package/src/runs/background/run-status.js +9 -7
  102. package/src/runs/background/scheduled-runs.d.ts +3 -1
  103. package/src/runs/background/scheduled-runs.js +13 -16
  104. package/src/runs/background/subagent-runner.d.ts +2 -4
  105. package/src/runs/background/subagent-runner.js +15 -12
  106. package/src/runs/background/subagent-wait.js +12 -15
  107. package/src/runs/background/wait-config.d.ts +2 -0
  108. package/src/runs/background/wait-config.js +17 -3
  109. package/src/runs/background/wait-tool.js +4 -2
  110. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  111. package/src/runs/background/workflow-terminal-proof.js +0 -1
  112. package/src/runs/foreground/execution.d.ts +0 -3
  113. package/src/runs/foreground/execution.js +17 -9
  114. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  115. package/src/runs/foreground/subagent-executor.js +107 -26
  116. package/src/runs/shared/acceptance.js +69 -26
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  128. package/src/runs/shared/external-cli-contract.js +18 -13
  129. package/src/runs/shared/external-cli-runner.js +26 -6
  130. package/src/runs/shared/herdr-connection.js +2 -1
  131. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  132. package/src/runs/shared/herdr-pane-host.js +17 -1
  133. package/src/runs/shared/herdr-placed-run.js +48 -22
  134. package/src/runs/shared/lane-metadata.d.ts +0 -1
  135. package/src/runs/shared/lane-metadata.js +0 -1
  136. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  137. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  138. package/src/runs/shared/model-resolution.d.ts +2 -2
  139. package/src/runs/shared/model-resolution.js +7 -1
  140. package/src/runs/shared/model-scope.d.ts +1 -5
  141. package/src/runs/shared/model-scope.js +1 -5
  142. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  143. package/src/runs/shared/mutation-evidence.js +52 -7
  144. package/src/runs/shared/nested-events.d.ts +1 -0
  145. package/src/runs/shared/nested-events.js +1 -1
  146. package/src/runs/shared/parallel-utils.d.ts +0 -1
  147. package/src/runs/shared/permissions.js +5 -3
  148. package/src/runs/shared/placement-host.d.ts +5 -1
  149. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  150. package/src/runs/shared/rex-pane-host.js +0 -2
  151. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  152. package/src/runs/shared/run-launch-folder.js +21 -0
  153. package/src/runs/shared/runner-launcher.d.ts +12 -1
  154. package/src/runs/shared/runner-launcher.js +16 -0
  155. package/src/runs/shared/single-output.d.ts +3 -3
  156. package/src/runs/shared/single-output.js +5 -3
  157. package/src/runs/shared/structured-output.d.ts +8 -0
  158. package/src/runs/shared/structured-output.js +40 -5
  159. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  160. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  161. package/src/runs/shared/tool-timeout.js +2 -1
  162. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  163. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  164. package/src/runs/shared/worktree.d.ts +3 -0
  165. package/src/runs/shared/worktree.js +20 -0
  166. package/src/shared/capacity-resilient-json.d.ts +1 -1
  167. package/src/shared/child-cache-retention.d.ts +1 -2
  168. package/src/shared/child-cache-retention.js +1 -2
  169. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  170. package/src/shared/fleet-transcript-reader.js +333 -0
  171. package/src/shared/formatters.d.ts +0 -18
  172. package/src/shared/formatters.js +0 -18
  173. package/src/shared/session-succession.d.ts +16 -1
  174. package/src/shared/session-succession.js +41 -2
  175. package/src/shared/session-warnings.d.ts +7 -0
  176. package/src/shared/session-warnings.js +26 -0
  177. package/src/shared/settings.d.ts +0 -23
  178. package/src/shared/settings.js +3 -35
  179. package/src/shared/types.d.ts +85 -59
  180. package/src/shared/types.js +0 -12
  181. package/src/shared/utils.d.ts +0 -14
  182. package/src/shared/utils.js +0 -22
  183. package/src/shared/wait-tool-name.d.ts +8 -0
  184. package/src/shared/wait-tool-name.js +13 -0
  185. package/src/slash/slash-commands.js +2 -1
  186. package/src/slash/subagent-cost.d.ts +3 -2
  187. package/src/slash/subagent-cost.js +22 -3
  188. package/src/slash/subagents-admin.js +0 -1
  189. package/src/tui/fleet-status.d.ts +0 -5
  190. package/src/tui/fleet-status.js +4 -24
  191. package/src/tui/fleet-transcript.d.ts +1 -44
  192. package/src/tui/fleet-transcript.js +1 -327
  193. package/src/tui/fleet.js +6 -4
  194. package/src/tui/render.d.ts +0 -9
  195. package/src/tui/render.js +161 -66
  196. package/src/tui/subagent-messages.js +3 -2
  197. package/src/watchdog/register-child.d.ts +2 -3
  198. package/src/watchdog/register-child.js +2 -3
  199. package/src/watchdog/turn-delta.js +2 -1
  200. package/src/workflows/scripted-workflow.js +241 -20
  201. package/src/workflows/workflow-launch-record.d.ts +15 -6
  202. package/src/workflows/workflow-launch-record.js +30 -12
  203. package/src/workflows/workflow-receipt.js +36 -53
  204. package/src/workflows/workflow-resume-claim.js +2 -2
  205. package/src/workflows/workflow-resume.d.ts +1 -1
  206. package/src/workflows/workflow-resume.js +11 -8
  207. package/src/workflows/workflow-script-worker.d.ts +13 -0
  208. package/src/workflows/workflow-script-worker.js +79 -0
  209. package/workflow-script-process.cjs +36 -0
  210. package/workflow-script-worker.cjs +4 -1
@@ -5,7 +5,7 @@ import { discoverAgents, findBlockingAgentDiagnostic, formatAvailableAgentLines,
5
5
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.js";
6
6
  import { writeAtomicJson } from "../../shared/atomic-json.js";
7
7
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.js";
8
- import { isStorageCapacityError } from "../../shared/file-system-retry.js";
8
+ import { reportSessionWarning } from "../../shared/session-warnings.js";
9
9
  import { resolveEffectiveThinking, toModelInfo } from "../../shared/model-info.js";
10
10
  import { beginForegroundChild, finishForegroundChild, foregroundSchedulingSettled, settleForegroundSchedulingOwner, updateForegroundChild, } from "./foreground-control.js";
11
11
  import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.js";
@@ -15,6 +15,7 @@ import { handleManagementAction } from "../../agents/agent-management.js";
15
15
  import { handleRefinementAction } from "../../agents/agent-refinements.js";
16
16
  import { buildDoctorReport } from "../../extension/doctor.js";
17
17
  import { readSubagentGuide } from "../../extension/subagent-guide.js";
18
+ import { approveWorkflowChildLaunch } from "../../extension/subagent-launch-tool.js";
18
19
  import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.js";
19
20
  import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.js";
20
21
  import { disabledFeatureNotice, disabledFeatureSectionNotice, disabledFeatureUseError, resolveDisabledFeatureSurface } from "../../shared/disabled-features.js";
@@ -37,7 +38,7 @@ import { isScheduledRunAction } from "../background/scheduled-runs.js";
37
38
  import { encodeIndexSegment } from "../background/index-segment.js";
38
39
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.js";
39
40
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.js";
40
- import { acceptanceHasTypedVerify, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.js";
41
+ import { acceptanceHasTypedVerify, normalizeAcceptanceInput, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.js";
41
42
  import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.js";
42
43
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.js";
43
44
  import { resolveCurrentSessionId } from "../../shared/session-identity.js";
@@ -84,7 +85,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.js";
84
85
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.js";
85
86
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
86
87
  import { formatHerdrMachineRunnerUnsupported, resolveMachinePlacement } from "../shared/herdr-machine.js";
87
- import { lookupRunnerLauncher, resolveAgentRunnerLauncher } from "../shared/runner-launcher.js";
88
+ import { checkRequiredRunnerLauncher, lookupRunnerLauncher, REQUIRE_LAUNCHER_SHAPE_ERROR, resolveAgentRunnerLauncher } from "../shared/runner-launcher.js";
88
89
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.js";
89
90
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.js";
90
91
  import { attachMissionToLaunchResult, missionAcceptanceStatus, prepareMissionLaunch, writeMissionAsyncBinding } from "../../missions/lifecycle.js";
@@ -111,13 +112,14 @@ import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflow
111
112
  import { authorizeWorkflowResourceHost, claimWorkflowChildPermit, consumeWorkflowResourcePermit, validateWorkflowChildPermitRoot, } from "../../shared/workflow-child-permit.js";
112
113
  import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveStructuredWorkflowResource, resolveWorkflowResource } from "../../workflows/workflow-resources.js";
113
114
  import { writeWorkflowLaunchRecord } from "../../workflows/workflow-launch-record.js";
114
- import { stableJsonDigest } from "../../shared/launch-contract.js";
115
+ import { agentDefinitionDigest, stableJsonDigest } from "../../shared/launch-contract.js";
115
116
  import { cleanupWorktrees, createWorktrees, preflightWorktreeSource, withWorktreeTransaction, diffWorktrees, formatWorktreeDiffSummary, } from "../shared/worktree.js";
116
117
  import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.js";
117
118
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.js";
118
119
  import { DIRS, DEFAULT_ARTIFACT_CONFIG, DEFAULT_MAX_OUTPUT, DEFAULT_FORK_PREAMBLE, SUBAGENT_ACTIONS, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, checkSubagentDepth, resolveChildMaxSubagentDepth, resolveCurrentMaxSubagentDepth, resolveMaxSubagentSpawnsPerRun, truncateOutput, wrapForkTask, } from "../../shared/types.js";
119
120
  import { deriveChildSessionName } from "../../shared/child-session-name.js";
120
121
  import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.js";
122
+ import { waitToolName } from "../../shared/wait-tool-name.js";
121
123
  const MUTATING_MANAGEMENT_ACTIONS = new Set(["command.yield", "command.cancel", "create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
122
124
  const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["command.cancel", "delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
123
125
  function resolveSteerDeliveryMode(mode) {
@@ -177,6 +179,47 @@ function inheritedRunFanoutBudget(deps) {
177
179
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
178
180
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
179
181
  }
182
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents) {
183
+ // prepareWorkflowLaunchParams turns a retained resume into { action: "resume", id, message }.
184
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : undefined;
185
+ const agent = request.agent ?? scriptAgent;
186
+ const task = resume !== undefined ? request.message : request.task;
187
+ // cwd is where execute runs a fresh local child. A resumed child keeps its retained directory, and a
188
+ // placed child's cwd names a directory on its machine, so neither gets a local cwd here.
189
+ const scope = resolveExecutionAgentScope(request.agentScope);
190
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents(dir, scope).agents).agent : undefined;
191
+ const ctxAgent = request.machine === undefined ? findAgent(ctxCwd) : undefined;
192
+ const placed = request.machine !== undefined || ctxAgent?.machine !== undefined;
193
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
194
+ const cwd = resume === undefined && !placed ? runCwd : undefined;
195
+ // Mirrors applySingleAgentLaunchDefaults: the agent's defaultAcceptance applies only to a fresh launch with no
196
+ // acceptance (gate is already acceptance here). A resume's retained commands were in the call that first launched it.
197
+ const acceptanceInput = request.acceptance !== undefined || resume !== undefined
198
+ ? request.acceptance
199
+ : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
200
+ // An invalid acceptance fails the launch before anything runs. Verify commands run only at level
201
+ // "verified", which no inferred level reaches.
202
+ const acceptance = acceptanceInput !== undefined && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : undefined;
203
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
204
+ command: verify.command,
205
+ ...(cwd !== undefined ? { cwd: verify.cwd ? path.resolve(cwd, verify.cwd) : cwd } : {}),
206
+ ...(verify.env !== undefined ? { env: verify.env } : {}),
207
+ })) : [];
208
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
209
+ return {
210
+ workflowRunId,
211
+ key,
212
+ ...(typeof agent === "string" ? { agent } : {}),
213
+ ...(typeof task === "string" ? { task } : {}),
214
+ ...(cwd !== undefined ? { cwd } : {}),
215
+ ...(typeof request.model === "string" ? { model: request.model } : {}),
216
+ ...(typeof request.async === "boolean" ? { async: request.async } : {}),
217
+ ...(typeof request.worktree === "boolean" ? { worktree: request.worktree } : {}),
218
+ ...(resume !== undefined ? { resume } : {}),
219
+ ...(commands.length > 0 ? { commands } : {}),
220
+ ...(output !== undefined ? { output } : {}),
221
+ };
222
+ }
180
223
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
181
224
  const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
182
225
  let script;
@@ -644,7 +687,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
644
687
  throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(", ")}. Provide a longer id.`);
645
688
  const run = matches[0];
646
689
  if (run.children.some((child) => child.status === "detached"))
647
- throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
690
+ throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with ${waitToolName()}({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
648
691
  if (run.children.length > 1 && params.index === undefined)
649
692
  throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
650
693
  const index = params.index ?? 0;
@@ -795,9 +838,8 @@ function persistAsyncWorkflowControlEvent(input) {
795
838
  fs.appendFileSync(path.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record)}\n`, "utf-8");
796
839
  }
797
840
  catch (error) {
798
- if (!isStorageCapacityError(error))
799
- throw error;
800
- console.error("Failed to append async workflow control event while storage is full:", error);
841
+ // Called from the child's 1 s activity timer, where a throw would exit Pi; the notice itself is still sent.
842
+ reportSessionWarning(input.state, `Failed to record a control event for workflow ${input.job.asyncId}: ${error instanceof Error ? error.message : String(error)}`, "async-workflow-control-event");
801
843
  }
802
844
  }
803
845
  function emitControlNotification(input) {
@@ -1180,8 +1222,8 @@ function validateNestedSessionFile(run, trustedSessionRoots, resolveSource, visi
1180
1222
  }
1181
1223
  return realSessionFile;
1182
1224
  }
1183
- export function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
1184
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
1225
+ export function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
1226
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
1185
1227
  if (!recoveryDescriptor)
1186
1228
  return undefined;
1187
1229
  if (recoveryDescriptor.sourceRunId !== runId)
@@ -1201,7 +1243,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots, resolveSource) {
1201
1243
  throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
1202
1244
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
1203
1245
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1204
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
1246
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : undefined;
1205
1247
  return compactOptional({
1206
1248
  kind: "revive",
1207
1249
  source: "nested",
@@ -1688,6 +1730,20 @@ async function resumeAsyncRun(input) {
1688
1730
  details: { mode: "management", results: [] },
1689
1731
  };
1690
1732
  }
1733
+ // Before any worktree protection or chain attachment: a launch that required a launcher and agent definition
1734
+ // resumes only while both still hold.
1735
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
1736
+ if (requiredLauncher) {
1737
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
1738
+ if (attachChain)
1739
+ return refuse(`Cannot attach a chain to run '${target.runId}': it was launched with requireLauncher, and appended steps would run inside its runner unchecked.`);
1740
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : undefined;
1741
+ const now = !discoveredAgentConfig ? "is missing"
1742
+ : recoveryDescriptor.launcher !== requiredLauncher.name || discoveredAgentConfig.launcher !== requiredLauncher.name ? `uses launcher '${discoveredAgentConfig.launcher ?? "none"}'`
1743
+ : currentDigest !== requiredLauncher.definitionDigest ? `has digest ${currentDigest}` : undefined;
1744
+ if (now)
1745
+ return refuse(`Cannot resume: run '${target.runId}' was launched requiring launcher '${requiredLauncher.name}' and agent definition ${requiredLauncher.definitionDigest}; agent '${target.agent}' now ${now}.`);
1746
+ }
1691
1747
  if (target.source === "async" && target.runner?.type === "external-cli") {
1692
1748
  const runner = normalizeExternalCliRunnerStatus(target.runner);
1693
1749
  const message = runner
@@ -1698,7 +1754,8 @@ async function resumeAsyncRun(input) {
1698
1754
  if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
1699
1755
  return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
1700
1756
  }
1701
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
1757
+ // Without a handoff the resume runs in the worktree the descriptor recorded; there is no cleanup record to mark preserved.
1758
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs.existsSync(parallelHandoffPath(target.asyncDir))) {
1702
1759
  try {
1703
1760
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
1704
1761
  if (path.resolve(protectedCwd) !== path.resolve(effectiveCwd))
@@ -1864,8 +1921,8 @@ async function resumeAsyncRun(input) {
1864
1921
  if (target.source === "nested" && !target.recoveryDescriptor) {
1865
1922
  return { content: [{ type: "text", text: `Nested child '${target.runId}' is missing its required recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
1866
1923
  }
1867
- // Runs without a recovery descriptor were never wrapped; a launcher added to the agent file later does not apply.
1868
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: undefined };
1924
+ // Without a recovery descriptor nothing records how the run was wrapped, so the agent file's launcher applies.
1925
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1869
1926
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
1870
1927
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
1871
1928
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -1884,7 +1941,7 @@ async function resumeAsyncRun(input) {
1884
1941
  }
1885
1942
  // Refuse before capacity moves so the retained run stays resumable once the config is fixed.
1886
1943
  if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
1887
- return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' was launched with launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
1944
+ return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' uses launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
1888
1945
  }
1889
1946
  const runId = randomUUID();
1890
1947
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -1930,6 +1987,7 @@ async function resumeAsyncRun(input) {
1930
1987
  goal: effectiveFollowUp,
1931
1988
  agentConfig,
1932
1989
  recoveryAgentConfig,
1990
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
1933
1991
  ctx: compactOptional({
1934
1992
  pi: input.deps.pi,
1935
1993
  cwd: input.requestCwd,
@@ -2117,6 +2175,7 @@ function createForegroundControlNotifier(data, deps) {
2117
2175
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
2118
2176
  if (asyncWorkflow) {
2119
2177
  persistAsyncWorkflowControlEvent({
2178
+ state: deps.state,
2120
2179
  job: asyncWorkflow,
2121
2180
  event: enriched,
2122
2181
  controlConfig: data.controlConfig,
@@ -3177,6 +3236,7 @@ async function runAsyncPath(data, deps) {
3177
3236
  requestedCwd: data.requestedCwd,
3178
3237
  machine: params.machine,
3179
3238
  machineCwd: params.machineCwd,
3239
+ requireLauncher: params.requireLauncher,
3180
3240
  maxOutput: params.maxOutput,
3181
3241
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3182
3242
  artifactConfig,
@@ -3677,7 +3737,7 @@ async function runSinglePath(data, deps) {
3677
3737
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
3678
3738
  : "";
3679
3739
  task = readsInstruction + task;
3680
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
3740
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
3681
3741
  let effectiveSkills;
3682
3742
  if (skillOverride === false) {
3683
3743
  effectiveSkills = [];
@@ -3829,6 +3889,7 @@ async function runSinglePath(data, deps) {
3829
3889
  suppressUnchangedDelegationUpdates,
3830
3890
  controlConfig,
3831
3891
  onControlEvent,
3892
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
3832
3893
  intercomSessionName: childIntercomTarget,
3833
3894
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : undefined,
3834
3895
  nestedRoute: foregroundControl?.nestedRoute,
@@ -4017,11 +4078,11 @@ async function runSinglePath(data, deps) {
4017
4078
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
4018
4079
  if (r.detached) {
4019
4080
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
4020
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4081
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
4021
4082
  const message = r.detachedReason === "intercom coordination"
4022
4083
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
4023
4084
  : r.detachedReason === "user request"
4024
- ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with bg_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4085
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with ${waitToolName()}({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4025
4086
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
4026
4087
  return {
4027
4088
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -4501,6 +4562,9 @@ export async function preflightWorkflowWorktrees(input) {
4501
4562
  input.signal.throwIfAborted();
4502
4563
  }
4503
4564
  export function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
4565
+ // Before the resume branch below, which rebuilds params field by field and would drop the requirement.
4566
+ if (childParams.requireLauncher !== undefined || workflowDefaults.requireLauncher !== undefined)
4567
+ throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
4504
4568
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4505
4569
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4506
4570
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -4779,11 +4843,12 @@ function savedWorkflowLaunchParams(params) {
4779
4843
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
4780
4844
  return saved;
4781
4845
  }
4782
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
4783
- if (launch.source === "structured")
4784
- return { version: 1, source: "structured", scriptDigest };
4846
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
4847
+ const owner = { version: 2, scriptDigest, sessionId, ...(ceiling ? { admissionCapabilityCeiling: ceiling } : {}) };
4848
+ if (launch.source === "structured" || launch.source === "internal")
4849
+ return { ...owner, source: launch.source };
4785
4850
  // The resolved cwd is saved: a relative one would resolve against a later session's cwd.
4786
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
4851
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
4787
4852
  }
4788
4853
  export function createSubagentExecutor(deps) {
4789
4854
  const executorDeps = deps;
@@ -5104,8 +5169,8 @@ export function createSubagentExecutor(deps) {
5104
5169
  try {
5105
5170
  fs.mkdirSync(asyncDir, { recursive: true });
5106
5171
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
5107
- if (topLevelAsyncWorkflow && publicWorkflowLaunch)
5108
- writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
5172
+ if (topLevelAsyncWorkflow)
5173
+ writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling));
5109
5174
  fs.mkdirSync(DIRS.results, { recursive: true });
5110
5175
  }
5111
5176
  catch (error) {
@@ -5865,9 +5930,12 @@ export function createSubagentExecutor(deps) {
5865
5930
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5866
5931
  });
5867
5932
  let preparedChildParams;
5868
- const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
5933
+ const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5869
5934
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
5870
5935
  preparedChildParams = childRequest;
5936
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5937
+ if (launchRefusal)
5938
+ return buildRequestedModeError(childRequest, launchRefusal);
5871
5939
  if (workflowUsageBudget.budget)
5872
5940
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5873
5941
  if (workflowRequiredExtensions)
@@ -6192,9 +6260,12 @@ export function createSubagentExecutor(deps) {
6192
6260
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
6193
6261
  });
6194
6262
  let preparedChildParams;
6195
- const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
6263
+ const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6196
6264
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
6197
6265
  preparedChildParams = childRequest;
6266
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6267
+ if (launchRefusal)
6268
+ return buildRequestedModeError(childRequest, launchRefusal);
6198
6269
  if (workflowUsageBudget.budget)
6199
6270
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6200
6271
  if (workflowRequiredExtensions)
@@ -7262,6 +7333,16 @@ export function createSubagentExecutor(deps) {
7262
7333
  if (launcherError)
7263
7334
  return buildRequestedModeError(effectiveParams, launcherError);
7264
7335
  }
7336
+ // Refused here, before admission; executeAsyncSingle checks again on the exact agent and launcher it spawns.
7337
+ if (effectiveParams.requireLauncher !== undefined) {
7338
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object")
7339
+ return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
7340
+ if (!hasSingle || effectiveParams.resume !== undefined || effectiveParams.workflowParentRunId !== undefined)
7341
+ return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
7342
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : undefined;
7343
+ if (required?.error)
7344
+ return buildRequestedModeError(effectiveParams, required.error);
7345
+ }
7265
7346
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7266
7347
  try {
7267
7348
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -1149,13 +1149,34 @@ function verifyRedactionEnv(env) {
1149
1149
  return value.length >= 4 && SENSITIVE_ENV_KEY_PATTERN.test(key);
1150
1150
  }));
1151
1151
  }
1152
- function redactVerifyEnv(value, env) {
1152
+ function verifySecrets(env) {
1153
+ return [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1154
+ }
1155
+ function redactSecrets(value, secrets) {
1153
1156
  let redacted = value;
1154
- const secrets = [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1155
1157
  for (const secret of secrets)
1156
1158
  redacted = redacted.replaceAll(secret, "[REDACTED]");
1157
1159
  return redacted;
1158
1160
  }
1161
+ function redactVerifyEnv(value, env) {
1162
+ return redactSecrets(value, verifySecrets(env));
1163
+ }
1164
+ /** Numbers are matched on their source text: parsing rounds or respells them (12345678901234567890, 1.50), which would hide a secret. */
1165
+ function parseRedactedVerifyValue(text, secrets) {
1166
+ return JSON.parse(text, (_key, value, context) => {
1167
+ if (typeof value === "string")
1168
+ return redactSecrets(value, secrets);
1169
+ if (typeof value === "number" && secrets.length > 0) {
1170
+ // Node 22+ and Bun pass the source text; without it, fail closed.
1171
+ const source = context?.source;
1172
+ return source !== undefined && redactSecrets(source, secrets) === source ? value : "[REDACTED]";
1173
+ }
1174
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1175
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactSecrets(key, secrets), item]));
1176
+ }
1177
+ return value;
1178
+ });
1179
+ }
1159
1180
  function uniqueStrings(items) {
1160
1181
  return unique(items.map((item) => item?.trim()).filter((item) => Boolean(item)));
1161
1182
  }
@@ -1223,34 +1244,49 @@ const TYPED_VERIFY_OUTPUT_MAX_BYTES = 12_000;
1223
1244
  * A passing `output: "json"` command must print one JSON document on stdout.
1224
1245
  * The parsed value becomes the run's structured output; anything else turns
1225
1246
  * the passing run into a failed one so acceptance rejects rather than
1226
- * silently dropping the verdict. Stdout is already bounded by trimOutput, so a
1227
- * truncated document is detected by its marker instead of a parse guess.
1247
+ * silently dropping the verdict. The raw stdout is parsed, because the stored
1248
+ * stdout is redacted and redaction can hit JSON syntax (`true` in KDE_FULL_SESSION).
1249
+ * The schema checks the raw value so a redacted string cannot fail a correct
1250
+ * gate. Error messages quote parts of their input (a parse error quotes ~10
1251
+ * chars, schema paths escape `/` and `~`), so each one is built from the
1252
+ * redacted text or value, never the raw one.
1228
1253
  */
1229
- async function applyTypedVerifyOutput(command, run) {
1254
+ async function applyTypedVerifyOutput(command, run, rawStdout) {
1230
1255
  if (run.status !== "passed")
1231
1256
  return;
1232
- const stdout = run.stdout ?? "";
1257
+ const secrets = verifySecrets(command.env);
1258
+ const stdout = rawStdout.trim();
1233
1259
  const fail = (message) => {
1234
1260
  run.status = "failed";
1235
- run.structuredOutputError = message;
1261
+ run.structuredOutputError = redactSecrets(message, secrets);
1236
1262
  };
1237
- if (!stdout.trim())
1263
+ if (!stdout)
1238
1264
  return fail("output: \"json\" command printed nothing on stdout.");
1239
- if (stdout.endsWith("...[truncated]"))
1265
+ if (stdout.length > TYPED_VERIFY_OUTPUT_MAX_BYTES)
1240
1266
  return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
1241
1267
  let value;
1242
1268
  try {
1243
1269
  value = JSON.parse(stdout);
1244
1270
  }
1245
- catch (error) {
1246
- return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1271
+ catch {
1272
+ let reason = "parse failed";
1273
+ try {
1274
+ JSON.parse(redactSecrets(stdout, secrets));
1275
+ }
1276
+ catch (error) {
1277
+ reason = error instanceof Error ? error.message : String(error);
1278
+ }
1279
+ return fail(`output: "json" stdout is not valid JSON: ${reason}`);
1247
1280
  }
1281
+ const redactedValue = parseRedactedVerifyValue(stdout, secrets);
1248
1282
  if (command.schema) {
1249
1283
  const validation = await validateStructuredOutputValue(command.schema, value);
1250
- if (validation.status === "invalid")
1251
- return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
1284
+ if (validation.status === "invalid") {
1285
+ const redactedValidation = await validateStructuredOutputValue(command.schema, redactedValue);
1286
+ return fail(`output: "json" stdout does not match gate.schema${redactedValidation.status === "invalid" ? `: ${redactedValidation.message}` : "."}`);
1287
+ }
1252
1288
  }
1253
- run.structuredOutput = value;
1289
+ run.structuredOutput = redactedValue;
1254
1290
  }
1255
1291
  /** The first typed verify result on a ledger, if any command produced one. */
1256
1292
  export function typedVerifyOutput(ledger) {
@@ -1258,6 +1294,13 @@ export function typedVerifyOutput(ledger) {
1258
1294
  return run ? { value: run.structuredOutput } : undefined;
1259
1295
  }
1260
1296
  async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1297
+ // Typed gates read inputs (a report file, a log) that can change without
1298
+ // the tracked tree changing, so their verdicts are never reused.
1299
+ if (command.output === "json") {
1300
+ const { run, rawStdout } = await runVerifyCommand(command, defaultCwd, options);
1301
+ await applyTypedVerifyOutput(command, run, rawStdout);
1302
+ return run;
1303
+ }
1261
1304
  const cwd = command.cwd ? path.resolve(defaultCwd, command.cwd) : defaultCwd;
1262
1305
  let workspaceState;
1263
1306
  try {
@@ -1266,10 +1309,8 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1266
1309
  catch {
1267
1310
  workspaceState = undefined;
1268
1311
  }
1269
- // Typed gates read inputs (a report file, a log) that can change without
1270
- // the tracked tree changing, so their verdicts are never reused.
1271
- if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
1272
- return runVerifyCommand(command, defaultCwd, options);
1312
+ if (!workspaceState || !options.artifactsDir || !options.runId) {
1313
+ return (await runVerifyCommand(command, defaultCwd, options)).run;
1273
1314
  }
1274
1315
  const envKeys = Object.keys(command.env ?? {}).sort();
1275
1316
  const envHash = hash(JSON.stringify(Object.fromEntries(Object.entries(effectiveVerifyEnv(command.env)).sort(([left], [right]) => left.localeCompare(right)))));
@@ -1295,7 +1336,7 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1295
1336
  catch {
1296
1337
  // A cache miss or unreadable artifact must not prevent host verification.
1297
1338
  }
1298
- const result = await runVerifyCommand(command, defaultCwd, options);
1339
+ const { run: result } = await runVerifyCommand(command, defaultCwd, options);
1299
1340
  const evidenced = { ...result, artifactPath, cacheKey, memoized: false, envKeys, envHash, workspaceState };
1300
1341
  try {
1301
1342
  fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
@@ -1363,6 +1404,7 @@ export function quoteExecutableForShell(command, platform = process.platform) {
1363
1404
  }
1364
1405
  return command;
1365
1406
  }
1407
+ /** `rawStdout` is unredacted and never stored; only typed output parsing reads it. */
1366
1408
  function runVerifyCommand(command, defaultCwd, options = {}) {
1367
1409
  return new Promise((resolve) => {
1368
1410
  const startedAt = Date.now();
@@ -1388,11 +1430,14 @@ function runVerifyCommand(command, defaultCwd, options = {}) {
1388
1430
  clearTimeout(hardKill);
1389
1431
  options.signal?.removeEventListener("abort", abortVerification);
1390
1432
  resolve({
1391
- id: command.id,
1392
- command: command.command,
1393
- cwd,
1394
- durationMs: Date.now() - startedAt,
1395
- ...result,
1433
+ run: {
1434
+ id: command.id,
1435
+ command: command.command,
1436
+ cwd,
1437
+ durationMs: Date.now() - startedAt,
1438
+ ...result,
1439
+ },
1440
+ rawStdout: stdout,
1396
1441
  });
1397
1442
  };
1398
1443
  const abortVerification = () => {
@@ -1531,8 +1576,6 @@ export async function evaluateAcceptance(input) {
1531
1576
  artifactsDir: input.artifactsDir,
1532
1577
  runId: input.runId,
1533
1578
  });
1534
- if (command.output === "json")
1535
- await applyTypedVerifyOutput(command, run);
1536
1579
  ledger.verifyRuns.push(run);
1537
1580
  if (input.signal?.aborted)
1538
1581
  break;
@@ -135,8 +135,20 @@ export function createChildCommandRuntime(channelDir) {
135
135
  persist();
136
136
  startInbox();
137
137
  let timer;
138
+ let yieldSaveError;
139
+ // A throw from this timer would exit Pi. A closed controller is already cancelling the command; a failed
140
+ // save still yields, and the handle says the saved state is stale.
138
141
  if (typeof yieldTimeMs === "number")
139
- timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
142
+ timer = setTimeout(() => {
143
+ if (closed)
144
+ return;
145
+ try {
146
+ operate("yield", toolCallId);
147
+ }
148
+ catch (error) {
149
+ yieldSaveError = error;
150
+ }
151
+ }, yieldTimeMs);
140
152
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
141
153
  job.snapshot.output = text(update);
142
154
  if (job.snapshot.state === "running")
@@ -163,7 +175,8 @@ export function createChildCommandRuntime(channelDir) {
163
175
  const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
164
176
  if (result)
165
177
  return result.value;
166
- return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
178
+ const saveWarning = yieldSaveError === undefined ? "" : `\nThe command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
179
+ return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.${saveWarning}\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
167
180
  },
168
181
  };
169
182
  },
@@ -1,13 +1,7 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
1
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
3
2
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
4
- import type { ChildSessionLaunch } from "./child-session.ts";
3
+ import type { ChildHookExtension, ChildSessionLaunch } from "./child-session.ts";
5
4
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
6
- /** Inline extension shape accepted by pi's resource loader (`extensionFactories`). */
7
- export interface ChildHookExtension {
8
- name: string;
9
- factory: (pi: ExtensionAPI) => void;
10
- }
11
5
  /** The host's mandatory transcript reporting, owned by the existing hook certificate. */
12
6
  export declare function withChildSessionErrorReporting(session: Omit<ChildSessionLaunch, "onExtensionError">, transcriptWriter: ChildTranscriptWriter | undefined): ChildSessionLaunch;
13
7
  export declare function isReadonlyChildSessionReporting(launch: ChildSessionLaunch): boolean;
@@ -3,6 +3,7 @@ import { ReadonlyDrainObservation } from "./readonly-drain-observation.js";
3
3
  import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.js";
4
4
  import registerSubagentFastModeExtension from "./fast-mode-extension.js";
5
5
  import registerSubagentPromptRuntime, { registerSubagentPromptBoundary } from "./subagent-prompt-runtime.js";
6
+ import { structuredOutputValidatorReady } from "./structured-output.js";
6
7
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.js";
7
8
  const promptProofs = new WeakMap();
8
9
  function ownedProof(hooks) {
@@ -153,11 +154,18 @@ function childHooks(config, capture, holdFinalDrain) {
153
154
  }
154
155
  const hooks = [
155
156
  { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
156
- if (!proof?.observeNext)
157
- return registerSubagentPromptRuntime(pi, runtime);
158
- proof.observation = proof.observeNext;
159
- proof.observeNext = undefined;
160
- registerSubagentPromptRuntime(pi, runtime, proof.observation);
157
+ if (!proof?.observeNext) {
158
+ registerSubagentPromptRuntime(pi, runtime);
159
+ }
160
+ else {
161
+ proof.observation = proof.observeNext;
162
+ proof.observeNext = undefined;
163
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
164
+ }
165
+ // Pi awaits extension factories, so structured_output's synchronous prepareArguments has its
166
+ // validator before the model can call it.
167
+ if (runtime.structuredOutput)
168
+ return structuredOutputValidatorReady();
161
169
  } },
162
170
  ];
163
171
  if (config.fast)
@@ -14,6 +14,7 @@ import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
14
14
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
15
15
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
16
16
  import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
17
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
17
18
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
18
19
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
19
20
  export function inheritedChildRuntime(config) {
@@ -34,7 +35,6 @@ export function inheritedChildRuntime(config) {
34
35
  export function createReportedChildSessionInput(launch, transcriptWriter) {
35
36
  return withChildSessionErrorReporting(launch.session, transcriptWriter);
36
37
  }
37
- /** Escape XML-significant characters in a string for safe attribute interpolation. */
38
38
  function escapeXmlAttr(value) {
39
39
  return value
40
40
  .replace(/&/g, "&amp;")
@@ -75,7 +75,10 @@ function childStorage(input) {
75
75
  return { kind: "default" };
76
76
  }
77
77
  export function buildInProcessChildLaunch(input) {
78
- const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
78
+ const resolvedRequiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
79
+ // A placed child cannot load local extension paths, so it skips non-mandatory entries like an
80
+ // external runner does; a mandatory one stays and refuses the launch when it is serialized.
81
+ const requiredExtensions = input.machine ? resolvedRequiredExtensions.filter((entry) => entry.requireForAllRunners) : resolvedRequiredExtensions;
79
82
  const agentCapabilityCeiling = input.descendantAllowedAgents === undefined
80
83
  ? undefined
81
84
  : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
@@ -171,6 +174,7 @@ export function buildInProcessChildLaunch(input) {
171
174
  waitTool: {
172
175
  enabled: input.waitToolEnabled ?? true,
173
176
  ...(input.waitToolDefaultTimeoutMs !== undefined ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}),
177
+ ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { name: waitToolName() } : {}),
174
178
  },
175
179
  ...(input.structuredOutput
176
180
  ? {