@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
@@ -53,9 +53,6 @@ import {
53
53
  } from "../../shared/utils.ts";
54
54
  import { resolveSkillsWithFallback } from "../../agents/skills.ts";
55
55
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
56
- import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
57
- import { planCompletionEvidence } from "../shared/completion-evidence.ts";
58
- import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
59
56
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
60
57
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
61
58
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
@@ -66,7 +63,7 @@ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
66
63
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
67
64
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
68
65
  import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
69
- import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
66
+ import { formatStructuredOutputRejectionError, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
70
67
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
71
68
  import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
72
69
  import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
@@ -89,10 +86,10 @@ import {
89
86
  shouldEscalateMutatingFailures,
90
87
  summarizeRecentMutatingFailures,
91
88
  } from "../shared/long-running-guard.ts";
92
- import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
89
+ import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, captureStagedIndexBaseline, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput, typedVerifyOutput } from "../shared/acceptance.ts";
93
90
  import { PROMPT_REDACTED } from "../../shared/utils.ts";
94
91
  import { attachContractProjections, isAgentContract } from "../shared/agent-contract.ts";
95
- import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
92
+ import { initialToolBudgetState, isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.ts";
96
93
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
97
94
  import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
98
95
  import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
@@ -108,6 +105,7 @@ import {
108
105
  } from "../../watchdog/child-status.ts";
109
106
  import { buildInProcessChildLaunch, createReportedChildSessionInput } from "../shared/child-launch.ts";
110
107
  import { childSessionFactory, childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
108
+ import { reconcileAttemptUsage } from "../shared/usage-reconciliation.ts";
111
109
 
112
110
  const artifactOutputByResult = new WeakMap<SingleResult, string>();
113
111
  const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
@@ -160,7 +158,7 @@ function persistSingleResultMetadata(input: {
160
158
  toolCount: target.progressSummary?.toolCount,
161
159
  error: target.error,
162
160
  agentContract: target.agentContract,
163
- sandbox: target.sandbox,
161
+ sandbox: target.sandbox,
164
162
  launchContractDigest: target.launchContractDigest,
165
163
  launchResolvedExtensions: target.launchResolvedExtensions,
166
164
  runtimeAcknowledgedExtensions: target.runtimeAcknowledgedExtensions,
@@ -288,6 +286,7 @@ interface StructuredDelegationProgressState {
288
286
  model?: string;
289
287
  toolCount: number;
290
288
  tokens: number;
289
+ turnCount?: number;
291
290
  }
292
291
 
293
292
  function captureStructuredDelegationProgressState(progress: AgentProgress, result: SingleResult): StructuredDelegationProgressState {
@@ -300,6 +299,7 @@ function captureStructuredDelegationProgressState(progress: AgentProgress, resul
300
299
  model: progress.model ?? result.model,
301
300
  toolCount: progress.toolCount,
302
301
  tokens: progress.tokens,
302
+ turnCount: progress.turnCount,
303
303
  };
304
304
  }
305
305
 
@@ -314,6 +314,7 @@ function structuredDelegationProgressChanged(
314
314
  || previous.model !== (progress.model ?? result.model)
315
315
  || previous.toolCount !== progress.toolCount
316
316
  || previous.tokens !== progress.tokens
317
+ || previous.turnCount !== progress.turnCount
317
318
  || previous.recentOutput.length !== progress.recentOutput.length) return true;
318
319
  for (let index = 0; index < progress.recentOutput.length; index++) {
319
320
  if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
@@ -328,6 +329,9 @@ function structuredDelegationProgressChanged(
328
329
  return false;
329
330
  }
330
331
 
332
+ function isCompleteUsageCounter(value: unknown): value is number {
333
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
334
+ }
331
335
 
332
336
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
333
337
  const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
@@ -376,8 +380,8 @@ async function runSingleAttempt(
376
380
  })
377
381
  : undefined;
378
382
  const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
379
- const sandbox = options.sandbox ?? agent.sandbox;
380
- const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
383
+ const sandbox = options.sandbox ?? agent.sandbox;
384
+ const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
381
385
  const permissionAuditPath = permissionRules && options.artifactsDir
382
386
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
383
387
  : undefined;
@@ -400,6 +404,7 @@ async function runSingleAttempt(
400
404
  tools: agent.tools,
401
405
  excludeTools: agent.excludeTools,
402
406
  allowNestedSubagents: agent.allowNestedSubagents,
407
+ descendantAllowedAgents: agent.allowedAgents,
403
408
  extensions: agent.extensions,
404
409
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
405
410
  // Exact terminal protocol belongs to session resources, not compactable history.
@@ -421,10 +426,10 @@ async function runSingleAttempt(
421
426
  toolBudget: options.toolBudget,
422
427
  permissionRules,
423
428
  permissionAuditPath,
424
- sandbox,
425
- permissionProfile,
426
- projectTrusted: options.projectTrusted,
427
- trustedProjectCwd: options.trustedProjectCwd,
429
+ sandbox,
430
+ permissionProfile,
431
+ projectTrusted: options.projectTrusted,
432
+ trustedProjectCwd: options.trustedProjectCwd,
428
433
  childWatchdog,
429
434
  // registerChildWatchdog returns before reading the sink when no watchdog exists.
430
435
  watchdogStatus: childWatchdog ? (event) => onWatchdogStatus?.(event) : undefined,
@@ -434,7 +439,6 @@ async function runSingleAttempt(
434
439
  thinkingCeiling: options.thinkingCeiling,
435
440
  maxSubagentDepth: options.maxSubagentDepth,
436
441
  runtimeSnapshotHost: options.runtimeSnapshotHost,
437
- hostAvailableBuiltins: options.hostAvailableBuiltins,
438
442
  inherited: options.childRuntime,
439
443
  host: "parent",
440
444
  });
@@ -446,34 +450,6 @@ async function runSingleAttempt(
446
450
  }
447
451
 
448
452
  const effectiveSystemPrompt = shared.systemPrompt;
449
- const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
450
- const contractError = validateImplementationToolContract({
451
- agent: agent.name,
452
- task: shared.originalTask ?? task,
453
- tools: contractTools,
454
- mcpDirectTools: toolPlan.effectiveMcpTools,
455
- configuredExtensions: toolPlan.configuredExtensions,
456
- requestedTools: toolPlan.requestedBuiltinTools,
457
- acceptanceRole: agent.acceptanceRole,
458
- completionGuard: agent.completionGuard,
459
- });
460
- if (contractError) {
461
- return {
462
- index: options.index ?? 0,
463
- agent: agent.name,
464
- task,
465
- ...(childSessionName ? { sessionName: childSessionName } : {}),
466
- messages: [],
467
- finalOutput: "",
468
- exitCode: 1,
469
- error: contractError,
470
- usage: emptyUsage(),
471
- model: modelArg,
472
- progressSummary: { status: "failed", toolCount: 0, tokens: 0, durationMs: 0 },
473
- ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
474
- ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
475
- };
476
- }
477
453
  const fast = options.fast ?? agent.fast;
478
454
  const { launchContractDigest } = resolveLaunchBinding({
479
455
  agent,
@@ -482,12 +458,12 @@ async function runSingleAttempt(
482
458
  ...(fast !== undefined ? { fast } : {}),
483
459
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
484
460
  systemPrompt: effectiveSystemPrompt,
485
- systemPromptMode: agent.systemPromptMode,
486
- inheritProjectContext: agent.inheritProjectContext,
487
- inheritGlobalContext: agent.inheritGlobalContext,
488
- inheritSkills: agent.inheritSkills,
489
- sandbox,
490
- permissionProfile,
461
+ systemPromptMode: agent.systemPromptMode,
462
+ inheritProjectContext: agent.inheritProjectContext,
463
+ inheritGlobalContext: agent.inheritGlobalContext,
464
+ inheritSkills: agent.inheritSkills,
465
+ sandbox,
466
+ permissionProfile,
491
467
  skills: shared.resolvedSkillNames ?? [],
492
468
  toolPlan,
493
469
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
@@ -501,8 +477,8 @@ async function runSingleAttempt(
501
477
  task: shared.originalTask ?? task,
502
478
  ...(childSessionName ? { sessionName: childSessionName } : {}),
503
479
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
504
- ...(sandbox ? { sandbox } : {}),
505
- ...(permissionProfile ? { permissionProfile } : {}),
480
+ ...(sandbox ? { sandbox } : {}),
481
+ ...(permissionProfile ? { permissionProfile } : {}),
506
482
  launchContractDigest,
507
483
  launchResolvedExtensions,
508
484
  exitCode: 0,
@@ -532,6 +508,10 @@ async function runSingleAttempt(
532
508
  pendingControlEvents.push(event);
533
509
  options.onControlEvent?.(event);
534
510
  };
511
+ let inputUsageComplete = true;
512
+ let outputUsageComplete = true;
513
+ let cacheReadUsageComplete = true;
514
+ let cacheWriteUsageComplete = true;
535
515
 
536
516
  const progress: AgentProgress = {
537
517
  index: options.index ?? 0,
@@ -546,12 +526,20 @@ async function runSingleAttempt(
546
526
  tokens: 0,
547
527
  ...(modelArg ? { model: modelArg } : {}),
548
528
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
549
- inputTokens: 0,
550
- outputTokens: 0,
551
529
  durationMs: 0,
552
530
  lastActivityAt: startTime,
553
531
  };
554
532
  result.progress = progress;
533
+ const projectCompleteUsage = () => {
534
+ if (inputUsageComplete) progress.inputTokens = result.usage.input;
535
+ else delete progress.inputTokens;
536
+ if (outputUsageComplete) progress.outputTokens = result.usage.output;
537
+ else delete progress.outputTokens;
538
+ if (cacheReadUsageComplete) progress.cacheRead = result.usage.cacheRead;
539
+ else delete progress.cacheRead;
540
+ if (cacheWriteUsageComplete) progress.cacheWrite = result.usage.cacheWrite;
541
+ else delete progress.cacheWrite;
542
+ };
555
543
  const attemptTimeout = resolveAttemptTimeout(options);
556
544
  if (attemptTimeout?.remainingMs === 0) {
557
545
  result.exitCode = 1;
@@ -568,7 +556,6 @@ async function runSingleAttempt(
568
556
  return result;
569
557
  }
570
558
  const mutationSnapshot = options.machine ? { source: "tracked-files" as const, trackedOnly: true as const, cwd: options.cwd ?? runtimeCwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(options.cwd ?? runtimeCwd);
571
- let observedMutationAttempt = false;
572
559
  let structuredOutputToolInvoked = false;
573
560
  let structuredOutputMessageStartIndex: number | undefined;
574
561
  let toolAvailabilityError: string | undefined;
@@ -597,6 +584,7 @@ async function runSingleAttempt(
597
584
  const exitCode = await new Promise<number>((resolve) => {
598
585
  const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
599
586
  let session: ChildSession | undefined;
587
+ let messageBaseline: number | undefined;
600
588
  let unsubscribe: (() => void) | undefined;
601
589
  let sessionSettled = false;
602
590
  let lifecycleFinished = false;
@@ -813,11 +801,11 @@ async function runSingleAttempt(
813
801
 
814
802
  let activeLongRunningNotified = false;
815
803
  let pendingToolResult: { tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined;
816
- // Pi host versions may represent one tool result as either a dedicated
817
- // tool_result_end event or a message_end whose message role is toolResult.
818
- // Remember correlated ids so normalizing both forms cannot duplicate output.
819
- const handledToolResultIds = new Set<string>();
820
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
804
+ // Pi host versions may represent one tool result as either a dedicated
805
+ // tool_result_end event or a message_end whose message role is toolResult.
806
+ // Remember correlated ids so normalizing both forms cannot duplicate output.
807
+ const handledToolResultIds = new Set<string>();
808
+ const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
821
809
  type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
822
810
  let activeToolSequence = 0;
823
811
  const activeToolCalls = new Map<string, ActiveToolCall>();
@@ -995,52 +983,61 @@ async function runSingleAttempt(
995
983
  emitUpdateSnapshot(output || "(running...)");
996
984
  };
997
985
 
998
- // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
999
- // deliver the same result either as a tool_result_end event or as a
1000
- // message_end whose message role is toolResult; both funnel through here
1001
- // so one result updates budget, output, and mutating-failure state once.
1002
- const handleToolResult = (message: Message, completion: { toolCallId?: unknown }, now: number): void => {
1003
- const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
1004
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
1005
- if (callId) {
1006
- if (handledToolResultIds.has(callId)) return;
1007
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
1008
- const oldest = handledToolResultIds.values().next().value;
1009
- if (typeof oldest === "string") handledToolResultIds.delete(oldest);
1010
- }
1011
- handledToolResultIds.add(callId);
1012
- }
1013
- result.messages!.push(message);
1014
- const resultText = extractTextFromContent(message.content);
1015
- if (options.toolBudget && pendingToolResult && resultText.includes("Tool budget hard limit reached")) {
1016
- result.toolBudgetBlocked = true;
1017
- result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, pendingToolResult.tool);
1018
- }
1019
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
1020
- const toolSnapshot = pendingToolResult;
1021
- pendingToolResult = undefined;
1022
- if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
1023
- recordMutatingFailure(mutatingFailures, {
1024
- tool: toolSnapshot.tool,
1025
- path: toolSnapshot.path,
1026
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1027
- ts: now,
1028
- }, mutatingFailureWindowMs);
1029
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
1030
- emitNeedsAttention(now, {
1031
- message: `${agent.name} needs attention after repeated mutating tool failures`,
1032
- reason: "tool_failures",
1033
- currentTool: toolSnapshot.tool,
1034
- currentPath: toolSnapshot.path,
1035
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1036
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
1037
- });
1038
- }
1039
- } else if (toolSnapshot?.mutates) {
1040
- resetMutatingFailureState(mutatingFailures);
1041
- }
1042
- fireUpdate();
1043
- };
986
+ // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
987
+ // deliver the same result either as a tool_result_end event or as a
988
+ // message_end whose message role is toolResult; both funnel through here
989
+ // so one result updates budget, output, and mutating-failure state once.
990
+ const handleToolResult = (message: Message, completion: { toolCallId?: unknown; toolName?: unknown }, now: number): void => {
991
+ const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
992
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
993
+ if (callId) {
994
+ if (handledToolResultIds.has(callId)) return;
995
+ if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
996
+ const oldest = handledToolResultIds.values().next().value;
997
+ if (typeof oldest === "string") handledToolResultIds.delete(oldest);
998
+ }
999
+ handledToolResultIds.add(callId);
1000
+ }
1001
+ result.messages!.push(message);
1002
+ const resultText = extractTextFromContent(message.content);
1003
+ // The result event's own tool name is authoritative; the single pending slot can
1004
+ // describe a different, overlapping call and serves only as a fallback.
1005
+ const blockedTool = (typeof completion.toolName === "string" && completion.toolName.length > 0
1006
+ ? completion.toolName
1007
+ : undefined) ?? pendingToolResult?.tool;
1008
+ if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
1009
+ result.toolBudgetBlocked = true;
1010
+ result.toolBudget = toolBudgetState(
1011
+ options.toolBudget,
1012
+ Math.max(progress.toolCount, options.toolBudget.hard + 1),
1013
+ blockedTool,
1014
+ );
1015
+ }
1016
+ appendRecentOutput(progress, resultText.split("\n").slice(-10));
1017
+ const toolSnapshot = pendingToolResult;
1018
+ pendingToolResult = undefined;
1019
+ if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
1020
+ recordMutatingFailure(mutatingFailures, {
1021
+ tool: toolSnapshot.tool,
1022
+ path: toolSnapshot.path,
1023
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1024
+ ts: now,
1025
+ }, mutatingFailureWindowMs);
1026
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
1027
+ emitNeedsAttention(now, {
1028
+ message: `${agent.name} needs attention after repeated mutating tool failures`,
1029
+ reason: "tool_failures",
1030
+ currentTool: toolSnapshot.tool,
1031
+ currentPath: toolSnapshot.path,
1032
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1033
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
1034
+ });
1035
+ }
1036
+ } else if (toolSnapshot?.mutates) {
1037
+ resetMutatingFailureState(mutatingFailures);
1038
+ }
1039
+ fireUpdate();
1040
+ };
1044
1041
 
1045
1042
  const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1046
1043
  if (lifecycleFinished) return;
@@ -1125,7 +1122,6 @@ async function runSingleAttempt(
1125
1122
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
1126
1123
  }
1127
1124
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1128
- observedMutationAttempt = observedMutationAttempt || mutates;
1129
1125
  pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1130
1126
  fireUpdate();
1131
1127
  }
@@ -1145,68 +1141,71 @@ async function runSingleAttempt(
1145
1141
  }
1146
1142
 
1147
1143
  if (evt.type === "message_end" && evt.message) {
1148
- if (evt.message.role === "toolResult") {
1149
- // Fork: hosts that deliver tool results as message_end instead of
1150
- // tool_result_end reach the same deduplicated completion path.
1151
- handleToolResult(evt.message, evt, now);
1152
- } else {
1153
- result.messages!.push(evt.message);
1154
- if (childWatchdog) {
1155
- const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
1156
- if (next) updateChildWatchdogState(next);
1144
+ if (evt.message.role === "toolResult") {
1145
+ // Fork: hosts that deliver tool results as message_end instead of
1146
+ // tool_result_end reach the same deduplicated completion path.
1147
+ handleToolResult(evt.message, evt, now);
1148
+ } else {
1149
+ result.messages!.push(evt.message);
1150
+ if (childWatchdog) {
1151
+ const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
1152
+ if (next) updateChildWatchdogState(next);
1153
+ }
1154
+ if (evt.message.role === "assistant") {
1155
+ result.usage.turns++;
1156
+ progress.turnCount = result.usage.turns;
1157
+ const toolCalls = Array.isArray(evt.message.content)
1158
+ ? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
1159
+ : [];
1160
+ const hasToolCall = toolCalls.length > 0;
1161
+ const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
1162
+ const u = evt.message.usage;
1163
+ inputUsageComplete &&= isCompleteUsageCounter(u?.input);
1164
+ outputUsageComplete &&= isCompleteUsageCounter(u?.output);
1165
+ cacheReadUsageComplete &&= isCompleteUsageCounter(u?.cacheRead);
1166
+ cacheWriteUsageComplete &&= isCompleteUsageCounter(u?.cacheWrite);
1167
+ if (u) {
1168
+ const window = (u.input || 0) + (u.cacheRead || 0);
1169
+ result.usage.input += u.input || 0;
1170
+ result.usage.output += u.output || 0;
1171
+ result.usage.cacheRead += u.cacheRead || 0;
1172
+ result.usage.cacheWrite += u.cacheWrite || 0;
1173
+ result.usage.cost += u.cost?.total || 0;
1174
+ progress.tokens = result.usage.input + result.usage.output;
1175
+ progress.window = window;
1176
+ progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1157
1177
  }
1158
- if (evt.message.role === "assistant") {
1159
- result.usage.turns++;
1160
- progress.turnCount = result.usage.turns;
1161
- const toolCalls = Array.isArray(evt.message.content)
1162
- ? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
1163
- : [];
1164
- const hasToolCall = toolCalls.length > 0;
1165
- const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
1166
- const u = evt.message.usage;
1167
- if (u) {
1168
- const window = (u.input || 0) + (u.cacheRead || 0);
1169
- result.usage.input += u.input || 0;
1170
- result.usage.output += u.output || 0;
1171
- result.usage.cacheRead += u.cacheRead || 0;
1172
- result.usage.cacheWrite += u.cacheWrite || 0;
1173
- result.usage.cost += u.cost?.total || 0;
1174
- progress.tokens = result.usage.input + result.usage.output;
1175
- progress.inputTokens = result.usage.input;
1176
- progress.outputTokens = result.usage.output;
1177
- progress.window = window;
1178
- progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1179
- }
1180
- if (evt.message.model) {
1181
- progress.model = evt.message.model;
1182
- if (!result.model) result.model = evt.message.model;
1183
- if (expectedModelForVerification && !hasToolCall) {
1184
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1185
- if (modelVerificationError && !result.error) result.error = modelVerificationError;
1186
- }
1187
- }
1188
- if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1189
- else if (hasToolCall && evt.message.stopReason === "toolUse") {
1190
- // A recovered request can finish via a terminating tool, without a text stop.
1191
- assistantError = undefined;
1192
- }
1193
- const assistantText = extractTextFromContent(evt.message.content);
1194
- appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1195
- // Final assistant message: start the settle drain window.
1196
- if (terminalAssistantStop) {
1197
- if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1198
- cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1199
- clearAllToolTimeouts();
1200
- activeToolCalls.clear();
1201
- activeToolKeysByName.clear();
1202
- refreshCurrentTool();
1203
- applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1178
+ projectCompleteUsage();
1179
+ if (evt.message.model) {
1180
+ progress.model = evt.message.model;
1181
+ if (!result.model) result.model = evt.message.model;
1182
+ if (expectedModelForVerification && !hasToolCall) {
1183
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1184
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1204
1185
  }
1205
1186
  }
1206
- updateActivityState(now);
1207
- fireUpdate();
1187
+ if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1188
+ else if (hasToolCall && evt.message.stopReason === "toolUse") {
1189
+ // A recovered request can finish via a terminating tool, without a text stop.
1190
+ assistantError = undefined;
1191
+ }
1192
+ const assistantText = extractTextFromContent(evt.message.content);
1193
+ appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1194
+ // Final assistant message: start the settle drain window.
1195
+ if (terminalAssistantStop) {
1196
+ if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1197
+ cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1198
+ clearAllToolTimeouts();
1199
+ activeToolCalls.clear();
1200
+ activeToolKeysByName.clear();
1201
+ refreshCurrentTool();
1202
+ applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1203
+ }
1208
1204
  }
1205
+ updateActivityState(now);
1206
+ fireUpdate();
1209
1207
  }
1208
+ }
1210
1209
 
1211
1210
  if (evt.type === "tool_result_end" && evt.message) {
1212
1211
  const toolResultCompletion = {
@@ -1223,16 +1222,16 @@ async function runSingleAttempt(
1223
1222
  });
1224
1223
  refreshCurrentTool();
1225
1224
  }
1226
- // Fork: the shared, id-deduplicated tail (message push, budget,
1227
- // mutating-failure tracking, output) lives in handleToolResult; hosts
1228
- // may deliver the same result via message_end(role=toolResult).
1229
- handleToolResult(evt.message, evt, now);
1225
+ // Fork: the shared, id-deduplicated tail (message push, budget,
1226
+ // mutating-failure tracking, output) lives in handleToolResult; hosts
1227
+ // may deliver the same result via message_end(role=toolResult).
1228
+ handleToolResult(evt.message, evt, now);
1230
1229
  }
1231
1230
  };
1232
- // SAFETY: this callback is only ever invoked with child-watchdog status events
1233
- // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1234
- // fields `processEvent` needs, and `processEvent` re-validates the shape with
1235
- // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1231
+ // SAFETY: this callback is only ever invoked with child-watchdog status events
1232
+ // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1233
+ // fields `processEvent` needs, and `processEvent` re-validates the shape with
1234
+ // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1236
1235
  onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
1237
1236
 
1238
1237
  fireUpdate();
@@ -1370,6 +1369,12 @@ async function runSingleAttempt(
1370
1369
  }
1371
1370
  const finalCode = forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal ? 0 : closeError || promptError !== undefined ? 1 : 0;
1372
1371
  if (!result.error && closeError) result.error = closeError;
1372
+ if (session && messageBaseline !== undefined) {
1373
+ result.usage = reconcileAttemptUsage(result.usage, session.messages, messageBaseline);
1374
+ progress.tokens = result.usage.input + result.usage.output;
1375
+ projectCompleteUsage();
1376
+ progress.turnCount = result.usage.turns;
1377
+ }
1373
1378
  finish(finalCode);
1374
1379
  };
1375
1380
 
@@ -1453,6 +1458,7 @@ async function runSingleAttempt(
1453
1458
  abortChild();
1454
1459
  }
1455
1460
  options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
1461
+ messageBaseline = created.messages.length;
1456
1462
  await created.prompt(`Task: ${task}`);
1457
1463
  settle(undefined);
1458
1464
  } catch (error) {
@@ -1492,15 +1498,11 @@ async function runSingleAttempt(
1492
1498
  result.exitCode = 1;
1493
1499
  }
1494
1500
  let validatedStructuredOutput = false;
1495
- if (options.structuredOutput && result.exitCode === 0 && !result.error) {
1501
+ if (options.structuredOutput) {
1496
1502
  result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
1497
1503
  result.structuredOutputPath = options.structuredOutput.outputPath;
1498
1504
  const structured = capture.structuredOutput();
1499
- if (!structuredOutputToolInvoked || !structured.called) {
1500
- result.exitCode = 1;
1501
- result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1502
- result.structuredOutputFailed = true;
1503
- } else {
1505
+ if (structuredOutputToolInvoked && structured.called) {
1504
1506
  result.structuredOutput = structured.value;
1505
1507
  const acceptanceMode = options.structuredOutput.acceptanceReportPath
1506
1508
  ? options.structuredOutput.acceptanceReportRequired ? "required" : "optional"
@@ -1512,6 +1514,12 @@ async function runSingleAttempt(
1512
1514
  (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReportError;
1513
1515
  writeStructuredOutputArtifacts(options.structuredOutput, structured.value, acceptanceMode ? structured.acceptanceReport : undefined);
1514
1516
  validatedStructuredOutput = true;
1517
+ } else if (result.exitCode === 0 && !result.error) {
1518
+ result.exitCode = 1;
1519
+ result.error = structuredOutputToolInvoked
1520
+ ? formatStructuredOutputRejectionError(result.messages ?? [])
1521
+ : MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1522
+ result.structuredOutputFailed = true;
1515
1523
  }
1516
1524
  }
1517
1525
  if (result.exitCode === 0 && !result.error) {
@@ -1526,17 +1534,17 @@ async function runSingleAttempt(
1526
1534
  && hasEmptyTerminalAssistantResponse(messages)
1527
1535
  && (progress.toolCount > 0 || Boolean(finalText?.trim()));
1528
1536
  if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1529
- // A startup guard can block the first turn, which leaves no message to
1530
- // inspect. Prefer the reason the blocked child published.
1531
- const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1537
+ // A startup guard can block the first turn, which leaves no message to
1538
+ // inspect. Prefer the reason the blocked child published.
1539
+ const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1532
1540
  result.exitCode = 1;
1533
- if (sandboxDiagnostic) {
1534
- result.error = sandboxDiagnostic.reason;
1535
- result.startupBlocked = true;
1536
- clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1537
- } else {
1538
- result.error = formatEmptyTerminalAssistantResponseError(messages);
1539
- }
1541
+ if (sandboxDiagnostic) {
1542
+ result.error = sandboxDiagnostic.reason;
1543
+ result.startupBlocked = true;
1544
+ clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1545
+ } else {
1546
+ result.error = formatEmptyTerminalAssistantResponseError(messages);
1547
+ }
1540
1548
  } else if (errInfo.hasError) {
1541
1549
  result.exitCode = errInfo.exitCode ?? 1;
1542
1550
  result.error = errInfo.details
@@ -1590,70 +1598,6 @@ async function runSingleAttempt(
1590
1598
  fullOutput = fullOutput.trim()
1591
1599
  ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1592
1600
  : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1593
- }
1594
- const completionGuardEnabled = isAgentContract(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1595
- const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
1596
- ? evaluateCompletionMutationGuard({
1597
- agent: agent.name,
1598
- task: shared.originalTask ?? task,
1599
- messages: result.messages ?? [],
1600
- tools: contractTools,
1601
- mcpDirectTools: toolPlan.effectiveMcpTools,
1602
- mutationTools: agent.mutationTools,
1603
- toolAvailabilityError,
1604
- mutationEvidence,
1605
- })
1606
- : undefined;
1607
- const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
1608
- let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
1609
- // The classifier is deliberately narrow, so a read-only review task can
1610
- // still be misread as implementation. Arbitrate BEFORE any failure side
1611
- // effect is published (effects, exit code, progress, notifications,
1612
- // acceptance, output persistence): only a confident read-only verdict
1613
- // rescues, and the task text alone is evidence — never the child's own
1614
- // final message.
1615
- let arbiterRescued = false;
1616
- if (completionGuardTriggered) {
1617
- const arbitration = await arbitrateCompletionGuardRescue({
1618
- guardTriggered: true,
1619
- task: shared.originalTask ?? task,
1620
- arbiter: options.llmIntentArbiter,
1621
- });
1622
- completionGuardTriggered = arbitration.triggered;
1623
- arbiterRescued = arbitration.rescued;
1624
- }
1625
- const completionEvidence = planCompletionEvidence({
1626
- guard: completionGuard,
1627
- guardTriggered: completionGuardTriggered,
1628
- completionGuardEnabled,
1629
- mutationCapable: hasMutationToolCapability(contractTools, toolPlan.effectiveMcpTools),
1630
- implementationMutationExpected: expectsImplementationMutation(agent.name, shared.originalTask ?? task),
1631
- mutationAttemptObserved,
1632
- mutationEvidence,
1633
- arbiterRescued,
1634
- agentContractEnabled: isAgentContract(options.agentContract),
1635
- });
1636
- if (completionEvidence.fileMutation) {
1637
- result.effects = {
1638
- ...(result.effects ?? {}),
1639
- fileMutation: completionEvidence.fileMutation,
1640
- };
1641
- }
1642
- if (completionEvidence.legacyFailureError) {
1643
- result.exitCode = 1;
1644
- result.error = completionEvidence.legacyFailureError;
1645
- progress.status = "failed";
1646
- progress.error = result.error;
1647
- emitControlEvent(buildControlEvent({
1648
- from: progress.activityState,
1649
- to: "needs_attention",
1650
- runId: options.runId ?? agent.name,
1651
- agent: agent.name,
1652
- index: options.index,
1653
- ts: Date.now(),
1654
- message: `${agent.name} completed without making edits for an implementation task`,
1655
- reason: "completion_guard",
1656
- }));
1657
1601
  }
1658
1602
  if (options.outputPath && result.exitCode === 0) {
1659
1603
  const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
@@ -1953,6 +1897,22 @@ async function runSyncCompletionInner(
1953
1897
  const verifyModel = Boolean(candidate) && !options.modelOverrideFromParent;
1954
1898
  let lastResult: SingleResult | undefined;
1955
1899
  let recoveryPrompt = task;
1900
+ let stagedIndexBaseline: string | undefined;
1901
+ if (effectiveAcceptance.preserveStagedIndex) {
1902
+ try {
1903
+ stagedIndexBaseline = captureStagedIndexBaseline(options.cwd ?? runtimeCwd);
1904
+ } catch (error) {
1905
+ return redactResultPrompt(withRunContext({
1906
+ index: options.index ?? 0,
1907
+ agent: agentName,
1908
+ task,
1909
+ exitCode: 1,
1910
+ messages: [],
1911
+ usage: emptyUsage(),
1912
+ error: error instanceof Error ? error.message : String(error),
1913
+ }, options.context));
1914
+ }
1915
+ }
1956
1916
  for (let attemptIndex = 0; attemptIndex < 2; attemptIndex++) {
1957
1917
  const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1958
1918
  const attemptResult = await runSingleAttempt(runtimeCwd, agent, recoveryPrompt, candidate, attemptOptions, {
@@ -2083,6 +2043,7 @@ async function runSyncCompletionInner(
2083
2043
  ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
2084
2044
  : undefined,
2085
2045
  cwd: options.cwd ?? runtimeCwd,
2046
+ stagedIndexBaseline,
2086
2047
  reportOptional: isAgentContract(options.agentContract),
2087
2048
  artifactsDir: options.artifactsDir,
2088
2049
  runId: options.runId,
@@ -2095,6 +2056,12 @@ async function runSyncCompletionInner(
2095
2056
  }
2096
2057
  const acceptanceFailure = acceptanceFailureMessage(result.acceptance);
2097
2058
  stripAcceptanceReportsFromMessages(result.messages);
2059
+ // A passing typed gate supplies the structured output for runs that have no
2060
+ // outputSchema of their own; preflight rejects the combination.
2061
+ const typedGate = typedVerifyOutput(result.acceptance);
2062
+ if (typedGate && result.structuredOutput === undefined && !acceptanceFailure && result.exitCode === 0) {
2063
+ result.structuredOutput = typedGate.value;
2064
+ }
2098
2065
  if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContract(options.agentContract)) {
2099
2066
  result.exitCode = 1;
2100
2067
  if (result.savedOutputPath) {