@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -6,8 +6,8 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
6
6
  import * as path from "node:path";
7
7
  import type { Message } from "@earendil-works/pi-ai";
8
8
  import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext, type AgentConfig } from "../../agents/agents.ts";
9
- import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
10
9
  import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.ts";
10
+ import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.ts";
11
11
  import {
12
12
  ensureArtifactsDir,
13
13
  formatOutputArtifactContent,
@@ -20,7 +20,6 @@ import {
20
20
  type AgentProgress,
21
21
  type ArtifactPaths,
22
22
  type ControlEvent,
23
- type ModelAttempt,
24
23
  type RunSyncOptions,
25
24
  type SingleResult,
26
25
  type Usage,
@@ -52,12 +51,10 @@ import {
52
51
  boundStreamedRecentOutput,
53
52
  boundStreamedToolCalls,
54
53
  } from "../../shared/utils.ts";
55
- import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
56
- import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
54
+ import { resolveSkillsWithFallback } from "../../agents/skills.ts";
57
55
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
58
56
  import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
59
57
  import { planCompletionEvidence } from "../shared/completion-evidence.ts";
60
- import { planAbortRecovery } from "../shared/abort-recovery.ts";
61
58
  import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
62
59
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
63
60
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
@@ -72,16 +69,15 @@ import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../sh
72
69
  import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
73
70
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
74
71
  import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
72
+ import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
73
+ import { planAbortRecovery } from "../shared/abort-recovery.ts";
75
74
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
76
- import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
75
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
77
76
  import {
78
- buildModelCandidates,
79
77
  formatSubagentModelVerificationError,
80
- formatModelAttemptNote,
81
78
  isContextOverflow,
82
- isRetryableModelFailureAttempt,
83
- recordRetryableModelFailure,
84
- } from "../shared/model-fallback.ts";
79
+ resolveModelSelection,
80
+ } from "../shared/model-resolution.ts";
85
81
  import {
86
82
  createMutatingFailureState,
87
83
  didMutatingToolFail,
@@ -95,10 +91,10 @@ import {
95
91
  } from "../shared/long-running-guard.ts";
96
92
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
97
93
  import { PROMPT_REDACTED } from "../../shared/utils.ts";
98
- import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
94
+ import { attachContractProjections, isAgentContract } from "../shared/agent-contract.ts";
99
95
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
100
96
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
101
- import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
97
+ import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
102
98
  import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
103
99
  import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
104
100
  import {
@@ -110,8 +106,8 @@ import {
110
106
  type ChildWatchdogStateSnapshot,
111
107
  type ChildWatchdogStatusEvent,
112
108
  } from "../../watchdog/child-status.ts";
113
- import { buildInProcessChildLaunch } from "../shared/child-launch.ts";
114
- import { childSessionFactory, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
109
+ import { buildInProcessChildLaunch, createReportedChildSessionInput } from "../shared/child-launch.ts";
110
+ import { childSessionFactory, childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
115
111
 
116
112
  const artifactOutputByResult = new WeakMap<SingleResult, string>();
117
113
  const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
@@ -159,8 +155,7 @@ function persistSingleResultMetadata(input: {
159
155
  processSignal: target.processSignal,
160
156
  usage: target.usage,
161
157
  model: target.model,
162
- attemptedModels: target.attemptedModels,
163
- modelAttempts: target.modelAttempts,
158
+ requestedModel: target.requestedModel,
164
159
  durationMs: target.progressSummary?.durationMs,
165
160
  toolCount: target.progressSummary?.toolCount,
166
161
  error: target.error,
@@ -261,13 +256,6 @@ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleRe
261
256
  messages: result.outputMode === "file-only" && result.savedOutputPath ? undefined : result.messages ? [...result.messages] : undefined,
262
257
  usage: { ...result.usage },
263
258
  skills: result.skills ? [...result.skills] : undefined,
264
- attemptedModels: result.attemptedModels ? [...result.attemptedModels] : undefined,
265
- modelAttempts: result.modelAttempts
266
- ? result.modelAttempts.map((attempt) => ({
267
- ...attempt,
268
- usage: attempt.usage ? { ...attempt.usage } : undefined,
269
- }))
270
- : undefined,
271
259
  controlEvents: result.controlEvents ? result.controlEvents.map((event) => ({ ...event })) : undefined,
272
260
  progress,
273
261
  progressSummary: result.progressSummary ? { ...result.progressSummary } : undefined,
@@ -340,10 +328,10 @@ function structuredDelegationProgressChanged(
340
328
  return false;
341
329
  }
342
330
 
343
- const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
344
- type AbortRecoverySingleResult = SingleResult & { [AFTER_COMPACTION_SETTLEMENT]?: true };
345
331
 
346
332
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
333
+ const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
334
+ type AbortRecoverySingleResult = SingleResult & { [AFTER_COMPACTION_SETTLEMENT]?: true };
347
335
 
348
336
 
349
337
  async function runSingleAttempt(
@@ -355,8 +343,8 @@ async function runSingleAttempt(
355
343
  shared: {
356
344
  sessionEnabled: boolean;
357
345
  systemPrompt: string;
346
+ acceptancePrompt: string;
358
347
  resolvedSkillNames?: string[];
359
- modelCandidates?: string[];
360
348
  skillsWarning?: string;
361
349
  jsonlPath?: string;
362
350
  artifactPaths?: ArtifactPaths;
@@ -395,6 +383,11 @@ async function runSingleAttempt(
395
383
  : undefined;
396
384
  let onWatchdogStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined;
397
385
  const launch = buildInProcessChildLaunch({
386
+ machine: options.machine,
387
+ remoteSkillNames: options.skills ?? agent.skills,
388
+ remoteReads: options.remoteReads,
389
+ extensionBindings: options.extensionBindings,
390
+ requiredExtensions: options.requiredExtensions,
398
391
  sessionEnabled: shared.sessionEnabled,
399
392
  sessionDir: options.sessionDir,
400
393
  sessionFile: options.sessionFile,
@@ -409,7 +402,8 @@ async function runSingleAttempt(
409
402
  allowNestedSubagents: agent.allowNestedSubagents,
410
403
  extensions: agent.extensions,
411
404
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
412
- systemPrompt: shared.systemPrompt,
405
+ // Exact terminal protocol belongs to session resources, not compactable history.
406
+ systemPrompt: shared.acceptancePrompt ? `${shared.systemPrompt}\n${shared.acceptancePrompt}` : shared.systemPrompt,
413
407
  mcpDirectTools: agent.mcpDirectTools,
414
408
  cwd: options.cwd ?? runtimeCwd,
415
409
  intercomSessionName: options.intercomSessionName,
@@ -424,7 +418,6 @@ async function runSingleAttempt(
424
418
  forkCacheKey: options.context === "fork" ? deriveForkPromptCacheKey(options.parentSessionId) : undefined,
425
419
  structuredOutput: options.structuredOutput,
426
420
  fast: options.fast ?? agent.fast,
427
- modelCandidates: shared.modelCandidates,
428
421
  toolBudget: options.toolBudget,
429
422
  permissionRules,
430
423
  permissionAuditPath,
@@ -433,16 +426,19 @@ async function runSingleAttempt(
433
426
  projectTrusted: options.projectTrusted,
434
427
  trustedProjectCwd: options.trustedProjectCwd,
435
428
  childWatchdog,
436
- watchdogStatus: (event) => onWatchdogStatus?.(event),
429
+ // registerChildWatchdog returns before reading the sink when no watchdog exists.
430
+ watchdogStatus: childWatchdog ? (event) => onWatchdogStatus?.(event) : undefined,
437
431
  waitToolEnabled: options.waitToolEnabled,
438
432
  waitToolDefaultTimeoutMs: options.waitToolDefaultTimeoutMs,
439
433
  capabilityCeiling: options.capabilityCeiling,
440
434
  thinkingCeiling: options.thinkingCeiling,
441
435
  maxSubagentDepth: options.maxSubagentDepth,
442
436
  runtimeSnapshotHost: options.runtimeSnapshotHost,
437
+ hostAvailableBuiltins: options.hostAvailableBuiltins,
443
438
  inherited: options.childRuntime,
444
439
  host: "parent",
445
440
  });
441
+ if (!options.machine && options.parentProviderRegistry) launch.session.parentProviderRegistry = options.parentProviderRegistry;
446
442
  const { toolPlan, capabilityAudit, warnings, launchResolvedExtensions, capture } = launch;
447
443
  if (!shared.launchWarnings.emitted && warnings.length > 0) {
448
444
  for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
@@ -473,21 +469,18 @@ async function runSingleAttempt(
473
469
  error: contractError,
474
470
  usage: emptyUsage(),
475
471
  model: modelArg,
476
- modelAttempts: [],
477
- attemptedModels: [],
478
472
  progressSummary: { status: "failed", toolCount: 0, tokens: 0, durationMs: 0 },
479
473
  ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
480
474
  ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
481
475
  };
482
476
  }
483
- const launchContractDigest = launchBindingDigest({
484
- definitionDigest: agentDefinitionDigest(agent),
477
+ const fast = options.fast ?? agent.fast;
478
+ const { launchContractDigest } = resolveLaunchBinding({
479
+ agent,
485
480
  task: shared.originalTask ?? task,
486
- ...(modelArg ? { model: modelArg } : {}),
487
- modelCandidates: shared.modelCandidates,
488
- ...((options.fast ?? agent.fast) !== undefined ? { fast: options.fast ?? agent.fast } : {}),
481
+ model: modelArg,
482
+ ...(fast !== undefined ? { fast } : {}),
489
483
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
490
- ...(options.thinkingCeiling ? { thinkingCeiling: options.thinkingCeiling } : {}),
491
484
  systemPrompt: effectiveSystemPrompt,
492
485
  systemPromptMode: agent.systemPromptMode,
493
486
  inheritProjectContext: agent.inheritProjectContext,
@@ -496,10 +489,7 @@ async function runSingleAttempt(
496
489
  sandbox,
497
490
  permissionProfile,
498
491
  skills: shared.resolvedSkillNames ?? [],
499
- tools: toolPlan.effectiveToolAllowlist,
500
- ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
501
- extensions: toolPlan.extensionArgs,
502
- mcpDirectTools: toolPlan.effectiveMcpTools,
492
+ toolPlan,
503
493
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
504
494
  outputMode: options.outputMode ?? "inline",
505
495
  ...(options.structuredOutput ? { structuredOutputSchema: options.structuredOutput.schema } : {}),
@@ -577,12 +567,13 @@ async function runSingleAttempt(
577
567
  };
578
568
  return result;
579
569
  }
580
- const mutationSnapshot = snapshotTrackedMutations(options.cwd ?? runtimeCwd);
570
+ 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);
581
571
  let observedMutationAttempt = false;
582
572
  let structuredOutputToolInvoked = false;
583
573
  let structuredOutputMessageStartIndex: number | undefined;
584
574
  let toolAvailabilityError: string | undefined;
585
575
  let abortedBySignal = options.signal?.aborted === true;
576
+ let afterCompactionSettlement = false;
586
577
 
587
578
  if (options.workflowChildPermitLaunch) {
588
579
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
@@ -603,7 +594,6 @@ async function runSingleAttempt(
603
594
  }
604
595
  }
605
596
  const childSessions = options.childSessionFactory ?? childSessionFactory();
606
- let afterCompactionSettlement = false;
607
597
  const exitCode = await new Promise<number>((resolve) => {
608
598
  const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
609
599
  let session: ChildSession | undefined;
@@ -683,6 +673,7 @@ async function runSingleAttempt(
683
673
  let forcedTermination = false;
684
674
  let cleanTerminalAssistantStopReceived = false;
685
675
  let agentSettledReceived = false;
676
+ let queuedDrainHold = false;
686
677
  let compactionStartedReceived = false;
687
678
  let finalDrainTimer: NodeJS.Timeout | undefined;
688
679
  let finalHardFinishTimer: NodeJS.Timeout | undefined;
@@ -709,14 +700,28 @@ async function runSingleAttempt(
709
700
  finalHardFinishTimer = undefined;
710
701
  }
711
702
  };
703
+ const observeQueuedDrainHold = (): boolean => {
704
+ if (childSessionHasQueuedMessages(session)) queuedDrainHold = true;
705
+ return queuedDrainHold;
706
+ };
712
707
  const startFinalDrain = () => {
713
708
  if (childWatchdogIsActive(childWatchdogState)) {
714
709
  armWatchdogTail();
715
710
  return;
716
711
  }
712
+ if (sessionSettled || finalDrainTimer || lifecycleFinished) return;
713
+ if (observeQueuedDrainHold()) return;
714
+ armFinalDrainTimer();
715
+ };
716
+ const armFinalDrainTimer = () => {
717
717
  if (sessionSettled || finalDrainTimer || lifecycleFinished) return;
718
718
  finalDrainTimer = setTimeout(() => {
719
719
  if (lifecycleFinished || sessionSettled) return;
720
+ if (capture.finalDrainHeld() || observeQueuedDrainHold()) {
721
+ finalDrainTimer = undefined;
722
+ armFinalDrainTimer();
723
+ return;
724
+ }
720
725
  forcedTermination = true;
721
726
  if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !assistantError) {
722
727
  result.error = result.error ?? `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
@@ -748,6 +753,8 @@ async function runSingleAttempt(
748
753
  }
749
754
  const applyChildLifecycle = (action: ChildLifecycleAction): void => {
750
755
  if (action === "cancel-drain") {
756
+ cleanTerminalAssistantStopReceived = false;
757
+ agentSettledReceived = false;
751
758
  clearFinalDrainTimers();
752
759
  clearWatchdogTailTimer();
753
760
  return;
@@ -792,7 +799,9 @@ async function runSingleAttempt(
792
799
  // JSONL artifact flush is best effort.
793
800
  });
794
801
  // Report the run only after the child's extensions have shut down.
795
- void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => resolve(code));
802
+ void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => {
803
+ resolve(code);
804
+ });
796
805
  };
797
806
 
798
807
  const drainPendingControlEvents = (): ControlEvent[] | undefined => {
@@ -1043,10 +1052,27 @@ async function runSingleAttempt(
1043
1052
  compactionStartedReceived = false;
1044
1053
  afterCompactionSettlement = false;
1045
1054
  }
1055
+ if (evt.type === "turn_start" || evt.type === "agent_start" || evt.type === "auto_retry_start") {
1056
+ queuedDrainHold = false;
1057
+ }
1046
1058
  if (evt.type === "agent_start" || evt.type === "auto_retry_start") {
1047
1059
  compactionStartedReceived = false;
1048
1060
  afterCompactionSettlement = false;
1049
1061
  }
1062
+ if (evt.type === "agent_start") {
1063
+ const diagnostic = capture.toolDiagnostic();
1064
+ if (diagnostic) {
1065
+ const message = formatChildToolDiagnostic(diagnostic, { host: "parent" });
1066
+ toolAvailabilityError = message;
1067
+ result.error = message;
1068
+ result.finalOutput = message;
1069
+ progress.status = "failed";
1070
+ progress.error = message;
1071
+ fireUpdate();
1072
+ abortChild();
1073
+ return;
1074
+ }
1075
+ }
1050
1076
  const lifecycleAction = projectChildLifecycle(evt, false, childLifecycleState);
1051
1077
  if (evt.type === "agent_settled" && lifecycleAction === "start-drain") {
1052
1078
  agentSettledReceived = true;
@@ -1155,11 +1181,15 @@ async function runSingleAttempt(
1155
1181
  progress.model = evt.message.model;
1156
1182
  if (!result.model) result.model = evt.message.model;
1157
1183
  if (expectedModelForVerification && !hasToolCall) {
1158
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
1184
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1159
1185
  if (modelVerificationError && !result.error) result.error = modelVerificationError;
1160
1186
  }
1161
1187
  }
1162
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
+ }
1163
1193
  const assistantText = extractTextFromContent(evt.message.content);
1164
1194
  appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1165
1195
  // Final assistant message: start the settle drain window.
@@ -1312,9 +1342,23 @@ async function runSingleAttempt(
1312
1342
  const toolDiagnosticError = diagnostic ? formatChildToolDiagnostic(diagnostic, { host: "parent" }) : undefined;
1313
1343
  toolAvailabilityError = toolDiagnosticError;
1314
1344
  result.runtimeAcknowledgedExtensions = capture.runtimeAcknowledgedExtensions();
1345
+ if (session?.machineEvidence) result.nativeMachine = { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) };
1315
1346
  let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1316
- if (!closeError && promptError !== undefined) {
1317
- closeError = promptError instanceof Error ? promptError.message : String(promptError);
1347
+ const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
1348
+ if (!closeError && promptErrorMessage !== undefined) {
1349
+ closeError = promptErrorMessage;
1350
+ }
1351
+ // A foreground child never loads the parent's ambient extensions, so a
1352
+ // provider one registers resolves as "not found" before the child starts.
1353
+ // Annotate only a creation/prompt failure that produced no turn; keep the
1354
+ // core error and add the host rule and both remedies after it.
1355
+ if (promptErrorMessage !== undefined
1356
+ && closeError === promptErrorMessage
1357
+ && isChildModelResolutionFailure(promptErrorMessage)
1358
+ && (result.messages?.length ?? 0) === 0
1359
+ && result.usage.turns === 0
1360
+ && !launch.session.ambientExtensions) {
1361
+ closeError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: agent.name, model: launch.session.model, host: "parent", capabilityCeiling: launch.toolPlan.capabilityCeiling })}`;
1318
1362
  }
1319
1363
  const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1320
1364
  const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
@@ -1386,17 +1430,23 @@ async function runSingleAttempt(
1386
1430
 
1387
1431
  void (async () => {
1388
1432
  try {
1389
- const created = await childSessions.create({
1390
- ...launch.session,
1391
- onExtensionError: (error) => {
1392
- shared.transcriptWriter?.writeStderrLine(`Extension error (${error.extensionPath}, ${error.event}): ${error.error instanceof Error ? error.error.message : String(error.error)}`);
1393
- },
1394
- });
1433
+ const input = createReportedChildSessionInput(launch, shared.transcriptWriter);
1434
+ const created = await childSessions.create(input);
1395
1435
  if (lifecycleFinished) {
1396
1436
  void created.dispose();
1397
1437
  return;
1398
1438
  }
1399
1439
  session = created;
1440
+ const steer = created.steer.bind(created);
1441
+ const followUp = created.followUp.bind(created);
1442
+ created.steer = async (text) => {
1443
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
1444
+ return steer(text);
1445
+ };
1446
+ created.followUp = async (text) => {
1447
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
1448
+ return followUp(text);
1449
+ };
1400
1450
  created.detached = detached;
1401
1451
  unsubscribe = created.subscribe((event) => processEvent(event as Parameters<typeof processEvent>[0]));
1402
1452
  if (abortedBySignal || interruptedByControl || result.timedOut) {
@@ -1510,7 +1560,8 @@ async function runSingleAttempt(
1510
1560
  tokens: progress.tokens,
1511
1561
  durationMs: progress.durationMs,
1512
1562
  };
1513
- const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, options.cwd ?? runtimeCwd);
1563
+ const remoteGitChanged = result.nativeMachine?.initialGit && result.nativeMachine.finalGit ? result.nativeMachine.initialGit.head !== result.nativeMachine.finalGit.head || result.nativeMachine.initialGit.dirty !== result.nativeMachine.finalGit.dirty : undefined;
1564
+ const mutationEvidence = result.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, options.cwd ?? runtimeCwd);
1514
1565
 
1515
1566
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1516
1567
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1540,7 +1591,7 @@ async function runSingleAttempt(
1540
1591
  ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1541
1592
  : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1542
1593
  }
1543
- const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1594
+ const completionGuardEnabled = isAgentContract(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1544
1595
  const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
1545
1596
  ? evaluateCompletionMutationGuard({
1546
1597
  agent: agent.name,
@@ -1580,7 +1631,7 @@ async function runSingleAttempt(
1580
1631
  mutationAttemptObserved,
1581
1632
  mutationEvidence,
1582
1633
  arbiterRescued,
1583
- agentContractV1: isAgentContractV1(options.agentContract),
1634
+ agentContractEnabled: isAgentContract(options.agentContract),
1584
1635
  });
1585
1636
  if (completionEvidence.fileMutation) {
1586
1637
  result.effects = {
@@ -1776,7 +1827,7 @@ async function runSyncCompletionInner(
1776
1827
  dynamicGroup: options.acceptanceContext?.dynamicGroup,
1777
1828
  agentContract: options.agentContract,
1778
1829
  });
1779
- const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract), structuredOutput: Boolean(options.structuredOutput?.acceptanceReportPath) });
1830
+ const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContract(options.agentContract), structuredOutput: Boolean(options.structuredOutput?.acceptanceReportPath) });
1780
1831
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1781
1832
  options.onEffectivePrompt?.(taskWithAcceptance);
1782
1833
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
@@ -1803,21 +1854,10 @@ async function runSyncCompletionInner(
1803
1854
  error: "Skills not found: pi-subagents",
1804
1855
  }, options.context));
1805
1856
  }
1806
- let systemPrompt = agent.systemPrompt?.trim() || "";
1807
- if (resolvedSkills.length > 0) {
1808
- const skillInjection = buildSkillInjection(resolvedSkills);
1809
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${skillInjection}` : skillInjection;
1810
- }
1811
- const memoryInjection = buildAgentMemoryInjection(agent, skillCwd);
1812
- if (memoryInjection) {
1813
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
1814
- }
1815
- systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: skillCwd, agentName });
1816
- systemPrompt = injectOutputPathSystemPrompt(systemPrompt, options.outputPath, agent);
1857
+ const systemPrompt = buildEffectiveSystemPrompt({ agent, resolvedSkills, cwd: skillCwd, ...(options.outputPath ? { outputPath: options.outputPath } : {}) });
1817
1858
 
1818
- const candidates = buildModelCandidates(
1859
+ const { model: selectedModel, requestedModel } = resolveModelSelection(
1819
1860
  options.modelOverride ?? agent.model,
1820
- agent.fallbackModels,
1821
1861
  options.availableModels,
1822
1862
  agent.modelProvider ?? options.preferredModelProvider,
1823
1863
  {
@@ -1826,23 +1866,9 @@ async function runSyncCompletionInner(
1826
1866
  origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1827
1867
  },
1828
1868
  );
1829
- if (options.workflowChildPermitLaunch && candidates.length > 1) {
1830
- const error = "Workflow child permit does not support model fallback.";
1831
- return redactResultPrompt(withRunContext({
1832
- index: options.index ?? 0,
1833
- agent: agent.name,
1834
- task,
1835
- exitCode: 1,
1836
- messages: [],
1837
- usage: emptyUsage(),
1838
- error,
1839
- }, options.context));
1840
- }
1841
1869
  try {
1842
- for (const candidate of candidates) {
1843
- const model = applyThinkingSuffix(candidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
1844
- assertThinkingWithinCeiling({ model, configThinking: options.thinkingOverride ?? agent.thinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
1845
- }
1870
+ const model = applyThinkingSuffix(selectedModel, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
1871
+ assertThinkingWithinCeiling({ model, configThinking: options.thinkingOverride ?? agent.thinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
1846
1872
  } catch (error) {
1847
1873
  return redactResultPrompt(withRunContext({
1848
1874
  index: options.index ?? 0,
@@ -1854,8 +1880,6 @@ async function runSyncCompletionInner(
1854
1880
  error: error instanceof Error ? error.message : String(error),
1855
1881
  }, options.context));
1856
1882
  }
1857
- const attemptedModels: string[] = [];
1858
- const modelAttempts: ModelAttempt[] = [];
1859
1883
  const aggregateUsage = emptyUsage();
1860
1884
  const attemptNotes: string[] = [];
1861
1885
  const launchWarnings = { emitted: false };
@@ -1906,10 +1930,11 @@ async function runSyncCompletionInner(
1906
1930
  });
1907
1931
  };
1908
1932
 
1909
- let intercomDetached = false;
1910
1933
  let detachedReason: string | undefined;
1934
+ const logicalDeadline = options.deadlineAt ?? (options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs);
1911
1935
  const attemptOptions: RunSyncOptions = {
1912
1936
  ...options,
1937
+ deadlineAt: logicalDeadline,
1913
1938
  onDetachReceipt: (receipt) => {
1914
1939
  receipt.acceptance = buildPendingAcceptanceLedger(effectiveAcceptance);
1915
1940
  try {
@@ -1920,108 +1945,65 @@ async function runSyncCompletionInner(
1920
1945
  const accepted = options.onDetachReceipt?.(receipt) === true;
1921
1946
  if (accepted) {
1922
1947
  detachedReason = receipt.detachedReason;
1923
- if (receipt.detachedReason === "intercom coordination") intercomDetached = true;
1924
1948
  }
1925
1949
  return accepted;
1926
1950
  },
1927
1951
  };
1952
+ const candidate = selectedModel;
1953
+ const verifyModel = Boolean(candidate) && !options.modelOverrideFromParent;
1928
1954
  let lastResult: SingleResult | undefined;
1929
- const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1930
- let abortRecoveryAttempted = false;
1931
- let nextAttemptTask = taskWithAcceptance;
1932
- modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1933
- const candidate = modelsToTry[modelIndex];
1934
- // The inner loop re-runs the same candidate at most once, for abort recovery.
1935
- for (;;) {
1936
- const recoveringAbort = abortRecoveryAttempted;
1937
- const attemptTask = nextAttemptTask;
1938
- const verifyModel = Boolean(candidate) && !(options.modelOverrideFromParent && modelIndex === 0);
1939
- const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1940
- const result = await runSingleAttempt(runtimeCwd, agent, attemptTask, candidate, attemptOptions, {
1941
- sessionEnabled,
1942
- systemPrompt,
1943
- resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
1944
- skillsWarning: missingSkills.length > 0 ? `Skills not found: ${missingSkills.join(", ")}` : undefined,
1945
- jsonlPath,
1946
- artifactPaths: artifactPathsResult,
1947
- transcriptWriter,
1948
- attemptNotes,
1949
- modelCandidates: candidates
1950
- .map((modelCandidate) => applyThinkingSuffix(modelCandidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined))
1951
- .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1952
- outputSnapshot,
1953
- originalTask: task,
1954
- orcaProgressTab,
1955
- launchWarnings,
1956
- verifyModel,
1957
- });
1958
- lastResult = result;
1959
- if (!recoveringAbort) {
1960
- if (result.model) attemptedModels.push(result.model);
1961
- else if (candidate) attemptedModels.push(candidate);
1962
- }
1963
- sumUsage(aggregateUsage, result.usage);
1964
- totalToolCount += result.progressSummary?.toolCount ?? 0;
1965
- totalDurationMs += result.progressSummary?.durationMs ?? 0;
1966
- const attemptSucceeded = result.exitCode === 0 && !result.error;
1967
- const attempt: ModelAttempt = {
1968
- model: result.model ?? candidate ?? agent.model ?? "default",
1969
- success: attemptSucceeded,
1970
- exitCode: result.exitCode,
1971
- error: result.error,
1972
- usage: { ...result.usage },
1973
- };
1974
- modelAttempts.push(attempt);
1975
- if (!attemptSucceeded) {
1976
- const afterCompactionSettlement = (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT];
1977
- const abortRecovery = planAbortRecovery({
1978
- messages: result.messages ?? [],
1979
- error: result.error,
1980
- processSignal: result.processSignal,
1981
- sessionAvailable: Boolean(options.sessionFile && existsSync(options.sessionFile)),
1982
- alreadyResumed: abortRecoveryAttempted,
1983
- stopped: result.stopped || result.detached || options.signal?.aborted,
1984
- interrupted: result.interrupted || intercomDetached || options.interruptSignal?.aborted,
1985
- timedOut: result.timedOut,
1986
- toolBudgetExhausted: result.toolBudgetBlocked,
1987
- usageBudgetExhausted: false,
1988
- structuredOutputFailed: result.structuredOutputFailed,
1989
- acceptanceFailed: false,
1990
- currentTool: result.progress?.currentTool,
1991
- afterCompactionSettlement,
1992
- });
1993
- if (abortRecovery.action === "resume") {
1994
- abortRecoveryAttempted = true;
1995
- nextAttemptTask = abortRecovery.prompt;
1996
- attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1997
- continue;
1998
- }
1999
- if (abortRecovery.diagnostic) {
2000
- result.error = result.error ? `${result.error}\n${abortRecovery.diagnostic}` : abortRecovery.diagnostic;
2001
- attempt.error = result.error;
2002
- break modelAttemptsLoop;
2003
- }
2004
- }
2005
- if (recoveringAbort && !attemptSucceeded) break modelAttemptsLoop;
2006
- if (options.workflowChildPermitLaunch && !attemptSucceeded) break modelAttemptsLoop;
2007
- // Preserve the legacy intercom handoff contract: once this logical run has
2008
- // been handed to a supervisor, terminating that attempt must not launch a
2009
- // model fallback. Explicit user detach retains fallback.
2010
- if (intercomDetached || result.timedOut) break modelAttemptsLoop;
2011
- if (attemptSucceeded) break modelAttemptsLoop;
2012
-
2013
- const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount, ...(result.startupBlocked ? { startupBlocked: true } : {}) });
2014
- if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
2015
- if (isContextOverflow(result.error)) {
2016
- result.contextOverflow = true;
2017
- attemptNotes.push(`[fallback] ${attempt.model} failed: context overflow — the input exceeds this model's context window. Reduce the task input or use a model with a larger context window.`);
2018
- break modelAttemptsLoop;
2019
- }
2020
- if (!retryableModelFailure || modelIndex === modelsToTry.length - 1) break modelAttemptsLoop;
2021
- attemptNotes.push(formatModelAttemptNote(attempt, modelsToTry[modelIndex + 1]));
2022
- break;
1955
+ let recoveryPrompt = task;
1956
+ for (let attemptIndex = 0; attemptIndex < 2; attemptIndex++) {
1957
+ const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1958
+ const attemptResult = await runSingleAttempt(runtimeCwd, agent, recoveryPrompt, candidate, attemptOptions, {
1959
+ sessionEnabled,
1960
+ systemPrompt,
1961
+ acceptancePrompt,
1962
+ resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
1963
+ skillsWarning: missingSkills.length > 0 ? `Skills not found: ${missingSkills.join(", ")}` : undefined,
1964
+ jsonlPath,
1965
+ artifactPaths: artifactPathsResult,
1966
+ transcriptWriter,
1967
+ attemptNotes,
1968
+ outputSnapshot,
1969
+ originalTask: task,
1970
+ orcaProgressTab,
1971
+ launchWarnings,
1972
+ verifyModel,
1973
+ });
1974
+ lastResult = attemptResult;
1975
+ sumUsage(aggregateUsage, attemptResult.usage);
1976
+ totalToolCount += attemptResult.progressSummary?.toolCount ?? 0;
1977
+ totalDurationMs += attemptResult.progressSummary?.durationMs ?? 0;
1978
+ if (attemptResult.exitCode === 0 && !attemptResult.error) break;
1979
+ const recovery = planAbortRecovery({
1980
+ messages: attemptResult.messages ?? [],
1981
+ error: attemptResult.error,
1982
+ processSignal: attemptResult.processSignal,
1983
+ sessionAvailable: Boolean(options.sessionFile && existsSync(options.sessionFile)),
1984
+ alreadyResumed: attemptIndex > 0,
1985
+ stopped: attemptResult.stopped || attemptResult.detached || Boolean(detachedReason) || Boolean(options.workflowChildPermitLaunch) || options.signal?.aborted,
1986
+ interrupted: attemptResult.interrupted || options.interruptSignal?.aborted,
1987
+ timedOut: attemptResult.timedOut,
1988
+ toolBudgetExhausted: attemptResult.toolBudgetBlocked,
1989
+ usageBudgetExhausted: false,
1990
+ structuredOutputFailed: attemptResult.structuredOutputFailed,
1991
+ acceptanceFailed: false,
1992
+ currentTool: attemptResult.progress?.currentTool,
1993
+ afterCompactionSettlement: (attemptResult as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT],
1994
+ });
1995
+ if (recovery.action === "resume") {
1996
+ recoveryPrompt = recovery.prompt;
1997
+ attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
1998
+ continue;
1999
+ }
2000
+ if (recovery.diagnostic) {
2001
+ attemptResult.error = attemptResult.error ? `${attemptResult.error}\n${recovery.diagnostic}` : recovery.diagnostic;
2023
2002
  }
2003
+ break;
2024
2004
  }
2005
+ if (!lastResult) throw new Error("Subagent did not produce a result.");
2006
+ if (isContextOverflow(lastResult.error)) lastResult.contextOverflow = true;
2025
2007
 
2026
2008
  const result = withRunContext(lastResult ?? {
2027
2009
  index: options.index ?? 0,
@@ -2035,8 +2017,7 @@ async function runSyncCompletionInner(
2035
2017
  result.task = task;
2036
2018
 
2037
2019
  result.usage = aggregateUsage;
2038
- result.attemptedModels = attemptedModels.length > 0 ? attemptedModels : undefined;
2039
- result.modelAttempts = modelAttempts.length > 0 ? modelAttempts : undefined;
2020
+ result.requestedModel = requestedModel;
2040
2021
  result.progressSummary = {
2041
2022
  ...(childSessionName ? { sessionName: childSessionName } : {}),
2042
2023
  toolCount: totalToolCount,
@@ -2102,7 +2083,7 @@ async function runSyncCompletionInner(
2102
2083
  ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
2103
2084
  : undefined,
2104
2085
  cwd: options.cwd ?? runtimeCwd,
2105
- reportOptional: isAgentContractV1(options.agentContract),
2086
+ reportOptional: isAgentContract(options.agentContract),
2106
2087
  artifactsDir: options.artifactsDir,
2107
2088
  runId: options.runId,
2108
2089
  watchdog: result.watchdog,
@@ -2114,7 +2095,7 @@ async function runSyncCompletionInner(
2114
2095
  }
2115
2096
  const acceptanceFailure = acceptanceFailureMessage(result.acceptance);
2116
2097
  stripAcceptanceReportsFromMessages(result.messages);
2117
- if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContractV1(options.agentContract)) {
2098
+ if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContract(options.agentContract)) {
2118
2099
  result.exitCode = 1;
2119
2100
  if (result.savedOutputPath) {
2120
2101
  result.finalOutput = finalizeSingleOutput({
@@ -2126,7 +2107,6 @@ async function runSyncCompletionInner(
2126
2107
  savedPath: result.savedOutputPath,
2127
2108
  outputReference: result.outputReference,
2128
2109
  }).displayOutput;
2129
- artifactOutputByResult.set(result, result.finalOutput);
2130
2110
  }
2131
2111
  result.error = result.error ? `${result.error}\n${acceptanceFailure}` : acceptanceFailure;
2132
2112
  if (artifactPathsResult && options.artifactConfig?.enabled !== false && options.artifactConfig?.includeOutput !== false) {
@@ -2147,7 +2127,7 @@ async function runSyncCompletionInner(
2147
2127
  result.progress.error = result.error;
2148
2128
  }
2149
2129
  }
2150
- if (isAgentContractV1(options.agentContract)) attachContractProjections(result);
2130
+ if (isAgentContract(options.agentContract)) attachContractProjections(result);
2151
2131
  redactResultPrompt(result);
2152
2132
  try {
2153
2133
  persistResultMetadata(result);
@@ -2192,7 +2172,7 @@ export async function runSync(
2192
2172
  ): Promise<SingleResult> {
2193
2173
  // Capture the strict contract before consumer-owned objects can be mutated
2194
2174
  // after a detached receipt is published.
2195
- const strictContract = isAgentContractV1(options.agentContract);
2175
+ const strictContract = isAgentContract(options.agentContract);
2196
2176
  let detachedReason: string | undefined;
2197
2177
  let publishedReceipt: SingleResult | undefined;
2198
2178
  let activeDetachAttempt: ((reason?: string) => boolean) | undefined;
@@ -2290,13 +2270,13 @@ export async function runSync(
2290
2270
  });
2291
2271
 
2292
2272
  let terminalCallbackInvoked = false;
2293
- void authoritativeCompletion.then((terminalResult) => {
2273
+ void authoritativeCompletion.then(async (terminalResult) => {
2294
2274
  if (!detachedReason || terminalCallbackInvoked) return;
2295
2275
  terminalCallbackInvoked = true;
2296
2276
  terminalResult.detached = undefined;
2297
2277
  terminalResult.detachedReason = detachedReason;
2298
2278
  try {
2299
- options.onDetachedExit?.(terminalResult);
2279
+ await options.onDetachedExit?.(terminalResult);
2300
2280
  } catch {
2301
2281
  // The authoritative result has settled. Consumer callback failures are
2302
2282
  // contained here; each consumer owns cleanup through its own finally block.