@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  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 +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -0,0 +1,76 @@
1
+ export interface ChildModelResolutionDiagnostic {
2
+ agent?: string;
3
+ model?: string;
4
+ host?: "parent" | "runner";
5
+ /** The launch's resolved capability ceiling, when one is active. */
6
+ capabilityCeiling?: { denyExtensions: boolean; sources?: readonly string[] };
7
+ }
8
+
9
+ /**
10
+ * Pi core's model-resolution failure text. `resolveCliModel` reports an
11
+ * unknown provider or model and cannot know which extension would have
12
+ * registered it, so these two shapes are the ones that mean "the child's
13
+ * model registry was missing a provider", not "the provider is unhealthy".
14
+ */
15
+ const MODEL_RESOLUTION_FAILURE_PATTERNS = [
16
+ /^Model .+ not found\b/i,
17
+ /^Unknown provider "/i,
18
+ ];
19
+
20
+ /** True for a core model-resolution failure, which a missing extension can explain. */
21
+ export function isChildModelResolutionFailure(error: string | undefined): boolean {
22
+ const text = typeof error === "string" ? error.trim() : "";
23
+ return MODEL_RESOLUTION_FAILURE_PATTERNS.some((pattern) => pattern.test(text));
24
+ }
25
+
26
+ /**
27
+ * A `capabilityCeiling.denyExtensions` launch loads no extension at all:
28
+ * ambient, listed, and MCP provider extensions are all suppressed, so neither
29
+ * `async: true` nor a frontmatter list can register the provider. Saying only
30
+ * the ambient-extension rule would direct the operator at remedies the ceiling
31
+ * discards.
32
+ */
33
+ function capabilityCeilingDeniesExtensions(diagnostic: ChildModelResolutionDiagnostic): boolean {
34
+ return diagnostic.capabilityCeiling?.denyExtensions === true;
35
+ }
36
+
37
+ function denyExtensionsClause(diagnostic: ChildModelResolutionDiagnostic): string {
38
+ const sources = diagnostic.capabilityCeiling?.sources ?? [];
39
+ return `Capability ceiling from ${sources.length > 0 ? sources.join(", ") : "an unnamed source"} denies extensions`;
40
+ }
41
+
42
+ /**
43
+ * Explain a child model that did not resolve because the extension serving its
44
+ * provider never loaded: a foreground child never loads the parent's ambient
45
+ * extensions, an explicit `extensions` list keeps a background child from
46
+ * loading them, and a capability ceiling denies extensions to both. The caller
47
+ * keeps the core error intact and appends this explanation, so a genuinely
48
+ * unknown model id still reads as one.
49
+ */
50
+ export function formatChildModelResolutionDiagnostic(diagnostic: ChildModelResolutionDiagnostic): string {
51
+ const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
52
+ const model = diagnostic.model ? `'${diagnostic.model}'` : "this model";
53
+ if (capabilityCeilingDeniesExtensions(diagnostic)) {
54
+ return (diagnostic.host === "parent"
55
+ ? [
56
+ `${subject} ran as a foreground child, which never loads the parent's ambient extensions.`,
57
+ `${denyExtensionsClause(diagnostic)}, so if ${model} is served by a provider extension, that extension cannot load for this child: \`async: true\` does not help either, and listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed.`,
58
+ "Relax the capability ceiling to allow extensions, or use a model that the parent's model registry already resolves.",
59
+ ]
60
+ : [
61
+ `${subject} ran as a background child without the ambient extensions.`,
62
+ `${denyExtensionsClause(diagnostic)}, so if ${model} is served by a provider extension, that extension cannot load for this child: listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed, and leaving \`extensions\` unset does not enable ambient loading.`,
63
+ "Relax the capability ceiling to allow extensions, or use a model that the child's model registry already resolves.",
64
+ ]).join("\n");
65
+ }
66
+ if (diagnostic.host === "parent") {
67
+ return [
68
+ `${subject} ran as a foreground child, which never loads the parent's ambient extensions but inherits the providers they registered.`,
69
+ `If ${model} is served by a provider extension, check the parent's \`/model\` list and the child extension diagnostics, or load the extension for this child with \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter.`,
70
+ ].join("\n");
71
+ }
72
+ return [
73
+ `${subject} ran as a background child without the ambient extensions.`,
74
+ `If ${model} is served by a provider extension, that extension is not loaded for this child: list it in \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter, or leave \`extensions\` unset so the child loads the ambient extensions.`,
75
+ ].join("\n");
76
+ }
@@ -1,26 +1,26 @@
1
- import { splitKnownThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
- import type { Usage } from "../../shared/types.ts";
3
- import { filterFallbackCandidates, findModelExclusion, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
1
+ import { splitKnownThinkingSuffix as splitThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
4
2
  import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
5
- import { redactSecretValues } from "./permissions.ts";
6
3
 
7
4
  export type { AvailableModelInfo };
8
5
 
9
- interface ModelAttemptSummary {
10
- model: string;
11
- success: boolean;
12
- exitCode?: number | null;
13
- error?: string;
14
- usage?: Usage;
6
+ export interface ModelSelectionEvidence {
7
+ model?: string;
8
+ requestedModel?: string;
15
9
  }
16
10
 
17
- export function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
18
- return splitKnownThinkingSuffix(model);
19
- }
11
+ export { splitThinkingSuffix };
20
12
 
21
- export function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined): string | undefined {
13
+ /** Aliases apply only to the resolved launch candidate (without its thinking suffix) and the exact raw response ID. */
14
+ export function formatSubagentModelVerificationError(
15
+ expectedModel: string,
16
+ observedModel: string,
17
+ availableModels: AvailableModelInfo[] | undefined,
18
+ modelResponseAliases?: Record<string, string[]>,
19
+ ): string | undefined {
22
20
  if (!availableModels || availableModels.length === 0) return undefined;
23
21
  const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
22
+ if (modelResponseAliases && Object.hasOwn(modelResponseAliases, expectedBase)
23
+ && modelResponseAliases[expectedBase]?.includes(observedModel)) return undefined;
24
24
  const observedBase = splitThinkingSuffix(observedModel).baseModel;
25
25
  if (expectedBase === observedBase) return undefined;
26
26
  const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
@@ -30,7 +30,7 @@ export function formatSubagentModelVerificationError(expectedModel: string, obse
30
30
  const expectedFullIdLeaf = expectedEntry.fullId.slice(expectedEntry.fullId.lastIndexOf("/") + 1);
31
31
  if (expectedIdLeaf === observedBase || expectedFullIdLeaf === observedBase) return undefined;
32
32
  }
33
- return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
33
+ return `model_verification_failed: native Pi child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'. If you have independently verified this response ID identifies the requested model, declare the exact mapping in modelResponseAliases in ~/.pi/agent/extensions/subagent/config.json (see docs/configuration.md#modelresponsealiases). Use the resolved provider/model ID without its thinking suffix as the key. This leaves the outgoing request unchanged. Configuration changes affect new independent native runs; resumed native runs retain their launch-time declaration. External CLI adapters do not use this setting.`;
34
34
  }
35
35
 
36
36
  /** Sentinel model value requesting that a subagent inherit the parent session's model. */
@@ -284,39 +284,6 @@ function enforceModelScopes(
284
284
  for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
285
285
  }
286
286
 
287
- const MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH = 240;
288
- const MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES = 20;
289
-
290
- function sanitizeModelExclusionDiagnostic(value: string | undefined, fallback: string): string {
291
- const normalized = typeof value === "string"
292
- ? value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").trim()
293
- : "";
294
- return redactSecretValues(normalized || fallback).slice(0, MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH);
295
- }
296
-
297
- function formatModelExclusionExpiry(expiresAt: number): string {
298
- if (!Number.isFinite(expiresAt)) return "unknown";
299
- const date = new Date(expiresAt);
300
- return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString();
301
- }
302
-
303
- function formatExcludedCandidateEvidence(candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>): string {
304
- const { provider, modelId } = parseModelKey(candidate);
305
- const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
306
- const displayModel = sanitizeModelExclusionDiagnostic(modelId, "unknown");
307
- const displayProvider = sanitizeModelExclusionDiagnostic(provider ?? exclusion.provider, "unspecified");
308
- const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
309
- return `${displayCandidate} — model: ${displayModel}; provider: ${displayProvider}; reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}`;
310
- }
311
-
312
- function throwForExplicitModelExclusion(model: string): void {
313
- const exclusion = findModelExclusion(model);
314
- if (!exclusion) return;
315
- const reason = redactSecretValues((exclusion.reason ?? "runtime-failure").replace(/[\u0000-\u001f\u007f]+/g, " ")).slice(0, 240);
316
- const expiry = Number.isFinite(exclusion.expiresAt) ? `; expires: ${new Date(exclusion.expiresAt).toISOString()}` : "";
317
- throw new Error(`Requested subagent model '${model}' is excluded and cannot be replaced by a fallback (reason: ${reason}${expiry}).`);
318
- }
319
-
320
287
  /**
321
288
  * Resolve the `--model` override passed to a spawned subagent.
322
289
  *
@@ -353,7 +320,6 @@ export function resolveSubagentModelOverride(
353
320
  const candidate = resolveSubagentModelCandidate(explicit, availableModels, preferredProvider);
354
321
  if (options?.source === "explicit") {
355
322
  resolved = candidate ?? resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
356
- throwForExplicitModelExclusion(resolved);
357
323
  resolvedFromRegistry = true;
358
324
  } else if (candidate) {
359
325
  resolved = candidate;
@@ -397,19 +363,15 @@ export function resolveEffectiveSubagentModel(
397
363
 
398
364
  export type ModelOrigin = ModelSource | "configured";
399
365
 
400
- export interface BuildModelCandidatesOptions {
401
- /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
366
+ export interface ResolveModelSelectionOptions {
402
367
  scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
403
368
  onWarn?: (violation: ModelScopeViolation) => void;
404
369
  /** The primary model came from the running parent session, not configuration. */
405
370
  primaryModelFromParent?: boolean;
406
- /** How the primary model was selected. Explicit stays strict and does not rotate to fallbacks. */
371
+ /** How the model was selected. */
407
372
  origin?: ModelOrigin;
408
373
  }
409
374
 
410
- const ZERO_USABLE_MODEL_CANDIDATES_ERROR =
411
- "No usable subagent models remain after registry, scope, and cached-exclusion filtering.";
412
-
413
375
  export function resolveModelOrigin(input: {
414
376
  explicitModel?: string | boolean;
415
377
  agentModel?: string | boolean;
@@ -434,169 +396,30 @@ export function inheritsParentModel(
434
396
  return Boolean(parentModel && (!trimmed || trimmed === INHERIT_MODEL));
435
397
  }
436
398
 
437
- export function buildModelCandidates(
438
- primaryModel: string | undefined,
439
- fallbackModels: string[] | undefined,
399
+ export function resolveModelSelection(
400
+ model: string | undefined,
440
401
  availableModels: AvailableModelInfo[] | undefined,
441
402
  preferredProvider?: string,
442
- options?: BuildModelCandidatesOptions,
443
- ): string[] {
444
- if (!primaryModel) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
403
+ options?: ResolveModelSelectionOptions,
404
+ ): ModelSelectionEvidence {
405
+ if (!model) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
445
406
  const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
407
+ const requestedModel = origin === "inherited" ? undefined : model;
446
408
  const scopes = configuredScopes(options?.scope);
447
- type ExcludedCandidate = { candidate: string; exclusion: NonNullable<ReturnType<typeof findModelExclusion>> };
448
- const excludedCandidates: ExcludedCandidate[] = [];
449
- let excludedCandidateCount = 0;
450
- const warnCachedExclusion = (candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>) => {
451
- excludedCandidateCount++;
452
- if (excludedCandidates.length < MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES) excludedCandidates.push({ candidate, exclusion });
453
- const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
454
- const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
455
- console.warn(`[pi-subagents] Skipping model '${displayCandidate}' due to a cached exclusion (reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}).`);
456
- };
457
- if (origin === "explicit" && primaryModel) {
458
- const normalized = resolveRequiredSubagentModelCandidate(primaryModel.trim(), availableModels, preferredProvider);
459
- throwForExplicitModelExclusion(normalized);
409
+ if (origin === "explicit" && model) {
410
+ const normalized = resolveRequiredSubagentModelCandidate(model.trim(), availableModels, preferredProvider);
460
411
  enforceModelScopes(normalized, scopes, "explicit", options?.onWarn);
461
- primaryModel = normalized;
462
- }
463
- const seen = new Set<string>();
464
- const candidates: string[] = [];
465
- const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
466
- let skippedPrimary: string | undefined;
467
- let skippedFallback: string | undefined;
468
- for (let index = 0; index < rawCandidates.length; index++) {
469
- const raw = rawCandidates[index];
470
- if (!raw) continue;
471
- const model = raw.trim();
472
- const normalized = index === 0 && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
473
- ? model
474
- : resolveSubagentModelCandidate(model, availableModels, preferredProvider);
475
- if (!normalized) {
476
- if (index === 0) skippedPrimary = model;
477
- else {
478
- skippedFallback ??= model;
479
- console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
480
- }
481
- continue;
482
- }
483
- if (seen.has(normalized)) continue;
484
- if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
485
- enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
486
- }
487
- seen.add(normalized);
488
- candidates.push(normalized);
412
+ model = normalized;
489
413
  }
490
- const resolved = filterFallbackCandidates(candidates, { onExcluded: warnCachedExclusion });
491
- if (resolved.length === 0) {
492
- if (skippedPrimary) resolveRequiredSubagentModelCandidate(skippedPrimary, availableModels, preferredProvider);
493
- if (candidates.length === 0 && skippedFallback) resolveRequiredSubagentModelCandidate(skippedFallback, availableModels, preferredProvider);
494
- if (candidates.length > 0) {
495
- const shownExclusions = excludedCandidates;
496
- const omittedExclusions = excludedCandidateCount - shownExclusions.length;
497
- const evidence = shownExclusions.length > 0
498
- ? ` (excluded: ${shownExclusions.map(({ candidate, exclusion }) => formatExcludedCandidateEvidence(candidate, exclusion)).join("; ")}${omittedExclusions > 0 ? `; ... and ${omittedExclusions} more` : ""})`
499
- : "";
500
- throw new Error(`${ZERO_USABLE_MODEL_CANDIDATES_ERROR}${evidence}`);
501
- }
502
- return resolved;
414
+ const resolved = model && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
415
+ ? model.trim()
416
+ : model ? resolveRequiredSubagentModelCandidate(model.trim(), availableModels, preferredProvider) : undefined;
417
+ if (resolved && scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
418
+ enforceModelScopes(resolved, scopes, "inherited", options?.onWarn);
503
419
  }
504
- if (skippedPrimary) {
505
- console.warn(`[pi-subagents] Skipping primary model '${skippedPrimary}' because it is unavailable in this environment.`);
506
- }
507
- return resolved;
420
+ return { ...(resolved ? { model: resolved } : {}), ...(requestedModel ? { requestedModel } : {}) };
508
421
  }
509
-
510
- const RETRYABLE_MODEL_FAILURE_PATTERNS = [
511
- /rate\s*limit/i,
512
- /usage\s*limit/i,
513
- /too many requests/i,
514
- /\b429\b/,
515
- /quota/i,
516
- /billing/i,
517
- /credit/i,
518
- /auth(?:entication)?/i,
519
- /unauthori[sz]ed/i,
520
- /forbidden/i,
521
- /api key/i,
522
- /token expired/i,
523
- /invalid key/i,
524
- /provider.*unavailable/i,
525
- /model.*unavailable/i,
526
- /model.*disabled/i,
527
- /model.*not found/i,
528
- /unknown model/i,
529
- /overloaded/i,
530
- /service unavailable/i,
531
- /temporar(?:ily)? unavailable/i,
532
- /connection\s+(?:error|reset|closed|aborted)/i,
533
- /connection refused/i,
534
- /fetch failed/i,
535
- /network error/i,
536
- /socket hang up/i,
537
- /stream ended without finish_reason/i,
538
- /upstream/i,
539
- /timed? out/i,
540
- /timeout/i,
541
- /\b500\b/,
542
- /\b502\b/,
543
- /\b503\b/,
544
- /\b504\b/,
545
- /internal server error/i,
546
- /cold.?start/i,
547
- /empty response/i,
548
- /no output/i,
549
- /model.*(?:load|fail|error)/i,
550
- ];
551
-
552
- /**
553
- * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with
554
- * exit code N` come from a tool call inside the child's task, not from the
555
- * provider/model, however network-flavored their details read. Retrying a
556
- * different model cannot fix them and would rerun the whole task. Tool names
557
- * include namespaced forms like `mcp.server/write`.
558
- */
559
- const TOOL_FAILURE_PREFIX = /^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i;
560
-
561
- export function isRetryableModelFailure(error: string | undefined): boolean {
562
- if (!error) return false;
563
- if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
564
- return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
565
- }
566
-
567
- function messageError(message: unknown): string | undefined {
568
- if (!message || typeof message !== "object") return undefined;
569
- const value = (message as { errorMessage?: unknown }).errorMessage;
570
- return typeof value === "string" ? value : undefined;
571
- }
572
-
573
- export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number; startupBlocked?: boolean }): boolean {
574
- // A startup guard blocked the child before its first model turn: no model
575
- // change can fix it, and recording it as a model failure would poison the
576
- // model registry with a long-lived exclusion for a policy decision.
577
- if (input.startupBlocked === true) return false;
578
- if (!isRetryableModelFailure(input.error)) return false;
579
- if ((input.toolCount ?? 0) > 0) return false;
580
- if (input.error === "Subagent produced no output (possible model cold-start or empty response)." || /^Subagent produced no output after terminal assistant stopReason "[^"]+"\.$/.test(input.error ?? "")) return true;
581
- if ((input.toolCount ?? 0) === 0 && (input.messages?.length ?? 0) === 0) return true;
582
- const error = input.error?.trim();
583
- return Boolean(error && input.messages?.some((message) => messageError(message)?.trim() === error));
584
- }
585
-
586
- export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
587
- if (!model || !isRetryableModelFailure(error)) return;
588
- const { provider, modelId } = parseModelKey(model);
589
- recordModelFailure({ modelId, reason: error, ...(provider ? { provider } : {}) });
590
- }
591
-
592
- /**
593
- * Context-overflow signals. These are deliberately NOT part of
594
- * {@link RETRYABLE_MODEL_FAILURE_PATTERNS}: an overflow means the input was too
595
- * large for the model's context window, so retrying the same input on another
596
- * model (or the same model again) cannot succeed. Callers should treat overflow
597
- * as a terminal, non-retryable failure and surface a clear "input too large"
598
- * error instead of burning fallback attempts on a guaranteed failure.
599
- */
422
+ /** Context-overflow signals used to surface a clear input-too-large error. */
600
423
  const CONTEXT_OVERFLOW_PATTERNS = [
601
424
  /context(?: length| window| limit)? (?:exceed|overflow|too long)/i,
602
425
  /maximum context length/i,
@@ -613,13 +436,6 @@ const CONTEXT_OVERFLOW_PATTERNS = [
613
436
 
614
437
  export function isContextOverflow(error: string | undefined): boolean {
615
438
  if (!error) return false;
616
- if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
439
+ if (/^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i.test(error.trim())) return false;
617
440
  return CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(error));
618
441
  }
619
-
620
- export function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {
621
- const failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;
622
- return nextModel
623
- ? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`
624
- : `[fallback] ${attempt.model} failed: ${failure}.`;
625
- }
@@ -17,7 +17,7 @@ import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
17
17
 
18
18
  export interface ModelScopeRule {
19
19
  enforce?: boolean;
20
- /** Reject inherited and fallback models outside the allowlist instead of warning. */
20
+ /** Reject inherited models outside the allowlist instead of warning. */
21
21
  strict?: boolean;
22
22
  /** Glob-style allow patterns (only `*` is special), matched against `provider/id`. */
23
23
  allow?: string[];
@@ -6,8 +6,8 @@ import {
6
6
  TEMP_ROOT_DIR,
7
7
  type AsyncJobState,
8
8
  type AsyncStatus,
9
- type LaunchResolvedChildExtensionsV1,
10
- type RuntimeAcknowledgedChildExtensionsV1,
9
+ type LaunchResolvedChildExtensions,
10
+ type RuntimeAcknowledgedChildExtensions,
11
11
  type NestedRouteInfo,
12
12
  type TurnBudgetState,
13
13
  type NestedRunSummary,
@@ -20,8 +20,8 @@ import { isSafeNestedPathId, sanitizeNestedPath, type NestedPathEntry } from "./
20
20
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
21
21
  import { sanitizeProcessTerminal } from "../background/process-terminal.ts";
22
22
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
23
- import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
24
- import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
23
+ import { validateSandboxProfileNameOptional } from "../../shared/sandbox-profile.ts";
24
+ import { validatePermissionProfileNameOptional } from "../../shared/permission-profile.ts";
25
25
 
26
26
  export const NESTED_EVENTS_DIR = path.join(TEMP_ROOT_DIR, "nested-subagent-events");
27
27
  const ROUTE_FILE = "route.json";
@@ -229,7 +229,7 @@ function sanitizeCost(value: unknown): NestedRunSummary["totalCost"] | undefined
229
229
  : undefined;
230
230
  }
231
231
 
232
- function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildExtensionsV1 | undefined {
232
+ function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildExtensions | undefined {
233
233
  if (!value || typeof value !== "object") return undefined;
234
234
  const raw = value as Record<string, unknown>;
235
235
  if (raw.version !== 1 || raw.source !== "launch-resolved" || typeof raw.disableAmbientExtensions !== "boolean") return undefined;
@@ -244,16 +244,18 @@ function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildEx
244
244
  disableAmbientExtensions: raw.disableAmbientExtensions,
245
245
  runtime: stringList(raw.runtime),
246
246
  configured: stringList(raw.configured),
247
+ required: Array.isArray(raw.required) ? raw.required.filter((item): item is string => typeof item === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item)).slice(0, 32) : [],
247
248
  effective: stringList(raw.effective),
248
249
  omitted: {
249
250
  runtime: omittedCount("runtime"),
250
251
  configured: omittedCount("configured"),
252
+ required: omittedCount("required"),
251
253
  effective: omittedCount("effective"),
252
254
  },
253
255
  };
254
256
  }
255
257
 
256
- function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensionsV1 | undefined {
258
+ function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensions | undefined {
257
259
  if (!value || typeof value !== "object") return undefined;
258
260
  const raw = value as Record<string, unknown>;
259
261
  if (raw.version !== 1 || raw.source !== "child-runtime" || !Array.isArray(raw.ids)) return undefined;
@@ -273,7 +275,7 @@ function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowled
273
275
  };
274
276
  }
275
277
 
276
- function runtimeAcknowledgedEntry(value: unknown): { runtimeAcknowledgedExtensions: RuntimeAcknowledgedChildExtensionsV1 } | Record<string, never> {
278
+ function runtimeAcknowledgedEntry(value: unknown): { runtimeAcknowledgedExtensions: RuntimeAcknowledgedChildExtensions } | Record<string, never> {
277
279
  const sanitized = sanitizeRuntimeAcknowledgedExtensions(value);
278
280
  return sanitized ? { runtimeAcknowledgedExtensions: sanitized } : {};
279
281
  }
@@ -298,39 +300,23 @@ function sanitizeTurnBudget(value: unknown): TurnBudgetState | undefined {
298
300
  }
299
301
 
300
302
  function sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState {
301
- return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "partial" || value === "paused" || value === "stopped"
303
+ return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "partial" || value === "paused" || value === "stopped" || value === "rejected"
302
304
  ? value
303
305
  : fallback;
304
306
  }
305
307
 
306
- function sandboxProfileValue(value: unknown): string | undefined {
307
- try {
308
- return validateSandboxProfileName(value);
309
- } catch {
310
- return undefined;
311
- }
312
- }
313
-
314
- function permissionProfileValue(value: unknown): string | undefined {
315
- try {
316
- return validatePermissionProfileName(value);
317
- } catch {
318
- return undefined;
319
- }
320
- }
321
-
322
308
  function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefined {
323
309
  if (!input || typeof input !== "object") return undefined;
324
310
  const raw = input as Record<string, unknown>;
325
311
  const agent = stringValue(raw.agent, 128);
326
312
  if (!agent) return undefined;
327
- const status = raw.status === "pending" || raw.status === "running" || raw.status === "complete" || raw.status === "completed" || raw.status === "failed" || raw.status === "paused" || raw.status === "stopped"
313
+ const status = raw.status === "pending" || raw.status === "running" || raw.status === "complete" || raw.status === "completed" || raw.status === "failed" || raw.status === "partial" || raw.status === "paused" || raw.status === "stopped" || raw.status === "rejected"
328
314
  ? raw.status
329
315
  : "pending";
330
316
  const model = stringValue(raw.model);
331
317
  const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
332
- const sandbox = sandboxProfileValue(raw.sandbox);
333
- const permissionProfile = permissionProfileValue(raw.permissionProfile);
318
+ const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
319
+ const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
334
320
  return {
335
321
  agent,
336
322
  status,
@@ -371,8 +357,8 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
371
357
  : undefined;
372
358
  const totalTokens = sanitizeTokenUsage(raw.totalTokens);
373
359
  const totalCost = sanitizeCost(raw.totalCost);
374
- const sandbox = sandboxProfileValue(raw.sandbox);
375
- const permissionProfile = permissionProfileValue(raw.permissionProfile);
360
+ const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
361
+ const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
376
362
  return {
377
363
  id: raw.id,
378
364
  parentRunId: raw.parentRunId,
@@ -475,7 +461,7 @@ export function parseNestedEventRecords(content: string, route: NestedRoute): Ne
475
461
  }
476
462
 
477
463
  function terminal(state: NestedRunState): boolean {
478
- return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped";
464
+ return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "rejected" || state === "stopped";
479
465
  }
480
466
 
481
467
  function mergeBoundedChildren(existing: NestedRunSummary[] | undefined, incoming: NestedRunSummary[] | undefined): NestedRunSummary[] | undefined {
@@ -1023,7 +1009,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
1023
1009
  }
1024
1010
 
1025
1011
  export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: string, fallback: { id: string; parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }>; mode?: SubagentRunMode; ts: number }): NestedRunSummary {
1026
- const sandbox = sandboxProfileValue(status.sandbox);
1012
+ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1027
1013
  return {
1028
1014
  id: status.runId || fallback.id,
1029
1015
  parentRunId: fallback.parentRunId,
@@ -1068,7 +1054,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1068
1054
  ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
1069
1055
  ...(status.steps?.length ? {
1070
1056
  steps: status.steps.map((step, index) => {
1071
- const stepSandbox = sandboxProfileValue(step.sandbox);
1057
+ const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
1072
1058
  return {
1073
1059
  agent: step.agent,
1074
1060
  ...(step.sessionName ? { sessionName: step.sessionName } : {}),
@@ -1108,8 +1094,15 @@ export function isTopLevelAsyncDir(asyncDir: string): boolean {
1108
1094
  return containedPath(DIRS.async, resolved) && !containedPath(path.join(TEMP_ROOT_DIR, "nested-subagent-runs"), resolved);
1109
1095
  }
1110
1096
 
1111
- export function nestedResultsPath(rootRunId: string, id: string): string {
1097
+ export function nestedRunScope(rootRunId: string) {
1112
1098
  assertSafeId("rootRunId", rootRunId);
1099
+ return {
1100
+ asyncDirRoot: path.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
1101
+ resultsDir: path.join(DIRS.results, "nested", rootRunId),
1102
+ };
1103
+ }
1104
+
1105
+ export function nestedResultsPath(rootRunId: string, id: string): string {
1113
1106
  assertSafeId("id", id);
1114
- return path.join(DIRS.results, "nested", rootRunId, `${id}.json`);
1107
+ return path.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
1115
1108
  }
@@ -29,7 +29,7 @@ const ORCA_CREATE_WATCHDOG_SCRIPT = [
29
29
  "function exists(file){try{return fs.existsSync(file)}catch{return false}}",
30
30
  "function keepQueued(){try{const now=new Date();fs.utimesSync(done,now,now)}catch{}}",
31
31
  "function predecessorReady(){if(previous==='-')return true;if(exists(previous.replace(/\\.pending$/,'.ready')))return true;try{return Date.now()-fs.statSync(previous).mtimeMs>=waitTimeout}catch{return true}}",
32
- "function updateManifest(state,stdout=''){if(manifest==='-')return;try{const payload=JSON.parse(fs.readFileSync(manifest,'utf8'));payload.state=state;payload.updatedAt=new Date().toISOString();const raw=stdout.trim().split(/\\r?\\n/).filter(Boolean).at(-1);if(raw){try{payload.orca=JSON.parse(raw)}catch{payload.orcaRaw=raw.slice(0,4096)}}fs.writeFileSync(manifest,JSON.stringify(payload,null,2)+'\\n')}catch{}}",
32
+ "function updateManifest(state,stdout=''){if(manifest==='-')return;try{const payload=JSON.parse(fs.readFileSync(manifest,'utf8'));payload.state=state;payload.updatedAt=new Date().toISOString();const raw=stdout.trim();if(raw){try{payload.orca=JSON.parse(raw)}catch{payload.orcaRaw=raw.slice(0,4096)}}fs.writeFileSync(manifest,JSON.stringify(payload,null,2)+'\\n')}catch{}}",
33
33
  "function start(){",
34
34
  " try{",
35
35
  " const child=spawn(command,args,{stdio:['ignore','pipe','ignore'],windowsHide:true});",
@@ -53,6 +53,8 @@ const ORCA_CLEANUP_WATCHDOG_SCRIPT = [
53
53
  ].join("");
54
54
 
55
55
  export interface OrcaProgressTab {
56
+ /** Resolves when the terminal-create watchdog closes, after its final manifest/queue writes (success or failure). Not viewer completion. */
57
+ readonly creationSettled: Promise<void>;
56
58
  append(text: string): void;
57
59
  section(input: { agent: string; index: number; count: number }): void;
58
60
  event(event: { type?: string; message?: Message; toolName?: string; args?: unknown }): void;
@@ -402,6 +404,8 @@ export function createOrcaProgressTab(input: {
402
404
  }
403
405
  };
404
406
  let createSettled = false;
407
+ let resolveCreationSettled!: () => void;
408
+ const creationSettled = new Promise<void>((resolve) => { resolveCreationSettled = resolve; });
405
409
  let cleanupPaths: string[] | undefined;
406
410
  const scheduleDeferredCleanup = () => {
407
411
  if (!createSettled || cleanupPaths === undefined) return;
@@ -434,6 +438,7 @@ export function createOrcaProgressTab(input: {
434
438
  createSettled = true;
435
439
  if (code !== 0) failObserver();
436
440
  scheduleDeferredCleanup();
441
+ resolveCreationSettled();
437
442
  });
438
443
  watchdog.once("error", () => {
439
444
  markCreateReady();
@@ -450,6 +455,7 @@ export function createOrcaProgressTab(input: {
450
455
 
451
456
  let finished = false;
452
457
  return {
458
+ creationSettled,
453
459
  append(text) {
454
460
  if (finished) return;
455
461
  writeProgress(text);