@xzzpig/pi-subagents 0.20.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 (140) hide show
  1. package/CHANGELOG.md +154 -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 +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  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 +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -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 +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -6,7 +6,7 @@ import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../
6
6
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
7
7
  import { deliverStopRequest, stopInboxClosedPath } from "../background/control-channel.ts";
8
8
  import { readProcessTerminal } from "../background/process-terminal.ts";
9
- import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
9
+ import { resultFilePath, resultPayloadFileForSessionRun, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
10
10
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
11
11
  import { readStatus } from "../../shared/utils.ts";
12
12
  import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
@@ -29,7 +29,7 @@ function getAsyncStopTarget(
29
29
 
30
30
  const STOP_MESSAGE = "Subagent stopped by user.";
31
31
 
32
- function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefined {
32
+ function sealPausedRun(asyncDir: string, status: AsyncStatus, resultsDir: string): string | undefined {
33
33
  const runnerProcessInstanceId = status.processTerminal?.runnerProcessInstanceId;
34
34
  if (!runnerProcessInstanceId) return "runner process identity is missing";
35
35
  const proof = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId });
@@ -37,15 +37,34 @@ function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefine
37
37
  return `process-terminal proof is ${proof?.state === "unknown" ? `unknown (${proof.reason})` : proof?.state ?? "missing"}`;
38
38
  }
39
39
  if (!status.sessionId) return "session identity is missing";
40
- const existingResultPath = resultPayloadPathForSessionRun(DIRS.results, status.sessionId, status.runId);
41
- if (!existingResultPath) return "paused result is missing";
40
+ // The validated lookup skips unreadable or foreign files; those must be refused below, not replaced.
41
+ const existingResultPath = resultPayloadPathForSessionRun(resultsDir, status.sessionId, status.runId)
42
+ ?? resultPayloadFileForSessionRun(resultsDir, status.sessionId, status.runId);
42
43
  let existingResult: Record<string, unknown>;
43
- try {
44
- const parsed: unknown = JSON.parse(fs.readFileSync(existingResultPath, "utf-8"));
45
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("result is not an object");
46
- existingResult = parsed as Record<string, unknown>;
47
- } catch (error) {
48
- return `paused result is unavailable: ${error instanceof Error ? error.message : String(error)}`;
44
+ if (!existingResultPath) {
45
+ // Delivery deletes the paused result, and an interrupted parent may never have received one; seal from status.
46
+ existingResult = {
47
+ id: status.runId,
48
+ mode: status.mode,
49
+ sessionId: status.sessionId,
50
+ asyncDir,
51
+ ...(status.completionOwnerId ? { completionOwnerId: status.completionOwnerId } : {}),
52
+ ...(status.toolCallId ? { toolCallId: status.toolCallId } : {}),
53
+ results: (status.steps ?? []).map((step) => ({
54
+ agent: step.agent,
55
+ success: step.status === "complete" || step.status === "completed",
56
+ ...(step.error ? { error: step.error } : {}),
57
+ ...(step.exitCode !== undefined ? { exitCode: step.exitCode } : {}),
58
+ })),
59
+ };
60
+ } else {
61
+ try {
62
+ const parsed: unknown = JSON.parse(fs.readFileSync(existingResultPath, "utf-8"));
63
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("result is not an object");
64
+ existingResult = parsed as Record<string, unknown>;
65
+ } catch (error) {
66
+ return `paused result is unavailable: ${error instanceof Error ? error.message : String(error)}`;
67
+ }
49
68
  }
50
69
  const resultRunId = typeof existingResult.runId === "string" ? existingResult.runId : existingResult.id;
51
70
  if (resultRunId !== status.runId || existingResult.sessionId !== status.sessionId) {
@@ -96,11 +115,22 @@ function sealPausedRun(asyncDir: string, status: AsyncStatus): string | undefine
96
115
  steps,
97
116
  };
98
117
  delete stoppedStatus.activityState;
99
- writeAsyncResultFile(resultFilePath(DIRS.results, status.runId), stoppedResult);
118
+ writeAsyncResultFile(resultFilePath(resultsDir, status.runId), stoppedResult);
100
119
  writeAtomicJson(path.join(asyncDir, "status.json"), stoppedStatus);
101
120
  updateActiveRunIndex(asyncDir, "stopped", status.toolCallId, { retryCapacityErrors: true, terminalIndexBeforeRelease: true });
102
121
  }
103
122
 
123
+ /** After ownership/state checks, deliver stop and seal paused whole runs only with native terminal proof. */
124
+ export function deliverAsyncRunStop(
125
+ input: Parameters<typeof deliverStopRequest>[0] & { status: AsyncStatus; resultsDir?: string },
126
+ ): string | undefined {
127
+ const { status, resultsDir = DIRS.results, ...delivery } = input;
128
+ const pausedWholeRun = status.state === "paused" && delivery.childId === undefined && delivery.targetIndex === undefined;
129
+ // A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
130
+ if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(delivery.asyncDir)))) deliverStopRequest(delivery);
131
+ if (pausedWholeRun) return sealPausedRun(delivery.asyncDir, status, resultsDir);
132
+ }
133
+
104
134
  export function stopAsyncRun(
105
135
  state: SubagentState,
106
136
  runId: string | undefined,
@@ -158,17 +188,13 @@ export function stopAsyncRun(
158
188
  }
159
189
  }
160
190
  try {
161
- // A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
162
- if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(target.asyncDir)))) deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
163
- if (pausedWholeRun) {
164
- const failure = sealPausedRun(target.asyncDir, status);
165
- if (failure) {
166
- return {
167
- content: [{ type: "text", text: `Stop request persisted for paused async run ${target.asyncId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.` }],
168
- isError: true,
169
- details: { mode: "management", results: [] },
170
- };
171
- }
191
+ const failure = deliverAsyncRunStop({ asyncDir: target.asyncDir, status, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
192
+ if (failure) {
193
+ return {
194
+ content: [{ type: "text", text: `Stop request persisted for paused async run ${target.asyncId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.` }],
195
+ isError: true,
196
+ details: { mode: "management", results: [] },
197
+ };
172
198
  }
173
199
  const tracked = state.asyncJobs.get(target.asyncId);
174
200
  if (tracked) {
@@ -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;
@@ -1011,8 +1014,9 @@ async function runSingleAttempt(
1011
1014
  const resultText = extractTextFromContent(message.content);
1012
1015
  // The result event's own tool name is authoritative; the single pending slot can
1013
1016
  // describe a different, overlapping call and serves only as a fallback.
1014
- const blockedTool = (typeof completion.toolName === "string" && completion.toolName.length > 0
1015
- ? completion.toolName
1017
+ const resultToolName = completion.toolName ?? (message as { toolName?: unknown }).toolName;
1018
+ const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
1019
+ ? resultToolName
1016
1020
  : undefined) ?? pendingToolResult?.tool;
1017
1021
  if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
1018
1022
  result.toolBudgetBlocked = true;
@@ -1050,6 +1054,7 @@ async function runSingleAttempt(
1050
1054
 
1051
1055
  const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1052
1056
  if (lifecycleFinished) return;
1057
+ partialOutput.observe(evt);
1053
1058
  jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
1054
1059
  shared.transcriptWriter?.writeChildEvent(evt);
1055
1060
  shared.orcaProgressTab?.event(evt);
@@ -1188,32 +1193,33 @@ async function runSingleAttempt(
1188
1193
  progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1189
1194
  }
1190
1195
  projectCompleteUsage();
1191
- if (evt.message.model) {
1192
- progress.model = evt.message.model;
1193
- if (!result.model) result.model = evt.message.model;
1194
- if (expectedModelForVerification && !hasToolCall) {
1195
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases, session?.virtualModelId);
1196
- if (modelVerificationError && !result.error) result.error = modelVerificationError;
1197
- }
1198
- }
1199
- if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1200
- else if (hasToolCall && evt.message.stopReason === "toolUse") {
1201
- // A recovered request can finish via a terminating tool, without a text stop.
1202
- assistantError = undefined;
1203
- }
1204
- const assistantText = extractTextFromContent(evt.message.content);
1205
- appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1206
- // Final assistant message: start the settle drain window.
1207
- if (terminalAssistantStop) {
1208
- if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1209
- cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1210
- clearAllToolTimeouts();
1211
- activeToolCalls.clear();
1212
- activeToolKeysByName.clear();
1213
- refreshCurrentTool();
1214
- 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;
1215
1203
  }
1216
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
+ }
1217
1223
  updateActivityState(now);
1218
1224
  fireUpdate();
1219
1225
  }
@@ -1237,7 +1243,7 @@ async function runSingleAttempt(
1237
1243
  // Fork: the shared, id-deduplicated tail (message push, budget,
1238
1244
  // mutating-failure tracking, output) lives in handleToolResult; hosts
1239
1245
  // may deliver the same result via message_end(role=toolResult).
1240
- handleToolResult(evt.message, evt, now);
1246
+ handleToolResult(evt.message, toolResultCompletion, now);
1241
1247
  }
1242
1248
  };
1243
1249
  // SAFETY: this callback is only ever invoked with child-watchdog status events
@@ -1260,8 +1266,9 @@ async function runSingleAttempt(
1260
1266
 
1261
1267
  if (attemptTimeout) {
1262
1268
  timeoutTimer = setTimeout(() => {
1263
- if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1269
+ if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut) return;
1264
1270
  result.timedOut = true;
1271
+ timeoutCause = attemptTimeout.message;
1265
1272
  clearAllToolTimeouts();
1266
1273
  result.error = attemptTimeout.message;
1267
1274
  result.finalOutput = attemptTimeout.message;
@@ -1310,8 +1317,10 @@ async function runSingleAttempt(
1310
1317
  }
1311
1318
  };
1312
1319
  const terminateForToolTimeout = (message: string): void => {
1313
- if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1320
+ if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut) return;
1321
+ clearTimeout(timeoutTimer);
1314
1322
  result.timedOut = true;
1323
+ timeoutCause = message;
1315
1324
  result.error = message;
1316
1325
  result.finalOutput = message;
1317
1326
  progress.status = "failed";
@@ -1356,13 +1365,15 @@ async function runSingleAttempt(
1356
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 } : {}) };
1357
1366
  let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1358
1367
  const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
1368
+ if (promptError !== undefined) childPromptFailed = true;
1359
1369
  if (!closeError && promptErrorMessage !== undefined) {
1360
1370
  closeError = promptErrorMessage;
1361
1371
  }
1362
- // A foreground child never loads the parent's ambient extensions, so a
1363
- // provider one registers resolves as "not found" before the child starts.
1364
- // Annotate only a creation/prompt failure that produced no turn; keep the
1365
- // 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.
1366
1377
  if (promptErrorMessage !== undefined
1367
1378
  && closeError === promptErrorMessage
1368
1379
  && isChildModelResolutionFailure(promptErrorMessage)
@@ -1370,12 +1381,19 @@ async function runSingleAttempt(
1370
1381
  && result.usage.turns === 0
1371
1382
  && !launch.session.ambientExtensions) {
1372
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 })}`;
1373
1390
  }
1374
1391
  const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1375
1392
  const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
1376
- if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
1377
- 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);
1378
1395
  }
1396
+ if (hostStopReason && !result.interrupted && !result.timedOut) result.stopped = true;
1379
1397
  // A workflow child ended by the workflow's abort signal was stopped, not failed.
1380
1398
  if (options.abortedAsStopped && abortedBySignal && !session?.shutDown && !result.interrupted && !result.timedOut) result.stopped = true;
1381
1399
  if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
@@ -1471,9 +1489,18 @@ async function runSingleAttempt(
1471
1489
  if (abortedBySignal || interruptedByControl || result.timedOut) {
1472
1490
  abortChild();
1473
1491
  }
1474
- 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
+ });
1475
1501
  messageBaseline = created.messages.length;
1476
- 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}`);
1477
1504
  settle(undefined);
1478
1505
  } catch (error) {
1479
1506
  settle(error ?? new Error("Child session failed."));
@@ -1586,11 +1613,23 @@ async function runSingleAttempt(
1586
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);
1587
1614
 
1588
1615
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1616
+ const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1589
1617
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
1590
- 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
+ }
1591
1631
  result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1592
- if (result.timedOut) {
1593
- const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1632
+ if (timeoutCause) {
1594
1633
  let requiredOutputMissing: boolean | undefined;
1595
1634
  if (options.outputMode === "file-only" && options.outputPath) {
1596
1635
  const outputChanged = hasSingleOutputChangedSinceSnapshot(options.outputPath, shared.outputSnapshot);
@@ -1610,11 +1649,12 @@ async function runSingleAttempt(
1610
1649
  artifactPaths: shared.artifactPaths,
1611
1650
  });
1612
1651
  fullOutput = fullOutput.trim()
1613
- ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1614
- : `${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}`;
1615
1654
  }
1616
1655
  if (options.outputPath && result.exitCode === 0) {
1617
- 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);
1618
1658
  fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
1619
1659
  result.savedOutputPath = resolvedOutput.savedPath;
1620
1660
  result.outputSaveError = resolvedOutput.saveError;
@@ -1882,6 +1922,7 @@ async function runSyncCompletionInner(
1882
1922
  metadataPath: artifactPathsResult?.metadataPath,
1883
1923
  enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
1884
1924
  runId: options.runId,
1925
+ parentSessionId: options.parentSessionId,
1885
1926
  agent: agentName,
1886
1927
  task,
1887
1928
  result: target,
@@ -2240,6 +2281,7 @@ export async function runSync(
2240
2281
  metadataPath: failedResult.artifactPaths?.metadataPath,
2241
2282
  enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
2242
2283
  runId: options.runId,
2284
+ parentSessionId: options.parentSessionId,
2243
2285
  agent: failedResult.agent,
2244
2286
  task: failedResult.task,
2245
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 } : {}),