@xzzpig/pi-subagents 0.16.0 → 0.18.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 (133) hide show
  1. package/CHANGELOG.md +164 -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 +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. 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";
@@ -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";
@@ -225,7 +220,6 @@ export interface SubagentRunConfig {
225
220
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
226
221
  runFanoutBudget?: RunFanoutBudgetDescriptor;
227
222
  /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
228
- hostAvailableBuiltins?: readonly string[];
229
223
  launchContractDigest?: string;
230
224
  launchResolvedExtensions?: LaunchResolvedChildExtensions;
231
225
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
@@ -285,6 +279,7 @@ interface StepResult {
285
279
  review?: import("../../shared/types.ts").ReviewProjection;
286
280
  effects?: import("../../shared/types.ts").EffectsProjection;
287
281
  structuredOutput?: unknown;
282
+ structuredOutputFailed?: boolean;
288
283
  structuredOutputPath?: string;
289
284
  structuredOutputSchemaPath?: string;
290
285
  acceptance?: import("../../shared/types.ts").AcceptanceLedger;
@@ -710,7 +705,6 @@ interface SingleStepContext {
710
705
  nestedRoute?: NestedRouteInfo;
711
706
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
712
707
  runFanoutBudget?: RunFanoutBudgetDescriptor;
713
- hostAvailableBuiltins?: readonly string[];
714
708
  onAttemptStart?: (attempt: { model?: string; thinking?: string; contextLimit?: number }) => void;
715
709
  onChildEvent?: (event: ChildEvent) => void;
716
710
  onExternalProcess?: (process: ExternalProcessStatus) => void;
@@ -722,8 +716,6 @@ interface SingleStepContext {
722
716
  usageBudgetExhausted?: () => boolean | undefined;
723
717
  /** Existing run-owned budget configuration; cost allowance is not settled by the live token ledger. */
724
718
  usageBudget?: UsageBudgetConfig;
725
- /** False when sibling work in the same Git worktree could have caused the tracked diff. */
726
- trackedMutationEvidenceForCompletionGuard?: boolean;
727
719
  orcaProgressTab?: OrcaProgressTab;
728
720
  }
729
721
 
@@ -749,7 +741,7 @@ export async function settleHerdrExternalRunnerError(error: unknown, adapter: He
749
741
  export async function runSingleStepInner(
750
742
  step: SubagentStep,
751
743
  ctx: SingleStepContext,
752
- ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
744
+ ): Promise<StepResult> {
753
745
  if (step.importAsyncRoot) {
754
746
  let importTimedOut = false;
755
747
  let importStopped = false;
@@ -827,7 +819,6 @@ export async function runSingleStepInner(
827
819
  const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
828
820
  let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
829
821
  if (ctx.outputs) task = resolveOutputReferences(task, ctx.outputs);
830
- const taskForCompletionGuard = task;
831
822
  let resolvedTaskToolPlan: ReturnType<typeof resolvePiLaunchToolPlan> | undefined;
832
823
  if (!step.runner) {
833
824
  resolvedTaskToolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
@@ -846,30 +837,7 @@ export async function runSingleStepInner(
846
837
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
847
838
  requiredExtensions: step.requiredExtensions ?? ctx.inheritedChildRuntime?.requiredExtensions,
848
839
  permissionRules: step.permissionRules,
849
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
850
840
  }));
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
841
  }
874
842
  // Derive from the pre-acceptance task so internal acceptance/recovery
875
843
  // instructions never leak into the display name.
@@ -1121,7 +1089,6 @@ export async function runSingleStepInner(
1121
1089
  let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1122
1090
  let structuredAcceptanceReport: unknown;
1123
1091
  let structuredAcceptanceReportError: string | undefined;
1124
- let completionGuardTriggeredFinal = false;
1125
1092
  let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1126
1093
  let toolBudgetBlocked = false;
1127
1094
  let actualLaunchContractDigest = step.launchContractDigest;
@@ -1133,6 +1100,7 @@ export async function runSingleStepInner(
1133
1100
  const aggregateUsage = emptyUsage();
1134
1101
  let launched = false;
1135
1102
  let recoveryTask = task;
1103
+ let stagedIndexBaseline: string | undefined;
1136
1104
  singleLaunch: for (let attemptIndex = 0; attemptIndex < 2; attemptIndex++) {
1137
1105
  if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break singleLaunch;
1138
1106
  const expectedModelForVerification = candidate && !step.skipPrimaryModelVerification ? candidate : undefined;
@@ -1142,9 +1110,9 @@ export async function runSingleStepInner(
1142
1110
  const message = error instanceof Error ? error.message : String(error);
1143
1111
  return omitUndefinedProperties({ agent: step.agent, output: message, error: message, exitCode: 1, context: step.context, thinkingCeiling: step.thinkingCeiling });
1144
1112
  }
1113
+ const attemptModel = omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) });
1145
1114
  ctx.onAttemptStart?.(omitUndefinedProperties({
1146
- model: candidate,
1147
- thinking: resolveEffectiveThinking(candidate, step.thinking),
1115
+ ...attemptModel,
1148
1116
  contextLimit: findModelInfo(candidate, step.modelVerificationRegistry)?.contextWindow,
1149
1117
  }));
1150
1118
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
@@ -1203,7 +1171,6 @@ export async function runSingleStepInner(
1203
1171
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1204
1172
  requiredExtensions: step.requiredExtensions ?? ctx.inheritedChildRuntime?.requiredExtensions,
1205
1173
  permissionRules: step.permissionRules,
1206
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
1207
1174
  }));
1208
1175
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1209
1176
  actualLaunchContractDigest = resolveLaunchBinding({
@@ -1229,6 +1196,14 @@ export async function runSingleStepInner(
1229
1196
  // Each attempt rewrites the step output log; synchronous appends keep a
1230
1197
  // retried attempt from interleaving with the previous attempt's flush.
1231
1198
  fs.writeFileSync(ctx.outputFile, "", "utf-8");
1199
+ if (step.effectiveAcceptance?.preserveStagedIndex && stagedIndexBaseline === undefined) {
1200
+ try {
1201
+ stagedIndexBaseline = captureStagedIndexBaseline(step.cwd ?? ctx.cwd);
1202
+ } catch (error) {
1203
+ const message = error instanceof Error ? error.message : String(error);
1204
+ return { agent: step.agent, output: message, error: message, exitCode: 1, context: step.context };
1205
+ }
1206
+ }
1232
1207
  const run = await runChildSession(omitUndefinedProperties({
1233
1208
  factory: ctx.childSessions,
1234
1209
  launch,
@@ -1253,6 +1228,7 @@ export async function runSingleStepInner(
1253
1228
  timeoutMessage: ctx.timeoutMessage,
1254
1229
  stopMessage: ctx.stopMessage,
1255
1230
  onChildEvent: ctx.onChildEvent,
1231
+ onContextWindow: (contextLimit) => ctx.onAttemptStart?.({ ...attemptModel, contextLimit }),
1256
1232
  transcriptWriter,
1257
1233
  toolTimeoutMs: ctx.toolTimeoutMs,
1258
1234
  runDeadlineAt: ctx.deadlineAt,
@@ -1268,9 +1244,9 @@ export async function runSingleStepInner(
1268
1244
  aggregateUsage.cacheWrite += run.usage.cacheWrite;
1269
1245
  aggregateUsage.cost += run.usage.cost;
1270
1246
  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;
1247
+ // A parked run still owes output diagnostics when it actually finishes.
1248
+ // Stopped/timedOut runs already have terminal failures, so terminal output diagnostics are deferred.
1249
+ const terminalDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
1274
1250
  const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
1275
1251
  const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
1276
1252
  const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
@@ -1286,16 +1262,23 @@ export async function runSingleStepInner(
1286
1262
  let structuredOutput: unknown;
1287
1263
  let structuredError: string | undefined;
1288
1264
  let validatedStructuredOutput = false;
1289
- if (completionDiagnosticsEligible && effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError) {
1290
- if (!run.structuredOutputToolInvoked) {
1265
+ if (effectiveStructuredOutput) {
1266
+ const otherwiseSuccessful = terminalDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError;
1267
+ if (!run.structuredOutputToolInvoked && otherwiseSuccessful) {
1291
1268
  structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1292
- } else {
1269
+ } else if (run.structuredOutputToolInvoked) {
1293
1270
  const structured = await readStructuredOutput({
1294
1271
  schema: effectiveStructuredOutput.schema,
1295
1272
  schemaPath: effectiveStructuredOutput.schemaPath,
1296
1273
  outputPath: effectiveStructuredOutput.outputPath,
1297
1274
  });
1298
- if (structured.error) structuredError = structured.error;
1275
+ if (structured.error) {
1276
+ if (otherwiseSuccessful) {
1277
+ structuredError = structured.error === MISSING_STRUCTURED_OUTPUT_CALL_ERROR
1278
+ ? formatStructuredOutputRejectionError(run.messages)
1279
+ : structured.error;
1280
+ }
1281
+ }
1299
1282
  else {
1300
1283
  structuredOutput = structured.value;
1301
1284
  const acceptanceReport = readStructuredOutputAcceptanceReport(effectiveStructuredOutput);
@@ -1308,13 +1291,13 @@ export async function runSingleStepInner(
1308
1291
  const errorMessages = validatedStructuredOutput
1309
1292
  ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1310
1293
  : run.messages;
1311
- const hiddenError = completionDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1294
+ const hiddenError = terminalDiagnosticsEligible && run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1312
1295
  ? detectSubagentError(errorMessages)
1313
1296
  : null;
1314
1297
  const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1315
1298
  && hasEmptyTerminalAssistantResponse(run.messages)
1316
1299
  && (run.toolCount > 0 || Boolean(run.finalOutput.trim()));
1317
- const emptyOutputError = completionDiagnosticsEligible && run.exitCode === 0
1300
+ const emptyOutputError = terminalDiagnosticsEligible && run.exitCode === 0
1318
1301
  && !run.error
1319
1302
  && !toolAvailabilityError
1320
1303
  && !structuredError
@@ -1323,48 +1306,10 @@ export async function runSingleStepInner(
1323
1306
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1324
1307
  ? formatEmptyTerminalAssistantResponseError(run.messages)
1325
1308
  : 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
1309
  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
1310
  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
1311
  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
- });
1312
+ const mutationAttemptObserved = run.observedMutationAttempt === true || mutationEvidence.attemptedMutation === true;
1368
1313
  const finalOutputHasPersistableFileContent = run.exitCode === 0 && !run.error && !emptyOutputError && Boolean(stripAcceptanceReport(run.finalOutput).trim());
1369
1314
  const requiredOutput = step.outputMode === "file-only" && step.outputPath
1370
1315
  ? { kind: "file-only" as const, path: step.outputPath, missing: !fs.existsSync(step.outputPath) && !finalOutputHasPersistableFileContent }
@@ -1372,9 +1317,9 @@ export async function runSingleStepInner(
1372
1317
  ? { kind: "structured" as const, path: effectiveStructuredOutput.outputPath, missing: !fs.existsSync(effectiveStructuredOutput.outputPath) }
1373
1318
  : undefined;
1374
1319
  finalRequiredOutputMissing = requiredOutput?.missing;
1375
- const missingRequiredOutputError = completionDiagnosticsEligible ? formatRequiredOutputError(requiredOutput) : undefined;
1320
+ const missingRequiredOutputError = terminalDiagnosticsEligible ? formatRequiredOutputError(requiredOutput) : undefined;
1376
1321
  const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1377
- const effectiveExitCode = toolAvailabilityError || completionEvidence.legacyFailureError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1322
+ const effectiveExitCode = toolAvailabilityError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1378
1323
  ? 1
1379
1324
  : hiddenError?.hasError
1380
1325
  ? (hiddenError.exitCode ?? 1)
@@ -1392,8 +1337,7 @@ export async function runSingleStepInner(
1392
1337
  ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1393
1338
  : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1394
1339
  : undefined);
1395
- const error = underlyingError ?? missingRequiredOutputError ?? completionEvidence.legacyFailureError;
1396
- completionGuardTriggeredFinal = completionEvidence.guardTriggered && !underlyingError && !missingRequiredOutputError;
1340
+ const error = underlyingError ?? missingRequiredOutputError;
1397
1341
  finalOutputSnapshot = outputSnapshot;
1398
1342
  if (step.toolBudget) {
1399
1343
  const toolMessages = run.messages.filter((message) => message.role === "toolResult");
@@ -1401,18 +1345,16 @@ export async function runSingleStepInner(
1401
1345
  toolBudgetBlocked = Boolean(blockedMessage);
1402
1346
  toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1403
1347
  }
1404
- const settlementDiagnostic = projectSettlementDiagnostic(completionEvidence, {
1405
- terminalFailed: effectiveExitCode !== 0,
1348
+ const settlementDiagnostic = effectiveExitCode !== 0 ? {
1406
1349
  finalTextPresent: Boolean(stripAcceptanceReport(run.finalOutput).trim()),
1407
- mutationObserved: mutationEvidence.attemptedMutation,
1408
- requiredOutput,
1350
+ mutation: { attempted: mutationAttemptObserved, observed: mutationEvidence.attemptedMutation },
1351
+ ...(requiredOutput ? { requiredOutput } : {}),
1409
1352
  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;
1353
+ } : undefined;
1354
+ const fileMutationEffect = missingRequiredOutputAfterMutation ? { status: "observed" as const, attempted: true as const, evidence: mutationEvidence } : undefined;
1355
+ 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
1356
  if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break singleLaunch;
1414
1357
  if (effectiveExitCode === 0 && !error) break singleLaunch;
1415
- if (completionEvidence.guardTriggered) break singleLaunch;
1416
1358
  const recovery = planAbortRecovery({
1417
1359
  messages: run.messages,
1418
1360
  error,
@@ -1509,6 +1451,7 @@ export async function runSingleStepInner(
1509
1451
  ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only", durable: resolvedOutput.savedPath !== undefined }
1510
1452
  : undefined,
1511
1453
  cwd: step.cwd ?? ctx.cwd,
1454
+ stagedIndexBaseline,
1512
1455
  signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
1513
1456
  abortMessage: ctx.stopSignal?.aborted ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.",
1514
1457
  reportOptional: isAgentContract(step.agentContract),
@@ -1529,6 +1472,12 @@ export async function runSingleStepInner(
1529
1472
  const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
1530
1473
  const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !isAgentContract(step.agentContract);
1531
1474
  const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1475
+ // A passing typed gate supplies the structured output for runs that have no
1476
+ // outputSchema of their own; preflight rejects the combination.
1477
+ const typedGate = typedVerifyOutput(effectiveAcceptance);
1478
+ if (typedGate && finalResult && finalResult.structuredOutput === undefined && effectiveFinalExitCode === 0) {
1479
+ finalResult = { ...finalResult, structuredOutput: typedGate.value };
1480
+ }
1532
1481
  const intercomDetachReceipt = finalResult?.finalOutput === INTERCOM_DETACH_RECEIPT;
1533
1482
  const baseFinalError = stoppedAfterAcceptance
1534
1483
  ? ctx.stopMessage ?? "Subagent stopped by user."
@@ -1578,7 +1527,7 @@ export async function runSingleStepInner(
1578
1527
  })
1579
1528
  : {};
1580
1529
 
1581
- const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
1530
+ const result: StepResult = omitUndefinedProperties({
1582
1531
  agent: step.agent,
1583
1532
  ...(childSessionName ? { sessionName: childSessionName } : {}),
1584
1533
  context: step.context,
@@ -1610,11 +1559,11 @@ export async function runSingleStepInner(
1610
1559
  timeoutRecovery,
1611
1560
  toolBudget,
1612
1561
  toolBudgetBlocked: toolBudgetBlocked || undefined,
1613
- completionGuardTriggered: completionGuardTriggeredFinal,
1614
1562
  ...((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,
1563
+ structuredOutput: (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1564
+ structuredOutputFailed: finalResult?.structuredOutputFailed,
1565
+ structuredOutputPath: effectiveStructuredOutput?.outputPath,
1566
+ structuredOutputSchemaPath: effectiveStructuredOutput?.schemaPath,
1618
1567
  acceptance: effectiveAcceptance,
1619
1568
  watchdog: finalResult?.watchdog,
1620
1569
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
@@ -1627,7 +1576,7 @@ export async function runSingleStepInner(
1627
1576
  async function runSingleStep(
1628
1577
  step: SubagentStep,
1629
1578
  ctx: SingleStepContext,
1630
- ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
1579
+ ): Promise<StepResult> {
1631
1580
  if (!step.importAsyncRoot) ctx.orcaProgressTab?.section({ agent: step.agent, index: ctx.flatIndex, count: ctx.flatStepCount });
1632
1581
  return runSingleStepInner(step, ctx);
1633
1582
  }
@@ -2107,6 +2056,7 @@ export async function runSubagent(
2107
2056
  ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2108
2057
  ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2109
2058
  pid: process.pid,
2059
+ pidNamespaceScope: currentPidNamespaceScope(),
2110
2060
  cwd,
2111
2061
  currentStep: 0,
2112
2062
  chainStepCount: steps.length,
@@ -3797,7 +3747,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3797
3747
  nestedRoute: config.nestedRoute,
3798
3748
  capabilityCeiling: config.capabilityCeiling,
3799
3749
  runFanoutBudget: config.runFanoutBudget,
3800
- hostAvailableBuiltins: config.hostAvailableBuiltins,
3801
3750
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
3802
3751
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
3803
3752
  registerStop: (stop) => registerStepStop(fi, stop),
@@ -3805,7 +3754,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3805
3754
  onSteerOutcome: (request, delivery) => applySteerDelivery(request.id, fi, delivery),
3806
3755
  timeoutSignal: timeoutAbortController.signal,
3807
3756
  stopSignal: stopAbortController.signal,
3808
- trackedMutationEvidenceForCompletionGuard: false,
3809
3757
  timeoutMessage,
3810
3758
  stopMessage,
3811
3759
  toolTimeoutMs: task.toolTimeoutMs ?? config.toolTimeoutMs,
@@ -3921,6 +3869,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3921
3869
  review: pr.review,
3922
3870
  timeoutRecovery: pr.timeoutRecovery,
3923
3871
  structuredOutput: pr.structuredOutput,
3872
+ structuredOutputFailed: pr.structuredOutputFailed,
3924
3873
  structuredOutputPath: pr.structuredOutputPath,
3925
3874
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
3926
3875
  acceptance: pr.acceptance,
@@ -4213,7 +4162,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4213
4162
  nestedRoute: config.nestedRoute,
4214
4163
  capabilityCeiling: config.capabilityCeiling,
4215
4164
  runFanoutBudget: config.runFanoutBudget,
4216
- hostAvailableBuiltins: config.hostAvailableBuiltins,
4217
4165
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4218
4166
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4219
4167
  registerStop: (stop) => registerStepStop(fi, stop),
@@ -4221,7 +4169,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4221
4169
  onSteerOutcome: (request, delivery) => applySteerDelivery(request.id, fi, delivery),
4222
4170
  timeoutSignal: timeoutAbortController.signal,
4223
4171
  stopSignal: stopAbortController.signal,
4224
- trackedMutationEvidenceForCompletionGuard: Boolean(worktreeSetup),
4225
4172
  timeoutMessage,
4226
4173
  stopMessage,
4227
4174
  toolTimeoutMs: taskForRun.toolTimeoutMs ?? config.toolTimeoutMs,
@@ -4299,20 +4246,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4299
4246
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskDuration,
4300
4247
  }));
4301
4248
  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
4249
  if (singleResult.exitCode !== 0 && failFast && !childStopped) aborted = true;
4317
4250
  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
4251
  },
@@ -4379,11 +4312,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4379
4312
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
4380
4313
  transcriptPath: pr.transcriptPath,
4381
4314
  transcriptError: pr.transcriptError,
4382
- effects: pr.effects,
4383
- execution: pr.execution,
4384
- review: pr.review,
4385
- timeoutRecovery: pr.timeoutRecovery,
4386
- structuredOutput: pr.structuredOutput,
4315
+ effects: pr.effects,
4316
+ execution: pr.execution,
4317
+ review: pr.review,
4318
+ timeoutRecovery: pr.timeoutRecovery,
4319
+ structuredOutput: pr.structuredOutput,
4320
+ structuredOutputFailed: pr.structuredOutputFailed,
4387
4321
  structuredOutputPath: pr.structuredOutputPath,
4388
4322
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
4389
4323
  acceptance: pr.acceptance,
@@ -4619,7 +4553,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4619
4553
  nestedRoute: config.nestedRoute,
4620
4554
  capabilityCeiling: config.capabilityCeiling,
4621
4555
  runFanoutBudget: config.runFanoutBudget,
4622
- hostAvailableBuiltins: config.hostAvailableBuiltins,
4623
4556
  registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4624
4557
  registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4625
4558
  registerStop: (stop) => registerStepStop(flatIndex, stop),
@@ -4684,6 +4617,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4684
4617
  review: singleResult.review,
4685
4618
  timeoutRecovery: singleResult.timeoutRecovery,
4686
4619
  structuredOutput: singleResult.structuredOutput,
4620
+ structuredOutputFailed: singleResult.structuredOutputFailed,
4687
4621
  structuredOutputPath: singleResult.structuredOutputPath,
4688
4622
  structuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,
4689
4623
  acceptance: singleResult.acceptance,
@@ -4843,20 +4777,6 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4843
4777
  });
4844
4778
  }
4845
4779
 
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
4780
  flatIndex++;
4861
4781
  if (isAgentContract(seqStep.agentContract) && seqStep.gateOn === "acceptance" && singleResult.acceptance?.status === "rejected") {
4862
4782
  statusPayload.error = acceptanceFailureMessage(singleResult.acceptance) ?? "Chain acceptance gate rejected the step.";
@@ -5101,6 +5021,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5101
5021
  review: r.review,
5102
5022
  effects: r.effects,
5103
5023
  structuredOutput: r.structuredOutput,
5024
+ structuredOutputFailed: r.structuredOutputFailed,
5104
5025
  structuredOutputPath: r.structuredOutputPath,
5105
5026
  structuredOutputSchemaPath: r.structuredOutputSchemaPath,
5106
5027
  acceptance: r.acceptance,
@@ -5218,152 +5139,40 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5218
5139
  }
5219
5140
  }
5220
5141
 
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);
5142
+ /** Heavy execution entry loaded by the bootstrap only after startup commits. */
5143
+ export async function runConfiguredSubagentExecution(config: SubagentRunConfig, options?: DefaultChildSessionFactoryOptions): Promise<void> {
5144
+ let childSessions: ChildSessionFactory;
5260
5145
  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
- }
5146
+ // Detached Node runners do not receive Pi's CLI dispatcher setup. Binary
5147
+ // hosts install the same dispatcher before entering the shared bootstrap.
5148
+ if (!options?.loadPiCodingAgent) installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
5149
+ childSessions = await loadRunnerChildSessionFactory(config, options);
5297
5150
  } 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
- }
5151
+ try {
5152
+ persistRunnerStartupFailure({
5153
+ asyncDir: config.asyncDir,
5154
+ runId: config.id,
5155
+ runnerProcessInstanceId: config.runnerProcessInstanceId ?? "unknown-runner-instance",
5156
+ message: `Subagent runner startup failed: ${error instanceof Error ? error.message : String(error)}`,
5157
+ ...(config.sessionId ? { sessionId: config.sessionId } : {}),
5158
+ ...(config.completionOwnerId ? { completionOwnerId: config.completionOwnerId } : {}),
5159
+ candidate: {
5160
+ ...(config.revivalLease?.sessionFile ? { sessionFile: config.revivalLease.sessionFile } : {}),
5161
+ ...(config.revivalLeaseToken ? { revivalLeaseToken: config.revivalLeaseToken } : {}),
5162
+ },
5163
+ });
5164
+ } catch (persistenceError) {
5165
+ console.error("Failed to persist runner setup failure:", persistenceError);
5304
5166
  }
5305
5167
  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
5168
  }
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
5169
  try {
5341
- const configJson = fs.readFileSync(configArg, "utf-8");
5342
- const config = JSON.parse(configJson) as SubagentRunConfig;
5170
+ await runSubagent(config, childSessions);
5171
+ } finally {
5343
5172
  try {
5344
- fs.unlinkSync(configArg);
5345
- } catch {
5346
- // Temp config cleanup is best effort.
5173
+ await childSessions.dispose();
5174
+ } catch (error) {
5175
+ console.error("Failed to dispose runner child sessions:", error);
5347
5176
  }
5348
- startConfiguredSubagent(config);
5349
- } catch (err) {
5350
- console.error("Subagent runner error:", err);
5351
- process.exit(1);
5352
5177
  }
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
5178
  }