@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -4,12 +4,7 @@ import * as path from "node:path";
4
4
  import { performance } from "node:perf_hooks";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
- import { arbitrateCompletionGuardRescue, createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
8
7
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
9
-
10
- const isRunnerEntrypoint = Boolean(process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href);
11
- // Detached Node runners skip Pi's CLI dispatcher setup; install the runner's own.
12
- if (isRunnerEntrypoint) installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
13
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
14
9
  import { writeAsyncResultFile, writePendingAsyncResultFile } from "./result-files.ts";
15
10
  import { createFileCoalescer } from "../../shared/file-coalescer.ts";
@@ -17,7 +12,7 @@ import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilie
17
12
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
18
13
  import { updateActiveRunIndex } from "./active-run-index.ts";
19
14
  import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
20
- import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
15
+ import { closeSteerInbox, closeStopInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
21
16
  import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
22
17
  import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
23
18
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
@@ -91,7 +86,7 @@ import { SUBAGENT_CHILD_ENV } from "../shared/child-runtime-config.ts";
91
86
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
92
87
  import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.ts";
93
88
  import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/chain-outputs.ts";
94
- import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
89
+ import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, formatStructuredOutputRejectionError, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
95
90
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
96
91
  import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
97
92
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
@@ -99,11 +94,11 @@ import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelSt
99
94
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.ts";
100
95
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.ts";
101
96
  import { formatSubagentModelVerificationError, isContextOverflow } from "../shared/model-resolution.ts";
102
- import { markProcessTerminalCandidateLeaseRelease, processTerminalPath, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal.ts";
97
+ import { processTerminalPath, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal.ts";
98
+ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
99
+ import { currentPidNamespaceScope } from "./pid-namespace.ts";
103
100
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, unconsumedSteerReason, updateSteeringTarget } from "./steering.ts";
104
101
  import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getAgentDir, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
105
- import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
106
- import { planCompletionEvidence, projectSettlementDiagnostic } from "../shared/completion-evidence.ts";
107
102
  import { planAbortRecovery } from "../shared/abort-recovery.ts";
108
103
  import {
109
104
  createMutatingFailureState,
@@ -136,7 +131,7 @@ import { assertThinkingWithinCeiling } from "../../shared/thinking-ceiling.ts";
136
131
  import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
137
132
  import { writeInitialProgressFile } from "../../shared/settings.ts";
138
133
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
139
- import { acceptanceFailureMessage, aggregateAcceptanceReport, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveAcceptanceReportMode, resolveEffectiveAcceptance, stripAcceptanceReport } from "../shared/acceptance.ts";
134
+ import { acceptanceFailureMessage, aggregateAcceptanceReport, buildSkippedAcceptanceLedger, captureStagedIndexBaseline, evaluateAcceptance, formatAcceptancePrompt, resolveAcceptanceReportMode, resolveEffectiveAcceptance, stripAcceptanceReport, typedVerifyOutput } from "../shared/acceptance.ts";
140
135
  import { attachContractProjections, isAgentContract } from "../shared/agent-contract.ts";
141
136
  import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
142
137
  import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
@@ -148,7 +143,7 @@ import { toolTimeoutCallKey } from "../shared/tool-timeout.ts";
148
143
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
149
144
  import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
150
145
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
151
- import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts";
146
+ import type { SessionLeaseRequest } from "../shared/session-lease.ts";
152
147
  import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts";
153
148
  import { resolveClaudeCodeLaunch } from "../shared/claude-code-adapter.ts";
154
149
  import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.ts";
@@ -195,6 +190,8 @@ export interface SubagentRunConfig {
195
190
  childSessionFactoryModule?: string;
196
191
  /** The launching executor's own child runtime when it was itself an in-process child. */
197
192
  inheritedChildRuntime?: InheritedChildRuntime;
193
+ /** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
194
+ projectTrusted?: boolean;
198
195
  worktreeSetupHook?: string;
199
196
  worktreeSetupHookTimeoutMs?: number;
200
197
  worktreeBaseDir?: string;
@@ -225,7 +222,6 @@ export interface SubagentRunConfig {
225
222
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
226
223
  runFanoutBudget?: RunFanoutBudgetDescriptor;
227
224
  /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
228
- hostAvailableBuiltins?: readonly string[];
229
225
  launchContractDigest?: string;
230
226
  launchResolvedExtensions?: LaunchResolvedChildExtensions;
231
227
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
@@ -285,6 +281,7 @@ interface StepResult {
285
281
  review?: import("../../shared/types.ts").ReviewProjection;
286
282
  effects?: import("../../shared/types.ts").EffectsProjection;
287
283
  structuredOutput?: unknown;
284
+ structuredOutputFailed?: boolean;
288
285
  structuredOutputPath?: string;
289
286
  structuredOutputSchemaPath?: string;
290
287
  acceptance?: import("../../shared/types.ts").AcceptanceLedger;
@@ -690,6 +687,7 @@ interface SingleStepContext {
690
687
  childSessions: ChildSessionFactory;
691
688
  /** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
692
689
  inheritedChildRuntime?: InheritedChildRuntime;
690
+ projectTrusted?: boolean;
693
691
  registerInterrupt?: (interrupt: (() => void) | undefined) => void;
694
692
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
695
693
  registerStop?: (stop: (() => void) | undefined) => void;
@@ -710,7 +708,6 @@ interface SingleStepContext {
710
708
  nestedRoute?: NestedRouteInfo;
711
709
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
712
710
  runFanoutBudget?: RunFanoutBudgetDescriptor;
713
- hostAvailableBuiltins?: readonly string[];
714
711
  onAttemptStart?: (attempt: { model?: string; thinking?: string; contextLimit?: number }) => void;
715
712
  onChildEvent?: (event: ChildEvent) => void;
716
713
  onExternalProcess?: (process: ExternalProcessStatus) => void;
@@ -722,8 +719,6 @@ interface SingleStepContext {
722
719
  usageBudgetExhausted?: () => boolean | undefined;
723
720
  /** Existing run-owned budget configuration; cost allowance is not settled by the live token ledger. */
724
721
  usageBudget?: UsageBudgetConfig;
725
- /** False when sibling work in the same Git worktree could have caused the tracked diff. */
726
- trackedMutationEvidenceForCompletionGuard?: boolean;
727
722
  orcaProgressTab?: OrcaProgressTab;
728
723
  }
729
724
 
@@ -749,7 +744,7 @@ export async function settleHerdrExternalRunnerError(error: unknown, adapter: He
749
744
  export async function runSingleStepInner(
750
745
  step: SubagentStep,
751
746
  ctx: SingleStepContext,
752
- ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
747
+ ): Promise<StepResult> {
753
748
  if (step.importAsyncRoot) {
754
749
  let importTimedOut = false;
755
750
  let importStopped = false;
@@ -827,7 +822,6 @@ export async function runSingleStepInner(
827
822
  const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
828
823
  let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
829
824
  if (ctx.outputs) task = resolveOutputReferences(task, ctx.outputs);
830
- const taskForCompletionGuard = task;
831
825
  let resolvedTaskToolPlan: ReturnType<typeof resolvePiLaunchToolPlan> | undefined;
832
826
  if (!step.runner) {
833
827
  resolvedTaskToolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
@@ -839,6 +833,7 @@ export async function runSingleStepInner(
839
833
  fast: step.fast,
840
834
  model: step.model,
841
835
  mcpDirectTools: step.mcpDirectTools,
836
+ builtinMcpTools: step.builtinMcpTools,
842
837
  cwd: step.cwd ?? ctx.cwd,
843
838
  requireReadTool: Boolean(step.skills?.length),
844
839
  structuredOutput: Boolean(effectiveStructuredOutput),
@@ -846,30 +841,7 @@ export async function runSingleStepInner(
846
841
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
847
842
  requiredExtensions: step.requiredExtensions ?? ctx.inheritedChildRuntime?.requiredExtensions,
848
843
  permissionRules: step.permissionRules,
849
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
850
844
  }));
851
- const contractTools = resolvedTaskToolPlan.explicitToolAllowlist ? resolvedTaskToolPlan.effectiveToolAllowlist : undefined;
852
- const contractError = validateImplementationToolContract({
853
- agent: step.agent,
854
- task: taskForCompletionGuard,
855
- tools: contractTools,
856
- mcpDirectTools: resolvedTaskToolPlan.effectiveMcpTools,
857
- configuredExtensions: resolvedTaskToolPlan.configuredExtensions,
858
- requestedTools: resolvedTaskToolPlan.requestedBuiltinTools,
859
- acceptanceRole: step.acceptanceRole,
860
- completionGuard: step.completionGuard,
861
- });
862
- if (contractError) {
863
- return omitUndefinedProperties({
864
- agent: step.agent,
865
- context: step.context,
866
- output: contractError,
867
- error: contractError,
868
- exitCode: 1,
869
- capabilityCeiling: resolvedTaskToolPlan.capabilityCeiling,
870
- capabilityAudit: resolvedTaskToolPlan.capabilityAudit,
871
- });
872
- }
873
845
  }
874
846
  // Derive from the pre-acceptance task so internal acceptance/recovery
875
847
  // instructions never leak into the display name.
@@ -1121,7 +1093,6 @@ export async function runSingleStepInner(
1121
1093
  let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1122
1094
  let structuredAcceptanceReport: unknown;
1123
1095
  let structuredAcceptanceReportError: string | undefined;
1124
- let completionGuardTriggeredFinal = false;
1125
1096
  let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1126
1097
  let toolBudgetBlocked = false;
1127
1098
  let actualLaunchContractDigest = step.launchContractDigest;
@@ -1133,6 +1104,7 @@ export async function runSingleStepInner(
1133
1104
  const aggregateUsage = emptyUsage();
1134
1105
  let launched = false;
1135
1106
  let recoveryTask = task;
1107
+ let stagedIndexBaseline: string | undefined;
1136
1108
  singleLaunch: for (let attemptIndex = 0; attemptIndex < 2; attemptIndex++) {
1137
1109
  if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break singleLaunch;
1138
1110
  const expectedModelForVerification = candidate && !step.skipPrimaryModelVerification ? candidate : undefined;
@@ -1142,9 +1114,9 @@ export async function runSingleStepInner(
1142
1114
  const message = error instanceof Error ? error.message : String(error);
1143
1115
  return omitUndefinedProperties({ agent: step.agent, output: message, error: message, exitCode: 1, context: step.context, thinkingCeiling: step.thinkingCeiling });
1144
1116
  }
1117
+ const attemptModel = omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) });
1145
1118
  ctx.onAttemptStart?.(omitUndefinedProperties({
1146
- model: candidate,
1147
- thinking: resolveEffectiveThinking(candidate, step.thinking),
1119
+ ...attemptModel,
1148
1120
  contextLimit: findModelInfo(candidate, step.modelVerificationRegistry)?.contextWindow,
1149
1121
  }));
1150
1122
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
@@ -1196,6 +1168,7 @@ export async function runSingleStepInner(
1196
1168
  fast: step.fast,
1197
1169
  model: step.model,
1198
1170
  mcpDirectTools: step.mcpDirectTools,
1171
+ builtinMcpTools: step.builtinMcpTools,
1199
1172
  cwd: step.cwd ?? ctx.cwd,
1200
1173
  requireReadTool: Boolean(step.skills?.length),
1201
1174
  structuredOutput: Boolean(effectiveStructuredOutput),
@@ -1203,7 +1176,6 @@ export async function runSingleStepInner(
1203
1176
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1204
1177
  requiredExtensions: step.requiredExtensions ?? ctx.inheritedChildRuntime?.requiredExtensions,
1205
1178
  permissionRules: step.permissionRules,
1206
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
1207
1179
  }));
1208
1180
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1209
1181
  actualLaunchContractDigest = resolveLaunchBinding({
@@ -1229,6 +1201,14 @@ export async function runSingleStepInner(
1229
1201
  // Each attempt rewrites the step output log; synchronous appends keep a
1230
1202
  // retried attempt from interleaving with the previous attempt's flush.
1231
1203
  fs.writeFileSync(ctx.outputFile, "", "utf-8");
1204
+ if (step.effectiveAcceptance?.preserveStagedIndex && stagedIndexBaseline === undefined) {
1205
+ try {
1206
+ stagedIndexBaseline = captureStagedIndexBaseline(step.cwd ?? ctx.cwd);
1207
+ } catch (error) {
1208
+ const message = error instanceof Error ? error.message : String(error);
1209
+ return { agent: step.agent, output: message, error: message, exitCode: 1, context: step.context };
1210
+ }
1211
+ }
1232
1212
  const run = await runChildSession(omitUndefinedProperties({
1233
1213
  factory: ctx.childSessions,
1234
1214
  launch,
@@ -1253,6 +1233,7 @@ export async function runSingleStepInner(
1253
1233
  timeoutMessage: ctx.timeoutMessage,
1254
1234
  stopMessage: ctx.stopMessage,
1255
1235
  onChildEvent: ctx.onChildEvent,
1236
+ onContextWindow: (contextLimit) => ctx.onAttemptStart?.({ ...attemptModel, contextLimit }),
1256
1237
  transcriptWriter,
1257
1238
  toolTimeoutMs: ctx.toolTimeoutMs,
1258
1239
  runDeadlineAt: ctx.deadlineAt,
@@ -1268,9 +1249,9 @@ export async function runSingleStepInner(
1268
1249
  aggregateUsage.cacheWrite += run.usage.cacheWrite;
1269
1250
  aggregateUsage.cost += run.usage.cost;
1270
1251
  aggregateUsage.turns += run.usage.turns;
1271
- // A parked run still owes completion evidence when it actually finishes.
1272
- // Stopped/timedOut runs already have terminal failures; checking completion evidence there is meaningless.
1273
- const completionDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
1252
+ // A parked run still owes output diagnostics when it actually finishes.
1253
+ // Stopped/timedOut runs already have terminal failures, so terminal output diagnostics are deferred.
1254
+ const terminalDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
1274
1255
  const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
1275
1256
  const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
1276
1257
  const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
@@ -1286,16 +1267,23 @@ export async function runSingleStepInner(
1286
1267
  let structuredOutput: unknown;
1287
1268
  let structuredError: string | undefined;
1288
1269
  let validatedStructuredOutput = false;
1289
- if (completionDiagnosticsEligible && effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError) {
1290
- if (!run.structuredOutputToolInvoked) {
1270
+ if (effectiveStructuredOutput) {
1271
+ const otherwiseSuccessful = terminalDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError;
1272
+ if (!run.structuredOutputToolInvoked && otherwiseSuccessful) {
1291
1273
  structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1292
- } else {
1274
+ } else if (run.structuredOutputToolInvoked) {
1293
1275
  const structured = await readStructuredOutput({
1294
1276
  schema: effectiveStructuredOutput.schema,
1295
1277
  schemaPath: effectiveStructuredOutput.schemaPath,
1296
1278
  outputPath: effectiveStructuredOutput.outputPath,
1297
1279
  });
1298
- if (structured.error) structuredError = structured.error;
1280
+ if (structured.error) {
1281
+ if (otherwiseSuccessful) {
1282
+ structuredError = structured.error === MISSING_STRUCTURED_OUTPUT_CALL_ERROR
1283
+ ? formatStructuredOutputRejectionError(run.messages)
1284
+ : structured.error;
1285
+ }
1286
+ }
1299
1287
  else {
1300
1288
  structuredOutput = structured.value;
1301
1289
  const acceptanceReport = readStructuredOutputAcceptanceReport(effectiveStructuredOutput);
@@ -1308,13 +1296,13 @@ export async function runSingleStepInner(
1308
1296
  const errorMessages = validatedStructuredOutput
1309
1297
  ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1310
1298
  : run.messages;
1311
- const hiddenError = completionDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1299
+ const hiddenError = terminalDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1312
1300
  ? detectSubagentError(errorMessages)
1313
1301
  : null;
1314
1302
  const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1315
1303
  && hasEmptyTerminalAssistantResponse(run.messages)
1316
1304
  && (run.toolCount > 0 || Boolean(run.finalOutput.trim()));
1317
- const emptyOutputError = completionDiagnosticsEligible && run.exitCode === 0
1305
+ const emptyOutputError = terminalDiagnosticsEligible && run.exitCode === 0
1318
1306
  && !run.error
1319
1307
  && !toolAvailabilityError
1320
1308
  && !structuredError
@@ -1323,48 +1311,10 @@ export async function runSingleStepInner(
1323
1311
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1324
1312
  ? formatEmptyTerminalAssistantResponseError(run.messages)
1325
1313
  : undefined;
1326
- const completionGuardEnabled = isAgentContract(step.agentContract) ? step.completionGuard === true : step.completionGuard !== false;
1327
- const completionToolPlan = resolvedTaskToolPlan;
1328
- const completionTools = completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools;
1329
1314
  const remoteGitChanged = run.nativeMachine?.initialGit && run.nativeMachine.finalGit ? run.nativeMachine.initialGit.head !== run.nativeMachine.finalGit.head || run.nativeMachine.initialGit.dirty !== run.nativeMachine.finalGit.dirty : undefined;
1330
1315
  const mutationEvidence = run.nativeMachine ? { source: "tracked-files" as const, trackedOnly: true as const, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1331
1316
  finalMutationEvidence = mutationEvidence;
1332
- const completionMutationEvidence = ctx.trackedMutationEvidenceForCompletionGuard === false ? undefined : mutationEvidence;
1333
- const completionGuard = completionDiagnosticsEligible && run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !midToolExitError && !emptyOutputError && completionGuardEnabled
1334
- ? evaluateCompletionMutationGuard(omitUndefinedProperties({
1335
- agent: step.agent,
1336
- task: taskForCompletionGuard,
1337
- messages: run.messages,
1338
- tools: completionTools,
1339
- mcpDirectTools: completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools,
1340
- mutationTools: step.mutationTools,
1341
- toolAvailabilityError,
1342
- mutationEvidence: completionMutationEvidence,
1343
- }))
1344
- : undefined;
1345
- const mutationAttemptObserved = run.observedMutationAttempt === true || completionMutationEvidence?.attemptedMutation === true;
1346
- let arbitration = { triggered: completionGuard?.triggered === true && !mutationAttemptObserved, rescued: false };
1347
- if (arbitration.triggered) {
1348
- const modelContext = launch.capture.completionIntentContext?.();
1349
- arbitration = await arbitrateCompletionGuardRescue({
1350
- guardTriggered: true,
1351
- task: taskForCompletionGuard,
1352
- // Construct lazily too: the shared gate refuses overlength tasks before
1353
- // registry/auth/model work. The child has already shut down normally.
1354
- arbiter: modelContext ? async (task) => createTaskMutationArbiter(modelContext)?.(task) ?? "unavailable" : undefined,
1355
- });
1356
- }
1357
- const completionEvidence = planCompletionEvidence({
1358
- guard: completionGuard,
1359
- guardTriggered: arbitration.triggered,
1360
- arbiterRescued: arbitration.rescued,
1361
- completionGuardEnabled,
1362
- mutationCapable: hasMutationToolCapability(completionTools, completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools),
1363
- implementationMutationExpected: expectsImplementationMutation(step.agent, taskForCompletionGuard),
1364
- mutationAttemptObserved,
1365
- mutationEvidence: completionMutationEvidence,
1366
- agentContractEnabled: isAgentContract(step.agentContract),
1367
- });
1317
+ const mutationAttemptObserved = run.observedMutationAttempt === true || mutationEvidence.attemptedMutation === true;
1368
1318
  const finalOutputHasPersistableFileContent = run.exitCode === 0 && !run.error && !emptyOutputError && Boolean(stripAcceptanceReport(run.finalOutput).trim());
1369
1319
  const requiredOutput = step.outputMode === "file-only" && step.outputPath
1370
1320
  ? { kind: "file-only" as const, path: step.outputPath, missing: !fs.existsSync(step.outputPath) && !finalOutputHasPersistableFileContent }
@@ -1372,9 +1322,9 @@ export async function runSingleStepInner(
1372
1322
  ? { kind: "structured" as const, path: effectiveStructuredOutput.outputPath, missing: !fs.existsSync(effectiveStructuredOutput.outputPath) }
1373
1323
  : undefined;
1374
1324
  finalRequiredOutputMissing = requiredOutput?.missing;
1375
- const missingRequiredOutputError = completionDiagnosticsEligible ? formatRequiredOutputError(requiredOutput) : undefined;
1325
+ const missingRequiredOutputError = terminalDiagnosticsEligible ? formatRequiredOutputError(requiredOutput) : undefined;
1376
1326
  const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1377
- const effectiveExitCode = toolAvailabilityError || completionEvidence.legacyFailureError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1327
+ const effectiveExitCode = toolAvailabilityError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1378
1328
  ? 1
1379
1329
  : hiddenError?.hasError
1380
1330
  ? (hiddenError.exitCode ?? 1)
@@ -1392,8 +1342,7 @@ export async function runSingleStepInner(
1392
1342
  ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1393
1343
  : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1394
1344
  : undefined);
1395
- const error = underlyingError ?? missingRequiredOutputError ?? completionEvidence.legacyFailureError;
1396
- completionGuardTriggeredFinal = completionEvidence.guardTriggered && !underlyingError && !missingRequiredOutputError;
1345
+ const error = underlyingError ?? missingRequiredOutputError;
1397
1346
  finalOutputSnapshot = outputSnapshot;
1398
1347
  if (step.toolBudget) {
1399
1348
  const toolMessages = run.messages.filter((message) => message.role === "toolResult");
@@ -1401,18 +1350,16 @@ export async function runSingleStepInner(
1401
1350
  toolBudgetBlocked = Boolean(blockedMessage);
1402
1351
  toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1403
1352
  }
1404
- const settlementDiagnostic = projectSettlementDiagnostic(completionEvidence, {
1405
- terminalFailed: effectiveExitCode !== 0,
1353
+ const settlementDiagnostic = effectiveExitCode !== 0 ? {
1406
1354
  finalTextPresent: Boolean(stripAcceptanceReport(run.finalOutput).trim()),
1407
- mutationObserved: mutationEvidence.attemptedMutation,
1408
- requiredOutput,
1355
+ mutation: { attempted: mutationAttemptObserved, observed: mutationEvidence.attemptedMutation },
1356
+ ...(requiredOutput ? { requiredOutput } : {}),
1409
1357
  afterCompactionSettlement: run.afterCompactionSettlement === true,
1410
- });
1411
- const fileMutationEffect = completionEvidence.fileMutation ?? (missingRequiredOutputAfterMutation ? { status: "observed" as const, expected: completionEvidence.mutationExpected, attempted: true, evidence: mutationEvidence } : undefined);
1412
- finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect || settlementDiagnostic ? { effects: { ...(fileMutationEffect ? { fileMutation: fileMutationEffect } : {}), ...(settlementDiagnostic ? { settlementDiagnostic } : {}) } } : {}) } as RunChildSessionResult;
1358
+ } : undefined;
1359
+ const fileMutationEffect = missingRequiredOutputAfterMutation ? { status: "observed" as const, attempted: true as const, evidence: mutationEvidence } : undefined;
1360
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, structuredOutputFailed: structuredError ? true : undefined, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect || settlementDiagnostic ? { effects: { ...(fileMutationEffect ? { fileMutation: fileMutationEffect } : {}), ...(settlementDiagnostic ? { settlementDiagnostic } : {}) } } : {}) } as RunChildSessionResult;
1413
1361
  if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break singleLaunch;
1414
1362
  if (effectiveExitCode === 0 && !error) break singleLaunch;
1415
- if (completionEvidence.guardTriggered) break singleLaunch;
1416
1363
  const recovery = planAbortRecovery({
1417
1364
  messages: run.messages,
1418
1365
  error,
@@ -1509,6 +1456,7 @@ export async function runSingleStepInner(
1509
1456
  ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only", durable: resolvedOutput.savedPath !== undefined }
1510
1457
  : undefined,
1511
1458
  cwd: step.cwd ?? ctx.cwd,
1459
+ stagedIndexBaseline,
1512
1460
  signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
1513
1461
  abortMessage: ctx.stopSignal?.aborted ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.",
1514
1462
  reportOptional: isAgentContract(step.agentContract),
@@ -1529,6 +1477,12 @@ export async function runSingleStepInner(
1529
1477
  const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
1530
1478
  const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !isAgentContract(step.agentContract);
1531
1479
  const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1480
+ // A passing typed gate supplies the structured output for runs that have no
1481
+ // outputSchema of their own; preflight rejects the combination.
1482
+ const typedGate = typedVerifyOutput(effectiveAcceptance);
1483
+ if (typedGate && finalResult && finalResult.structuredOutput === undefined && effectiveFinalExitCode === 0) {
1484
+ finalResult = { ...finalResult, structuredOutput: typedGate.value };
1485
+ }
1532
1486
  const intercomDetachReceipt = finalResult?.finalOutput === INTERCOM_DETACH_RECEIPT;
1533
1487
  const baseFinalError = stoppedAfterAcceptance
1534
1488
  ? ctx.stopMessage ?? "Subagent stopped by user."
@@ -1578,7 +1532,7 @@ export async function runSingleStepInner(
1578
1532
  })
1579
1533
  : {};
1580
1534
 
1581
- const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
1535
+ const result: StepResult = omitUndefinedProperties({
1582
1536
  agent: step.agent,
1583
1537
  ...(childSessionName ? { sessionName: childSessionName } : {}),
1584
1538
  context: step.context,
@@ -1610,11 +1564,11 @@ export async function runSingleStepInner(
1610
1564
  timeoutRecovery,
1611
1565
  toolBudget,
1612
1566
  toolBudgetBlocked: toolBudgetBlocked || undefined,
1613
- completionGuardTriggered: completionGuardTriggeredFinal,
1614
1567
  ...((finalResult as (RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1615
- structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1616
- structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.outputPath,
1617
- structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.schemaPath,
1568
+ structuredOutput: (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1569
+ structuredOutputFailed: finalResult?.structuredOutputFailed,
1570
+ structuredOutputPath: effectiveStructuredOutput?.outputPath,
1571
+ structuredOutputSchemaPath: effectiveStructuredOutput?.schemaPath,
1618
1572
  acceptance: effectiveAcceptance,
1619
1573
  watchdog: finalResult?.watchdog,
1620
1574
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
@@ -1627,7 +1581,7 @@ export async function runSingleStepInner(
1627
1581
  async function runSingleStep(
1628
1582
  step: SubagentStep,
1629
1583
  ctx: SingleStepContext,
1630
- ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
1584
+ ): Promise<StepResult> {
1631
1585
  if (!step.importAsyncRoot) ctx.orcaProgressTab?.section({ agent: step.agent, index: ctx.flatIndex, count: ctx.flatStepCount });
1632
1586
  return runSingleStepInner(step, ctx);
1633
1587
  }
@@ -2107,6 +2061,7 @@ export async function runSubagent(
2107
2061
  ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2108
2062
  ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2109
2063
  pid: process.pid,
2064
+ pidNamespaceScope: currentPidNamespaceScope(),
2110
2065
  cwd,
2111
2066
  currentStep: 0,
2112
2067
  chainStepCount: steps.length,
@@ -3789,6 +3744,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3789
3744
  artifactsDir, artifactConfig, id,
3790
3745
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
3791
3746
  outputFile: path.join(asyncDir, `output-${fi}.log`),
3747
+ projectTrusted: config.projectTrusted,
3792
3748
  piPackageRoot: config.piPackageRoot,
3793
3749
  childSessions,
3794
3750
  inheritedChildRuntime: config.inheritedChildRuntime,
@@ -3797,7 +3753,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3797
3753
  nestedRoute: config.nestedRoute,
3798
3754
  capabilityCeiling: config.capabilityCeiling,
3799
3755
  runFanoutBudget: config.runFanoutBudget,
3800
- hostAvailableBuiltins: config.hostAvailableBuiltins,
3801
3756
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
3802
3757
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
3803
3758
  registerStop: (stop) => registerStepStop(fi, stop),
@@ -3805,7 +3760,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3805
3760
  onSteerOutcome: (request, delivery) => applySteerDelivery(request.id, fi, delivery),
3806
3761
  timeoutSignal: timeoutAbortController.signal,
3807
3762
  stopSignal: stopAbortController.signal,
3808
- trackedMutationEvidenceForCompletionGuard: false,
3809
3763
  timeoutMessage,
3810
3764
  stopMessage,
3811
3765
  toolTimeoutMs: task.toolTimeoutMs ?? config.toolTimeoutMs,
@@ -3921,6 +3875,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3921
3875
  review: pr.review,
3922
3876
  timeoutRecovery: pr.timeoutRecovery,
3923
3877
  structuredOutput: pr.structuredOutput,
3878
+ structuredOutputFailed: pr.structuredOutputFailed,
3924
3879
  structuredOutputPath: pr.structuredOutputPath,
3925
3880
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
3926
3881
  acceptance: pr.acceptance,
@@ -4204,6 +4159,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4204
4159
  sessionDir: taskSessionDir,
4205
4160
  artifactsDir, artifactConfig, id,
4206
4161
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4162
+ projectTrusted: config.projectTrusted,
4207
4163
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4208
4164
  piPackageRoot: config.piPackageRoot,
4209
4165
  childSessions,
@@ -4213,7 +4169,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4213
4169
  nestedRoute: config.nestedRoute,
4214
4170
  capabilityCeiling: config.capabilityCeiling,
4215
4171
  runFanoutBudget: config.runFanoutBudget,
4216
- hostAvailableBuiltins: config.hostAvailableBuiltins,
4217
4172
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4218
4173
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4219
4174
  registerStop: (stop) => registerStepStop(fi, stop),
@@ -4221,7 +4176,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4221
4176
  onSteerOutcome: (request, delivery) => applySteerDelivery(request.id, fi, delivery),
4222
4177
  timeoutSignal: timeoutAbortController.signal,
4223
4178
  stopSignal: stopAbortController.signal,
4224
- trackedMutationEvidenceForCompletionGuard: Boolean(worktreeSetup),
4225
4179
  timeoutMessage,
4226
4180
  stopMessage,
4227
4181
  toolTimeoutMs: taskForRun.toolTimeoutMs ?? config.toolTimeoutMs,
@@ -4299,20 +4253,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4299
4253
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskDuration,
4300
4254
  }));
4301
4255
  if (stopped || childStopped) appendTerminalChildStatusEvent(fi, taskEndTime);
4302
- if (singleResult.completionGuardTriggered) {
4303
- const event = buildControlEvent(omitUndefinedProperties({
4304
- from: requiredStatusStep(statusPayload, fi).activityState,
4305
- to: "needs_attention",
4306
- runId: id,
4307
- agent: task.agent,
4308
- index: fi,
4309
- ts: taskEndTime,
4310
- message: `${task.agent} completed without making edits for an implementation task`,
4311
- reason: "completion_guard",
4312
- }));
4313
- appendControlEvent(event);
4314
- }
4315
-
4316
4256
  if (singleResult.exitCode !== 0 && failFast && !childStopped) aborted = true;
4317
4257
  return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: singleResult.output || (timeoutMessage ?? "Subagent timed out."), error: singleResult.error ?? timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
4318
4258
  },
@@ -4379,11 +4319,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4379
4319
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
4380
4320
  transcriptPath: pr.transcriptPath,
4381
4321
  transcriptError: pr.transcriptError,
4382
- effects: pr.effects,
4383
- execution: pr.execution,
4384
- review: pr.review,
4385
- timeoutRecovery: pr.timeoutRecovery,
4386
- structuredOutput: pr.structuredOutput,
4322
+ effects: pr.effects,
4323
+ execution: pr.execution,
4324
+ review: pr.review,
4325
+ timeoutRecovery: pr.timeoutRecovery,
4326
+ structuredOutput: pr.structuredOutput,
4327
+ structuredOutputFailed: pr.structuredOutputFailed,
4387
4328
  structuredOutputPath: pr.structuredOutputPath,
4388
4329
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
4389
4330
  acceptance: pr.acceptance,
@@ -4609,6 +4550,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4609
4550
  outputs: statusPayload.mode === "single" ? undefined : outputs,
4610
4551
  sessionDir: config.sessionDir,
4611
4552
  artifactsDir, artifactConfig, id,
4553
+ projectTrusted: config.projectTrusted,
4612
4554
  flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4613
4555
  outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4614
4556
  piPackageRoot: config.piPackageRoot,
@@ -4619,7 +4561,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4619
4561
  nestedRoute: config.nestedRoute,
4620
4562
  capabilityCeiling: config.capabilityCeiling,
4621
4563
  runFanoutBudget: config.runFanoutBudget,
4622
- hostAvailableBuiltins: config.hostAvailableBuiltins,
4623
4564
  registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4624
4565
  registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4625
4566
  registerStop: (stop) => registerStepStop(flatIndex, stop),
@@ -4684,6 +4625,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4684
4625
  review: singleResult.review,
4685
4626
  timeoutRecovery: singleResult.timeoutRecovery,
4686
4627
  structuredOutput: singleResult.structuredOutput,
4628
+ structuredOutputFailed: singleResult.structuredOutputFailed,
4687
4629
  structuredOutputPath: singleResult.structuredOutputPath,
4688
4630
  structuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,
4689
4631
  acceptance: singleResult.acceptance,
@@ -4843,20 +4785,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4843
4785
  });
4844
4786
  }
4845
4787
 
4846
- if (singleResult.completionGuardTriggered) {
4847
- const event = buildControlEvent(omitUndefinedProperties({
4848
- from: requiredStatusStep(statusPayload, flatIndex).activityState,
4849
- to: "needs_attention",
4850
- runId: id,
4851
- agent: seqStep.agent,
4852
- index: flatIndex,
4853
- ts: stepEndTime,
4854
- message: `${seqStep.agent} completed without making edits for an implementation task`,
4855
- reason: "completion_guard",
4856
- }));
4857
- appendControlEvent(event);
4858
- }
4859
-
4860
4788
  flatIndex++;
4861
4789
  if (isAgentContract(seqStep.agentContract) && seqStep.gateOn === "acceptance" && singleResult.acceptance?.status === "rejected") {
4862
4790
  statusPayload.error = acceptanceFailureMessage(singleResult.acceptance) ?? "Chain acceptance gate rejected the step.";
@@ -4970,6 +4898,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4970
4898
  timedOut = true;
4971
4899
  }
4972
4900
  disposeControlInbox();
4901
+ try {
4902
+ closeStopInbox(asyncDir);
4903
+ } catch (error) {
4904
+ // Result publication must not depend on the marker; without it a late stop is accepted as before.
4905
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.run.stop_inbox_close_failed", ts: Date.now(), runId: id, message: error instanceof Error ? error.message : String(error) }));
4906
+ }
4973
4907
  for (const request of consumeStopRequestPayloads(asyncDir)) stopChildStep(request);
4974
4908
  const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4975
4909
  processSignal: result.processSignal,
@@ -5101,6 +5035,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5101
5035
  review: r.review,
5102
5036
  effects: r.effects,
5103
5037
  structuredOutput: r.structuredOutput,
5038
+ structuredOutputFailed: r.structuredOutputFailed,
5104
5039
  structuredOutputPath: r.structuredOutputPath,
5105
5040
  structuredOutputSchemaPath: r.structuredOutputSchemaPath,
5106
5041
  acceptance: r.acceptance,
@@ -5218,152 +5153,40 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5218
5153
  }
5219
5154
  }
5220
5155
 
5221
- async function waitForStartupControl(
5222
- controlPath: string,
5223
- token: string,
5224
- action: "ack" | "confirm" | "proceed",
5225
- timeoutMs = 30_000,
5226
- ): Promise<void> {
5227
- const deadline = Date.now() + timeoutMs;
5228
- while (Date.now() <= deadline) {
5229
- if (fs.existsSync(controlPath)) {
5230
- let payload: { action?: unknown; token?: unknown };
5231
- try {
5232
- payload = JSON.parse(fs.readFileSync(controlPath, "utf-8")) as { action?: unknown; token?: unknown };
5233
- } catch (error) {
5234
- throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
5235
- }
5236
- if (payload.token !== token) throw new Error("Runner startup control token does not match.");
5237
- if (payload.action === action) return;
5238
- if (payload.action !== "ack" && payload.action !== "confirm" && payload.action !== "proceed") throw new Error("Runner startup control action is invalid.");
5239
- }
5240
- await new Promise((resolve) => setTimeout(resolve, 20));
5241
- }
5242
- throw new Error(`Timed out after ${timeoutMs}ms waiting for runner startup control '${action}'.`);
5243
- }
5244
-
5245
- // Both hosts enter here: startup authorization, revival leases and disposal stay shared.
5246
- export async function runConfiguredSubagent(config: SubagentRunConfig, options?: DefaultChildSessionFactoryOptions): Promise<void> {
5247
- let lease: ReturnType<typeof acquireSessionLease> | undefined;
5248
- let startupCommitted = config.revivalLease === undefined && config.launchBarrierToken === undefined;
5249
- const startupPath = path.join(config.asyncDir, "runner-startup.json");
5250
- const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
5251
- const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
5252
- const releaseOnExit = (): void => {
5253
- try {
5254
- lease?.release();
5255
- } catch {
5256
- // Exit cleanup is best effort; a dead-owner lease is reclaimed on the next revival.
5257
- }
5258
- };
5259
- process.once("exit", releaseOnExit);
5156
+ /** Heavy execution entry loaded by the bootstrap only after startup commits. */
5157
+ export async function runConfiguredSubagentExecution(config: SubagentRunConfig, options?: DefaultChildSessionFactoryOptions): Promise<void> {
5158
+ let childSessions: ChildSessionFactory;
5260
5159
  try {
5261
- if (config.launchBarrierToken) {
5262
- await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
5263
- startupCommitted = true;
5264
- try {
5265
- fs.rmSync(startupProceedPath, { force: true });
5266
- } catch {
5267
- // Startup control cleanup is best effort after the parent commits the run.
5268
- }
5269
- } else if (config.revivalLease) {
5270
- lease = acquireSessionLease(config.revivalLease);
5271
- config.revivalLeaseToken = lease.owner.token;
5272
- writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
5273
- await waitForStartupControl(startupAckPath, lease.owner.token, "ack");
5274
- writeAtomicJson(startupPath, { state: "acknowledged", token: lease.owner.token, pid: process.pid });
5275
- await waitForStartupControl(startupAckPath, lease.owner.token, "confirm");
5276
- writeAtomicJson(startupPath, { state: "confirmed", token: lease.owner.token, pid: process.pid });
5277
- await waitForStartupControl(startupProceedPath, lease.owner.token, "proceed");
5278
- startupCommitted = true;
5279
- for (const controlPath of [startupAckPath, startupProceedPath]) {
5280
- try {
5281
- fs.rmSync(controlPath, { force: true });
5282
- } catch {
5283
- // Startup control cleanup is best effort after the parent commits the run.
5284
- }
5285
- }
5286
- }
5287
- const childSessions = await loadRunnerChildSessionFactory(config, options);
5288
- try {
5289
- await runSubagent(config, childSessions);
5290
- } finally {
5291
- try {
5292
- await childSessions.dispose();
5293
- } catch (error) {
5294
- console.error("Failed to dispose runner child sessions:", error);
5295
- }
5296
- }
5160
+ // Detached Node runners do not receive Pi's CLI dispatcher setup. Binary
5161
+ // hosts install the same dispatcher before entering the shared bootstrap.
5162
+ if (!options?.loadPiCodingAgent) installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
5163
+ childSessions = await loadRunnerChildSessionFactory(config, options);
5297
5164
  } catch (error) {
5298
- if (!startupCommitted) {
5299
- try {
5300
- writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
5301
- } catch {
5302
- // The parent will time out and terminate this runner if the handshake cannot be written.
5303
- }
5165
+ try {
5166
+ persistRunnerStartupFailure({
5167
+ asyncDir: config.asyncDir,
5168
+ runId: config.id,
5169
+ runnerProcessInstanceId: config.runnerProcessInstanceId ?? "unknown-runner-instance",
5170
+ message: `Subagent runner startup failed: ${error instanceof Error ? error.message : String(error)}`,
5171
+ ...(config.sessionId ? { sessionId: config.sessionId } : {}),
5172
+ ...(config.completionOwnerId ? { completionOwnerId: config.completionOwnerId } : {}),
5173
+ candidate: {
5174
+ ...(config.revivalLease?.sessionFile ? { sessionFile: config.revivalLease.sessionFile } : {}),
5175
+ ...(config.revivalLeaseToken ? { revivalLeaseToken: config.revivalLeaseToken } : {}),
5176
+ },
5177
+ });
5178
+ } catch (persistenceError) {
5179
+ console.error("Failed to persist runner setup failure:", persistenceError);
5304
5180
  }
5305
5181
  throw error;
5306
- } finally {
5307
- process.off("exit", releaseOnExit);
5308
- if (lease) {
5309
- let acknowledged = false;
5310
- try {
5311
- acknowledged = lease.release();
5312
- } catch (error) {
5313
- console.error("Failed to release session revival lease:", error);
5314
- }
5315
- try {
5316
- markProcessTerminalCandidateLeaseRelease(config.asyncDir, lease.owner.token, acknowledged);
5317
- } catch (error) {
5318
- console.error("Failed to record session revival lease release:", error);
5319
- }
5320
- }
5321
5182
  }
5322
- }
5323
-
5324
- function startConfiguredSubagent(config: SubagentRunConfig): void {
5325
- // Child sessions and the extensions loaded into them may leave handles
5326
- // behind even after shutdown; the run is fully persisted by now, so exit
5327
- // explicitly instead of waiting for the event loop to drain.
5328
- runConfiguredSubagent(config).then(
5329
- () => process.exit(0),
5330
- (runErr) => {
5331
- console.error("Subagent runner error:", runErr);
5332
- process.exit(1);
5333
- },
5334
- );
5335
- }
5336
-
5337
- if (isRunnerEntrypoint) {
5338
- const configArg = process.argv[2];
5339
- if (configArg) {
5340
5183
  try {
5341
- const configJson = fs.readFileSync(configArg, "utf-8");
5342
- const config = JSON.parse(configJson) as SubagentRunConfig;
5184
+ await runSubagent(config, childSessions);
5185
+ } finally {
5343
5186
  try {
5344
- fs.unlinkSync(configArg);
5345
- } catch {
5346
- // Temp config cleanup is best effort.
5187
+ await childSessions.dispose();
5188
+ } catch (error) {
5189
+ console.error("Failed to dispose runner child sessions:", error);
5347
5190
  }
5348
- startConfiguredSubagent(config);
5349
- } catch (err) {
5350
- console.error("Subagent runner error:", err);
5351
- process.exit(1);
5352
5191
  }
5353
- } else {
5354
- let input = "";
5355
- process.stdin.setEncoding("utf-8");
5356
- process.stdin.on("data", (chunk) => {
5357
- input += chunk;
5358
- });
5359
- process.stdin.on("end", () => {
5360
- try {
5361
- const config = JSON.parse(input) as SubagentRunConfig;
5362
- startConfiguredSubagent(config);
5363
- } catch (err) {
5364
- console.error("Subagent runner error:", err);
5365
- process.exit(1);
5366
- }
5367
- });
5368
- }
5369
5192
  }