@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -52,6 +52,7 @@ import {
52
52
  boundStreamedToolCalls,
53
53
  } from "../../shared/utils.ts";
54
54
  import { resolveSkillsWithFallback } from "../../agents/skills.ts";
55
+ import { createPartialOutputTracker, formatPartialOutput, type PartialOutputCause } from "../shared/partial-output.ts";
55
56
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
56
57
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
57
58
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
@@ -61,12 +62,12 @@ import { resolvePermissionRules } from "../shared/permissions.ts";
61
62
  import { applyThinkingSuffix, deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
62
63
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
63
64
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
64
- import { resolveEffectiveThinking } from "../../shared/model-info.ts";
65
+ import { qualifyModelWithProvider, resolveEffectiveThinking } from "../../shared/model-info.ts";
65
66
  import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
66
67
  import { formatStructuredOutputRejectionError, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
67
68
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
68
69
  import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
69
- import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
70
+ import { formatChildModelResolutionDiagnostic, formatInheritedProviderDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
70
71
  import { planAbortRecovery } from "../shared/abort-recovery.ts";
71
72
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
72
73
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
@@ -139,6 +140,7 @@ function persistSingleResultMetadata(input: {
139
140
  metadataPath?: string;
140
141
  enabled: boolean;
141
142
  runId?: string;
143
+ parentSessionId?: string;
142
144
  agent: string;
143
145
  task: string;
144
146
  result: SingleResult;
@@ -147,6 +149,7 @@ function persistSingleResultMetadata(input: {
147
149
  const target = input.result;
148
150
  writeMetadata(input.metadataPath, {
149
151
  runId: input.runId,
152
+ parentSessionId: input.parentSessionId,
150
153
  agent: input.agent,
151
154
  task: PROMPT_REDACTED,
152
155
  exitCode: target.exitCode,
@@ -176,17 +179,13 @@ function persistSingleResultMetadata(input: {
176
179
  });
177
180
  }
178
181
 
179
- function formatTimeoutMessage(timeoutMs: number): string {
180
- return `Subagent timed out after ${timeoutMs}ms.`;
181
- }
182
-
183
182
  function resolveAttemptTimeout(options: RunSyncOptions): { timeoutMs: number; remainingMs: number; message: string } | undefined {
184
183
  if (options.timeoutMs === undefined) return undefined;
185
184
  const deadlineAt = options.deadlineAt ?? Date.now() + options.timeoutMs;
186
185
  return {
187
186
  timeoutMs: options.timeoutMs,
188
187
  remainingMs: Math.max(0, deadlineAt - Date.now()),
189
- message: formatTimeoutMessage(options.timeoutMs),
188
+ message: `Subagent timed out after ${options.timeoutMs}ms.`,
190
189
  };
191
190
  }
192
191
 
@@ -271,8 +270,7 @@ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleRe
271
270
  * foreground detach receipts and terminal consumers use snapshotResult directly.
272
271
  */
273
272
  function snapshotStreamResult(result: SingleResult, progress: AgentProgress): SingleResult {
274
- const snapshot = snapshotResult(result, progress);
275
- snapshot.messages = undefined;
273
+ const snapshot = snapshotResult({ ...result, messages: undefined }, progress);
276
274
  snapshot.toolCalls = boundStreamedToolCalls(result);
277
275
  return snapshot;
278
276
  }
@@ -420,6 +418,7 @@ async function runSingleAttempt(
420
418
  nestedRoute: options.nestedRoute,
421
419
  runFanoutBudget: options.runFanoutBudget,
422
420
  parentSessionId: options.parentSessionId,
421
+ parentSessionFile: options.parentSessionFile,
423
422
  forkCacheKey: options.context === "fork" ? deriveForkPromptCacheKey(options.parentSessionId) : undefined,
424
423
  structuredOutput: options.structuredOutput,
425
424
  fast: options.fast ?? agent.fast,
@@ -541,6 +540,7 @@ async function runSingleAttempt(
541
540
  else delete progress.cacheWrite;
542
541
  };
543
542
  const attemptTimeout = resolveAttemptTimeout(options);
543
+ let timeoutCause: string | undefined;
544
544
  if (attemptTimeout?.remainingMs === 0) {
545
545
  result.exitCode = 1;
546
546
  result.timedOut = true;
@@ -581,6 +581,8 @@ async function runSingleAttempt(
581
581
  }
582
582
  }
583
583
  const childSessions = options.childSessionFactory ?? childSessionFactory();
584
+ const partialOutput = createPartialOutputTracker();
585
+ let childPromptFailed = false;
584
586
  const exitCode = await new Promise<number>((resolve) => {
585
587
  const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
586
588
  let session: ChildSession | undefined;
@@ -589,6 +591,7 @@ async function runSingleAttempt(
589
591
  let sessionSettled = false;
590
592
  let lifecycleFinished = false;
591
593
  let detached = false;
594
+ let hostStopReason: string | undefined;
592
595
  let intercomStarted = false;
593
596
  let assistantError: string | undefined;
594
597
  let removeAbortListener: (() => void) | undefined;
@@ -787,7 +790,13 @@ async function runSingleAttempt(
787
790
  // JSONL artifact flush is best effort.
788
791
  });
789
792
  // Report the run only after the child's extensions have shut down.
790
- void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => {
793
+ void Promise.resolve().then(async () => {
794
+ if (code === 0 && !result.interrupted && !result.timedOut && !result.stopped && !abortedBySignal) {
795
+ try { await session?.finishCommands?.(); }
796
+ catch (error) { result.error = error instanceof Error ? error.message : String(error); code = 1; }
797
+ }
798
+ await session?.dispose();
799
+ }).catch(() => undefined).then(() => {
791
800
  resolve(code);
792
801
  });
793
802
  };
@@ -806,7 +815,7 @@ async function runSingleAttempt(
806
815
  // Remember correlated ids so normalizing both forms cannot duplicate output.
807
816
  const handledToolResultIds = new Set<string>();
808
817
  const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
809
- type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
818
+ type ActiveToolCall = { attentionEmitted?: boolean; key: string; tool: string; args: string; startedAt: number; path?: string };
810
819
  let activeToolSequence = 0;
811
820
  const activeToolCalls = new Map<string, ActiveToolCall>();
812
821
  const activeToolKeysByName = new Map<string, string[]>();
@@ -862,12 +871,12 @@ async function runSingleAttempt(
862
871
  return key ? removeActiveToolCallKey(key) : undefined;
863
872
  };
864
873
  const openToolAttentionTarget = (now: number): ActiveToolCall | undefined => [...activeToolCalls.values()]
865
- .filter((active) => shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
874
+ .filter((active) => !active.attentionEmitted && shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
866
875
  .sort((left, right) => left.startedAt - right.startedAt)[0];
867
876
  const mutatingFailures = createMutatingFailureState();
868
877
  const mutatingFailureWindowMs = 5 * 60_000;
869
878
  const currentToolDurationMs = (now: number) => progress.currentToolStartedAt ? Math.max(0, now - progress.currentToolStartedAt) : undefined;
870
- const emitNeedsAttention = (now: number, input: { message?: string; reason?: ControlEvent["reason"]; recentFailureSummary?: string; currentTool?: string; currentPath?: string; currentToolDurationMs?: number } = {}): boolean => {
879
+ const emitNeedsAttention = (now: number, input: { message?: string; reason?: ControlEvent["reason"]; recentFailureSummary?: string; currentTool?: string; toolCallId?: string; currentPath?: string; currentToolDurationMs?: number } = {}): boolean => {
871
880
  if (!controlConfig.enabled) return false;
872
881
  const previous = progress.activityState;
873
882
  progress.activityState = "needs_attention";
@@ -886,13 +895,14 @@ async function runSingleAttempt(
886
895
  tokens: progress.tokens,
887
896
  toolCount: progress.toolCount,
888
897
  currentTool: input.currentTool ?? progress.currentTool,
898
+ toolCallId: input.toolCallId,
889
899
  currentToolDurationMs: input.currentToolDurationMs ?? currentToolDurationMs(now),
890
900
  currentPath: input.currentPath ?? progress.currentPath,
891
901
  recentFailureSummary: input.recentFailureSummary,
892
902
  taskPreview: task,
893
903
  });
894
904
  emitControlEvent(event);
895
- return previous !== "needs_attention";
905
+ return previous !== "needs_attention" || input.reason === "tool_open_threshold";
896
906
  };
897
907
  const emitActiveLongRunning = (now: number, reason: ControlEvent["reason"]): boolean => {
898
908
  if (!controlConfig.enabled || activeLongRunningNotified || progress.activityState === "needs_attention") return false;
@@ -934,13 +944,15 @@ async function runSingleAttempt(
934
944
  if (idleState === "needs_attention") {
935
945
  return progress.activityState === "needs_attention" ? false : emitNeedsAttention(now);
936
946
  }
937
- const toolAttentionTarget = progress.activityState !== "needs_attention" ? openToolAttentionTarget(now) : undefined;
947
+ const toolAttentionTarget = openToolAttentionTarget(now);
938
948
  if (toolAttentionTarget) {
949
+ toolAttentionTarget.attentionEmitted = true;
939
950
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
940
951
  return emitNeedsAttention(now, {
941
952
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1000)}s`,
942
953
  reason: "tool_open_threshold",
943
954
  currentTool: toolAttentionTarget.tool,
955
+ toolCallId: toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : undefined,
944
956
  currentPath: toolAttentionTarget.path,
945
957
  currentToolDurationMs: durationMs,
946
958
  });
@@ -1002,8 +1014,9 @@ async function runSingleAttempt(
1002
1014
  const resultText = extractTextFromContent(message.content);
1003
1015
  // The result event's own tool name is authoritative; the single pending slot can
1004
1016
  // 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
1017
+ const resultToolName = completion.toolName ?? (message as { toolName?: unknown }).toolName;
1018
+ const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
1019
+ ? resultToolName
1007
1020
  : undefined) ?? pendingToolResult?.tool;
1008
1021
  if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
1009
1022
  result.toolBudgetBlocked = true;
@@ -1041,6 +1054,7 @@ async function runSingleAttempt(
1041
1054
 
1042
1055
  const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1043
1056
  if (lifecycleFinished) return;
1057
+ partialOutput.observe(evt);
1044
1058
  jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
1045
1059
  shared.transcriptWriter?.writeChildEvent(evt);
1046
1060
  shared.orcaProgressTab?.event(evt);
@@ -1179,32 +1193,33 @@ async function runSingleAttempt(
1179
1193
  progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1180
1194
  }
1181
1195
  projectCompleteUsage();
1182
- if (evt.message.model) {
1183
- progress.model = evt.message.model;
1184
- if (!result.model) result.model = evt.message.model;
1185
- if (expectedModelForVerification && !hasToolCall) {
1186
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1187
- if (modelVerificationError && !result.error) result.error = modelVerificationError;
1188
- }
1189
- }
1190
- if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1191
- else if (hasToolCall && evt.message.stopReason === "toolUse") {
1192
- // A recovered request can finish via a terminating tool, without a text stop.
1193
- assistantError = undefined;
1194
- }
1195
- const assistantText = extractTextFromContent(evt.message.content);
1196
- appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1197
- // Final assistant message: start the settle drain window.
1198
- if (terminalAssistantStop) {
1199
- if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1200
- cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1201
- clearAllToolTimeouts();
1202
- activeToolCalls.clear();
1203
- activeToolKeysByName.clear();
1204
- refreshCurrentTool();
1205
- applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1196
+ if (evt.message.model) {
1197
+ const observedModel = qualifyModelWithProvider(evt.message.model, evt.message.provider, options.availableModels);
1198
+ progress.model = observedModel;
1199
+ if (!result.model) result.model = observedModel;
1200
+ if (expectedModelForVerification && !hasToolCall) {
1201
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases, session?.virtualModelId);
1202
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1206
1203
  }
1207
1204
  }
1205
+ if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1206
+ else if (hasToolCall && evt.message.stopReason === "toolUse") {
1207
+ // A recovered request can finish via a terminating tool, without a text stop.
1208
+ assistantError = undefined;
1209
+ }
1210
+ const assistantText = extractTextFromContent(evt.message.content);
1211
+ appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1212
+ // Final assistant message: start the settle drain window.
1213
+ if (terminalAssistantStop) {
1214
+ if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1215
+ cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1216
+ clearAllToolTimeouts();
1217
+ activeToolCalls.clear();
1218
+ activeToolKeysByName.clear();
1219
+ refreshCurrentTool();
1220
+ applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1221
+ }
1222
+ }
1208
1223
  updateActivityState(now);
1209
1224
  fireUpdate();
1210
1225
  }
@@ -1228,7 +1243,7 @@ async function runSingleAttempt(
1228
1243
  // Fork: the shared, id-deduplicated tail (message push, budget,
1229
1244
  // mutating-failure tracking, output) lives in handleToolResult; hosts
1230
1245
  // may deliver the same result via message_end(role=toolResult).
1231
- handleToolResult(evt.message, evt, now);
1246
+ handleToolResult(evt.message, toolResultCompletion, now);
1232
1247
  }
1233
1248
  };
1234
1249
  // SAFETY: this callback is only ever invoked with child-watchdog status events
@@ -1251,8 +1266,9 @@ async function runSingleAttempt(
1251
1266
 
1252
1267
  if (attemptTimeout) {
1253
1268
  timeoutTimer = setTimeout(() => {
1254
- if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1269
+ if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut) return;
1255
1270
  result.timedOut = true;
1271
+ timeoutCause = attemptTimeout.message;
1256
1272
  clearAllToolTimeouts();
1257
1273
  result.error = attemptTimeout.message;
1258
1274
  result.finalOutput = attemptTimeout.message;
@@ -1301,8 +1317,10 @@ async function runSingleAttempt(
1301
1317
  }
1302
1318
  };
1303
1319
  const terminateForToolTimeout = (message: string): void => {
1304
- if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1320
+ if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut) return;
1321
+ clearTimeout(timeoutTimer);
1305
1322
  result.timedOut = true;
1323
+ timeoutCause = message;
1306
1324
  result.error = message;
1307
1325
  result.finalOutput = message;
1308
1326
  progress.status = "failed";
@@ -1347,13 +1365,15 @@ async function runSingleAttempt(
1347
1365
  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 } : {}) };
1348
1366
  let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1349
1367
  const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
1368
+ if (promptError !== undefined) childPromptFailed = true;
1350
1369
  if (!closeError && promptErrorMessage !== undefined) {
1351
1370
  closeError = promptErrorMessage;
1352
1371
  }
1353
- // A foreground child never loads the parent's ambient extensions, so a
1354
- // provider one registers resolves as "not found" before the child starts.
1355
- // Annotate only a creation/prompt failure that produced no turn; keep the
1356
- // core error and add the host rule and both remedies after it.
1372
+ // A foreground child never loads the parent's ambient extensions. A model
1373
+ // whose provider the parent registry does not serve resolves as "not found"
1374
+ // before the child starts; a provider it does serve is inherited without its
1375
+ // extension's session hooks and can fail the first request. Keep the
1376
+ // original error first and add the host rule and remedies after it.
1357
1377
  if (promptErrorMessage !== undefined
1358
1378
  && closeError === promptErrorMessage
1359
1379
  && isChildModelResolutionFailure(promptErrorMessage)
@@ -1361,12 +1381,19 @@ async function runSingleAttempt(
1361
1381
  && result.usage.turns === 0
1362
1382
  && !launch.session.ambientExtensions) {
1363
1383
  closeError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: agent.name, model: launch.session.model, host: "parent", capabilityCeiling: launch.toolPlan.capabilityCeiling })}`;
1384
+ } else if (session?.inheritedProvider
1385
+ && closeError !== undefined
1386
+ && (closeError === promptErrorMessage || closeError === assistantError)
1387
+ && progress.toolCount === 0
1388
+ && (result.messages ?? []).every((message) => message.role !== "assistant" || (message as { stopReason?: string }).stopReason === "error")) {
1389
+ closeError = `${closeError}\n\n${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.model, provider: session.inheritedProvider, capabilityCeiling: launch.toolPlan.capabilityCeiling })}`;
1364
1390
  }
1365
1391
  const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1366
1392
  const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
1367
- if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
1368
- closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
1393
+ if (!closeError && (abortedBySignal || session?.shutDown || hostStopReason) && !result.interrupted && !result.timedOut) {
1394
+ closeError = hostStopReason ?? (session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR);
1369
1395
  }
1396
+ if (hostStopReason && !result.interrupted && !result.timedOut) result.stopped = true;
1370
1397
  // A workflow child ended by the workflow's abort signal was stopped, not failed.
1371
1398
  if (options.abortedAsStopped && abortedBySignal && !session?.shutDown && !result.interrupted && !result.timedOut) result.stopped = true;
1372
1399
  if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
@@ -1462,9 +1489,18 @@ async function runSingleAttempt(
1462
1489
  if (abortedBySignal || interruptedByControl || result.timedOut) {
1463
1490
  abortChild();
1464
1491
  }
1465
- options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
1492
+ options.onChildSession?.({
1493
+ steer: (text) => created.steer(text),
1494
+ followUp: (text) => created.followUp(text),
1495
+ stop: (reason) => {
1496
+ if (sessionSettled || lifecycleFinished) return;
1497
+ hostStopReason = reason;
1498
+ abortChild();
1499
+ },
1500
+ });
1466
1501
  messageBaseline = created.messages.length;
1467
- await created.prompt(`Task: ${task}`);
1502
+ // A runtime replacement can stop a child that detached while it was still being created.
1503
+ if (!hostStopReason) await created.prompt(`Task: ${task}`);
1468
1504
  settle(undefined);
1469
1505
  } catch (error) {
1470
1506
  settle(error ?? new Error("Child session failed."));
@@ -1577,11 +1613,23 @@ async function runSingleAttempt(
1577
1613
  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);
1578
1614
 
1579
1615
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1616
+ const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1580
1617
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
1581
- if (!fullOutput.trim() && result.structuredOutput !== undefined) fullOutput = JSON.stringify(result.structuredOutput, null, 2);
1618
+ if (!fullOutput.trim() && structuredText !== undefined) fullOutput = structuredText;
1619
+ // Text still streaming when the child timed out or its session threw never reached
1620
+ // a completed message. Keep it, labeled; the run still fails and the text never
1621
+ // stands in for acceptance or a requested output file.
1622
+ const partialCause: PartialOutputCause | undefined = result.timedOut
1623
+ ? "timeout"
1624
+ : childPromptFailed && !abortedBySignal && !result.interrupted && !result.stopped ? "child error" : undefined;
1625
+ const streamedPartial = partialCause ? partialOutput.text() : undefined;
1626
+ if (partialCause && streamedPartial) {
1627
+ const text = stripAcceptanceReport(streamedPartial);
1628
+ fullOutput = partialCause === "timeout" ? text : formatPartialOutput(text, partialCause);
1629
+ result.outputPartial = true;
1630
+ }
1582
1631
  result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1583
- if (result.timedOut) {
1584
- const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1632
+ if (timeoutCause) {
1585
1633
  let requiredOutputMissing: boolean | undefined;
1586
1634
  if (options.outputMode === "file-only" && options.outputPath) {
1587
1635
  const outputChanged = hasSingleOutputChangedSinceSnapshot(options.outputPath, shared.outputSnapshot);
@@ -1601,11 +1649,12 @@ async function runSingleAttempt(
1601
1649
  artifactPaths: shared.artifactPaths,
1602
1650
  });
1603
1651
  fullOutput = fullOutput.trim()
1604
- ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1605
- : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1652
+ ? `${timeoutCause}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1653
+ : `${timeoutCause}\n\n${result.timeoutRecovery.message}`;
1606
1654
  }
1607
1655
  if (options.outputPath && result.exitCode === 0) {
1608
- const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
1656
+ // The schema is the caller's contract: a bound output file holds the structured result, not closing prose.
1657
+ const resolvedOutput = resolveSingleOutput(options.outputPath, structuredText ?? fullOutput, shared.outputSnapshot, options.outputClaimPath);
1609
1658
  fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
1610
1659
  result.savedOutputPath = resolvedOutput.savedPath;
1611
1660
  result.outputSaveError = resolvedOutput.saveError;
@@ -1873,6 +1922,7 @@ async function runSyncCompletionInner(
1873
1922
  metadataPath: artifactPathsResult?.metadataPath,
1874
1923
  enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
1875
1924
  runId: options.runId,
1925
+ parentSessionId: options.parentSessionId,
1876
1926
  agent: agentName,
1877
1927
  task,
1878
1928
  result: target,
@@ -2231,6 +2281,7 @@ export async function runSync(
2231
2281
  metadataPath: failedResult.artifactPaths?.metadataPath,
2232
2282
  enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
2233
2283
  runId: options.runId,
2284
+ parentSessionId: options.parentSessionId,
2234
2285
  agent: failedResult.agent,
2235
2286
  task: failedResult.task,
2236
2287
  result: failedResult,
@@ -48,6 +48,7 @@ function compactChild(child: ForegroundResumeChild): ForegroundResumeChild {
48
48
  ...(child.error ? { error: child.error } : {}),
49
49
  ...(!outputPath && child.finalOutput ? { finalOutput: boundedTail(child.finalOutput) } : {}),
50
50
  ...(child.outputState ? { outputState: child.outputState } : {}),
51
+ ...(child.outputPartial ? { outputPartial: true } : {}),
51
52
  ...(child.outputMode ? { outputMode: child.outputMode } : {}),
52
53
  ...(child.savedOutputPath ? { savedOutputPath: child.savedOutputPath } : {}),
53
54
  ...(child.outputSaveError ? { outputSaveError: child.outputSaveError } : {}),