@xzzpig/pi-subagents 0.4.1 → 0.5.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 (128) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/README.md +4 -0
  3. package/agents/oracle.md +3 -1
  4. package/agents/reviewer.md +1 -0
  5. package/agents/scout.md +2 -2
  6. package/agents/worker.md +2 -1
  7. package/async-retention-discovery-worker.mjs +180 -0
  8. package/docs/agents.md +41 -3
  9. package/docs/configuration.md +41 -13
  10. package/docs/extension-api.md +65 -2
  11. package/docs/models.md +2 -0
  12. package/docs/observability.md +41 -5
  13. package/docs/tool-reference.md +38 -39
  14. package/docs/workflows.md +173 -3
  15. package/package.json +14 -10
  16. package/prompts/council.md +48 -0
  17. package/skills/council-mode/SKILL.md +230 -0
  18. package/skills/pi-subagents/SKILL.md +8 -4
  19. package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
  20. package/skills/pi-subagents/references/execution-controls.md +40 -15
  21. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  22. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
  24. package/src/agents/agent-management.ts +471 -377
  25. package/src/agents/agent-serializer.ts +2 -0
  26. package/src/agents/agents.ts +186 -44
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +418 -0
  29. package/src/agents/skills.ts +1 -1
  30. package/src/api/agent-management.ts +9 -0
  31. package/src/api/agents.ts +7 -0
  32. package/src/api/external-job-provider.ts +186 -0
  33. package/src/api/preflight.ts +45 -13
  34. package/src/api/shared-types.ts +2 -0
  35. package/src/extension/config.ts +6 -3
  36. package/src/extension/doctor.ts +4 -6
  37. package/src/extension/fanout-child.ts +2 -2
  38. package/src/extension/index.ts +183 -90
  39. package/src/extension/public-execution.ts +31 -2
  40. package/src/extension/rpc.ts +41 -1
  41. package/src/extension/schemas.ts +17 -37
  42. package/src/extension/tool-description.ts +35 -24
  43. package/src/inspectors/herdr/actions.ts +2 -2
  44. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  45. package/src/inspectors/herdr/project-panes.ts +2 -2
  46. package/src/intercom/native-supervisor-channel.ts +32 -10
  47. package/src/missions/lifecycle.ts +6 -1
  48. package/src/missions/store.ts +4 -9
  49. package/src/missions/workflow-state.ts +2 -2
  50. package/src/profiles/profiles.ts +3 -1
  51. package/src/runs/background/active-run-index.ts +31 -8
  52. package/src/runs/background/async-execution.ts +70 -41
  53. package/src/runs/background/async-job-tracker.ts +24 -7
  54. package/src/runs/background/async-resume.ts +49 -16
  55. package/src/runs/background/async-retention.ts +886 -0
  56. package/src/runs/background/async-status-snapshot.ts +14 -5
  57. package/src/runs/background/async-status.ts +39 -53
  58. package/src/runs/background/auto-drain.ts +1 -0
  59. package/src/runs/background/chain-append.ts +3 -33
  60. package/src/runs/background/completion-dedupe.ts +5 -1
  61. package/src/runs/background/completion-replay.ts +22 -12
  62. package/src/runs/background/control-channel.ts +14 -68
  63. package/src/runs/background/fleet-view.ts +68 -19
  64. package/src/runs/background/index-segment.ts +59 -0
  65. package/src/runs/background/inspect-rpc.ts +443 -0
  66. package/src/runs/background/notify.ts +31 -5
  67. package/src/runs/background/result-files.ts +158 -90
  68. package/src/runs/background/result-watcher.ts +124 -20
  69. package/src/runs/background/resume-guidance.ts +8 -5
  70. package/src/runs/background/retained-children.ts +13 -3
  71. package/src/runs/background/run-id-query.ts +7 -0
  72. package/src/runs/background/run-id-resolver.ts +11 -9
  73. package/src/runs/background/run-status.ts +27 -18
  74. package/src/runs/background/scheduled-runs.ts +24 -4
  75. package/src/runs/background/stale-run-reconciler.ts +6 -3
  76. package/src/runs/background/steering.ts +11 -1
  77. package/src/runs/background/subagent-runner.ts +260 -144
  78. package/src/runs/background/subagent-wait.ts +17 -13
  79. package/src/runs/background/terminal-run-index.ts +138 -0
  80. package/src/runs/background/wait-completions.ts +21 -4
  81. package/src/runs/background/wait-subscriptions.ts +81 -2
  82. package/src/runs/background/wait-tool.ts +1 -0
  83. package/src/runs/foreground/async-steering-action.ts +21 -14
  84. package/src/runs/foreground/execution.ts +104 -71
  85. package/src/runs/foreground/subagent-executor.ts +816 -1593
  86. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  87. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  88. package/src/runs/shared/acceptance.ts +48 -5
  89. package/src/runs/shared/chain-outputs.ts +1 -3
  90. package/src/runs/shared/external-job-bridge.ts +444 -0
  91. package/src/runs/shared/external-job-runner.ts +286 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  93. package/src/runs/shared/model-exclusions.ts +242 -0
  94. package/src/runs/shared/model-fallback.ts +153 -40
  95. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  96. package/src/runs/shared/parallel-handoff.ts +46 -4
  97. package/src/runs/shared/parallel-utils.ts +4 -15
  98. package/src/runs/shared/permissions.ts +5 -1
  99. package/src/runs/shared/pi-args.ts +8 -1
  100. package/src/runs/shared/session-lease.ts +0 -6
  101. package/src/runs/shared/subagent-control.ts +51 -7
  102. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  103. package/src/runs/shared/workflow-graph.ts +1 -23
  104. package/src/runs/shared/worktree.ts +14 -2
  105. package/src/shared/atomic-json.ts +22 -2
  106. package/src/shared/capacity-resilient-json.ts +102 -0
  107. package/src/shared/completion-owner.ts +14 -0
  108. package/src/shared/file-system-retry.ts +49 -1
  109. package/src/shared/fork-context.ts +59 -1
  110. package/src/shared/model-info.ts +20 -0
  111. package/src/shared/prompt-resources.ts +0 -40
  112. package/src/shared/settings.ts +5 -29
  113. package/src/shared/types.ts +106 -26
  114. package/src/shared/utils.ts +8 -0
  115. package/src/shared/watch-strategy.ts +10 -0
  116. package/src/slash/slash-bridge.ts +2 -1
  117. package/src/slash/slash-commands.ts +47 -7
  118. package/src/slash/slash-live-state.ts +3 -3
  119. package/src/tui/fleet-status.ts +86 -1
  120. package/src/tui/fleet.ts +117 -16
  121. package/src/tui/render.ts +73 -3
  122. package/src/watchdog/change-signature.ts +1 -1
  123. package/src/watchdog/lsp-diagnostics.ts +1 -0
  124. package/src/workflows/chat-progress.ts +2 -2
  125. package/src/workflows/scripted-workflow.ts +320 -79
  126. package/src/workflows/workflow-receipt.ts +140 -0
  127. package/src/runs/foreground/chain-clarify.ts +0 -1354
  128. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -3,12 +3,12 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { resolveAgentName, type AgentConfig, type AgentScope } from "../../agents/agents.ts";
6
+ import { findBlockingAgentDiagnostic, resolveAgentName, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope } from "../../agents/agents.ts";
7
7
  import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
- import { ChainClarifyComponent, type ChainClarifyResult } from "./chain-clarify.ts";
9
+ import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
10
+ import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
10
11
  import { resolveEffectiveThinking, toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
11
- import { executeChain } from "./chain-execution.ts";
12
12
  import {
13
13
  beginForegroundChild,
14
14
  finishForegroundChild,
@@ -28,7 +28,7 @@ import { normalizePublicSubagentExecution } from "../../extension/public-executi
28
28
  import { runSync } from "./execution.ts";
29
29
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
30
30
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
31
- import { buildModelCandidates, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, type ParentModel } from "../shared/model-fallback.ts";
31
+ import { buildModelCandidates, inheritsParentModel, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
33
  import type { ModelScopeConfig } from "../shared/model-scope.ts";
34
34
  import { aggregateParallelOutputs } from "../shared/parallel-utils.ts";
@@ -55,13 +55,15 @@ import {
55
55
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
56
56
  import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
57
57
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
58
+ import { steeringReceipt } from "../background/steering.ts";
58
59
  import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
59
60
  import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
60
61
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
61
62
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
62
63
  import { normalizeGateAcceptance, validateExecutionAcceptance } from "../shared/acceptance.ts";
63
- import { createForkContextResolver, forkedChildRequiresThinkingOff } from "../../shared/fork-context.ts";
64
+ import { canPreferFork, createForkContextResolver, forkedChildRequiresThinkingOff, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
64
65
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
66
+ import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
65
67
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget, type IntercomBridgeState } from "../../intercom/intercom-bridge.ts";
66
68
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
67
69
  import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
@@ -86,10 +88,10 @@ import {
86
88
  resolveSubagentResultStatus,
87
89
  stripDetailsOutputsForIntercomReceipt,
88
90
  } from "../../intercom/result-intercom.ts";
89
- import { applySteeringRecoveryAgentConfig, buildRevivedAsyncTask, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
90
- import { deliverCheckpointDecisionRequest, deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
91
+ import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
92
+ import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
91
93
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
92
- import { steerAsyncRun } from "./async-steering-action.ts";
94
+ import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
93
95
  import {
94
96
  removeWorkflowForegroundSteeringRoute,
95
97
  resolveWorkflowForegroundSteeringTarget,
@@ -99,6 +101,7 @@ import {
99
101
  } from "./workflow-foreground-steering.ts";
100
102
  import { stopAsyncRun } from "./async-stop-action.ts";
101
103
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
104
+ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
102
105
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
103
106
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
104
107
  import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
@@ -115,8 +118,8 @@ import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
115
118
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
116
119
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
117
120
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
118
- import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowScriptChildResult } from "../../workflows/scripted-workflow.ts";
119
- import { renderWorkflowPrompt } from "../../shared/prompt-resources.ts";
121
+ import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
122
+ import { buildWorkflowReceipt, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
120
123
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
121
124
  import {
122
125
  cleanupWorktrees,
@@ -170,10 +173,11 @@ import {
170
173
  resolveCurrentMaxSubagentDepth,
171
174
  resolveMaxSubagentSpawnsPerRun,
172
175
  wrapForkTask,
176
+ type ScheduleOrigin,
173
177
  } from "../../shared/types.ts";
174
178
 
175
179
  const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
176
- const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "reject-checkpoint", "schedule.delete"]);
180
+ const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
177
181
 
178
182
  function editDistance(left: string, right: string): number {
179
183
  const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
@@ -286,11 +290,15 @@ export interface SubagentParamsLike {
286
290
  mode?: SteerDeliveryMode;
287
291
  workflowScript?: string;
288
292
  chatProgress?: "auto" | "off" | "live-card";
293
+ isolation?: "none" | "worktree";
289
294
  step?: ChainStep;
290
295
  /** Internal workflow ownership metadata; not part of the public schema. */
291
296
  workflowParentRunId?: string;
292
297
  workflowKey?: string;
298
+ /** Set by the scheduler so this run's completion can name the schedule that produced it. */
299
+ scheduleOrigin?: ScheduleOrigin;
293
300
  workflowChildAsyncId?: string;
301
+ workflowParentDeadlineAt?: number;
294
302
  suppressRoutineResultIntercom?: boolean;
295
303
  /** Internal inherited cumulative run-tree budget. */
296
304
  runFanoutBudget?: RunFanoutBudgetDescriptor;
@@ -301,7 +309,7 @@ export interface SubagentParamsLike {
301
309
  tasks?: TaskParam[];
302
310
  concurrency?: number;
303
311
  worktree?: boolean;
304
- context?: "fresh" | "fork";
312
+ context?: "fresh" | "fork" | "profile";
305
313
  /** Per-run intercom bridge config. It replaces the global config for this launch only. */
306
314
  intercomBridge?: IntercomBridgeConfig;
307
315
  async?: boolean;
@@ -339,8 +347,6 @@ export interface SubagentParamsLike {
339
347
  acceptance?: AcceptanceInput;
340
348
  gate?: string;
341
349
  agentContract?: AgentContract;
342
- schedule?: string;
343
- scheduleName?: string;
344
350
  at?: string;
345
351
  every?: string;
346
352
  on?: string | number;
@@ -378,13 +384,15 @@ interface ExecutorDeps {
378
384
  tempArtifactsDir: string;
379
385
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
380
386
  expandTilde: (p: string) => string;
381
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; modelScope?: ModelScopeConfig };
387
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig };
382
388
  allowMutatingManagementActions?: boolean;
389
+ activateSupervisorTransport?: () => void;
390
+ refreshResultDelivery?: () => void;
383
391
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
384
392
  }
385
393
 
386
- type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string) => string | undefined;
387
- type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string) => AgentConfig["thinking"] | undefined;
394
+ type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => string | undefined;
395
+ type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => AgentConfig["thinking"] | undefined;
388
396
 
389
397
  interface ExecutionContextData {
390
398
  params: SubagentParamsLike;
@@ -462,6 +470,7 @@ function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentP
462
470
  delete params.workflowParentRunId;
463
471
  delete params.workflowKey;
464
472
  delete params.workflowChildAsyncId;
473
+ delete params.workflowParentDeadlineAt;
465
474
  delete params.suppressRoutineResultIntercom;
466
475
  if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
467
476
  return params;
@@ -553,7 +562,7 @@ function countRequestedSubagentSpawns(params: SubagentParamsLike, config: Extens
553
562
  function staticRunFanoutPaths(params: SubagentParamsLike): string[] {
554
563
  if (params.tasks) return params.tasks.map((_, index) => `tasks[${index}]`);
555
564
  if (params.chain) return params.chain.flatMap((step, stepIndex) => {
556
- if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
565
+ if (isDynamicParallelStep(step)) return [];
557
566
  if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${stepIndex}].parallel[${itemIndex}]`);
558
567
  return [`chain[${stepIndex}]`];
559
568
  });
@@ -627,7 +636,7 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
627
636
  };
628
637
  }
629
638
 
630
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; checkpoint?: Details["checkpoint"] }): void {
639
+ function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[] }): void {
631
640
  state.foregroundRuns ??= new Map();
632
641
  const previous = state.foregroundRuns.get(input.runId);
633
642
  const updatedAt = Date.now();
@@ -637,7 +646,6 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
637
646
  cwd: input.cwd,
638
647
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
639
648
  updatedAt,
640
- ...(input.checkpoint ? { checkpoint: input.checkpoint } : {}),
641
649
  children: input.results.map((result, index) => {
642
650
  const child = {
643
651
  agent: result.agent,
@@ -788,12 +796,13 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
788
796
  });
789
797
  }
790
798
 
791
- function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
799
+ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
792
800
  const requested = (params.id ?? params.runId)?.trim();
793
801
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
794
- const sessionRuns = [...state.foregroundRuns.values()].filter((run) => run.sessionId === state.currentSessionId);
795
- const direct = sessionRuns.find((run) => run.runId === requested);
796
- const matches = direct ? [direct] : sessionRuns.filter((run) => run.runId.startsWith(requested));
802
+ const direct = state.foregroundRuns.get(requested);
803
+ const matches = direct?.sessionId === state.currentSessionId
804
+ ? [direct]
805
+ : options.exactOnly ? [] : [...state.foregroundRuns.values()].filter((run) => run.sessionId === state.currentSessionId && run.runId.startsWith(requested));
797
806
  if (matches.length === 0) return undefined;
798
807
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(", ")}. Provide a longer id.`);
799
808
  const run = matches[0]!;
@@ -861,7 +870,7 @@ function isExactResumeError(error: unknown, source: "async" | "foreground", requ
861
870
  return new RegExp(`\\b${source} run '${escapeRegExp(requested)}'`, "i").test(error.message);
862
871
  }
863
872
 
864
- function resolveResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { asyncRequireSessionFile?: boolean } = {}): ResumeSourceTarget {
873
+ function resolveResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { asyncRequireSessionFile?: boolean; exactOnly?: boolean } = {}): ResumeSourceTarget {
865
874
  const requested = (params.id ?? params.runId)?.trim() ?? "";
866
875
  let foregroundTarget: ForegroundResumeSourceTarget | undefined;
867
876
  let foregroundError: unknown;
@@ -869,15 +878,18 @@ function resolveResumeTarget(params: SubagentParamsLike, state: SubagentState, o
869
878
  let asyncError: unknown;
870
879
 
871
880
  try {
872
- const target = resolveForegroundResumeTarget(params, state);
881
+ const target = resolveForegroundResumeTarget(params, state, options);
873
882
  if (target) foregroundTarget = { kind: "revive", source: "foreground", ...target };
874
883
  } catch (error) {
875
884
  foregroundError = error;
876
885
  }
877
886
  try {
887
+ const asyncParams = options.exactOnly && requested && !params.dir
888
+ ? { ...params, dir: path.join(DIRS.async, requested) }
889
+ : params;
878
890
  asyncTarget = {
879
891
  source: "async",
880
- ...resolveAsyncResumeTarget(params, {}, compactOptional<NonNullable<Parameters<typeof resolveAsyncResumeTarget>[2]>>({
892
+ ...resolveAsyncResumeTarget(asyncParams, {}, compactOptional<NonNullable<Parameters<typeof resolveAsyncResumeTarget>[2]>>({
881
893
  requireSessionFile: options.asyncRequireSessionFile,
882
894
  sessionId: state.currentSessionId ?? undefined,
883
895
  })),
@@ -950,11 +962,48 @@ function emitAdvisoryControlEvent(pi: ExtensionAPI, channel: string, payload: un
950
962
  }
951
963
  }
952
964
 
965
+ function persistAsyncWorkflowControlEvent(input: {
966
+ job: AsyncJobState;
967
+ event: ControlEvent;
968
+ controlConfig: ResolvedControlConfig;
969
+ intercomBridge: IntercomBridgeState;
970
+ childIntercomTarget?: string;
971
+ }): void {
972
+ const channels = input.event.type === "active_long_running"
973
+ ? input.controlConfig.notifyChannels.filter((channel) => channel !== "intercom")
974
+ : input.controlConfig.notifyChannels;
975
+ if (channels.length === 0) return;
976
+ const record = {
977
+ ts: Date.now(),
978
+ runId: input.job.asyncId,
979
+ type: "subagent.control",
980
+ event: input.event,
981
+ channels,
982
+ childIntercomTarget: input.childIntercomTarget,
983
+ noticeText: formatControlNoticeMessage(input.event, input.childIntercomTarget),
984
+ ...(input.intercomBridge.active && input.intercomBridge.orchestratorTarget && channels.includes("intercom")
985
+ ? {
986
+ intercom: {
987
+ to: input.intercomBridge.orchestratorTarget,
988
+ message: formatControlIntercomMessage(input.event, input.childIntercomTarget),
989
+ },
990
+ }
991
+ : {}),
992
+ };
993
+ try {
994
+ fs.appendFileSync(path.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record)}\n`, "utf-8");
995
+ } catch (error) {
996
+ if (!isStorageCapacityError(error)) throw error;
997
+ console.error("Failed to append async workflow control event while storage is full:", error);
998
+ }
999
+ }
1000
+
953
1001
  function emitControlNotification(input: {
954
1002
  pi: ExtensionAPI;
955
1003
  controlConfig: ResolvedControlConfig;
956
1004
  intercomBridge: IntercomBridgeState;
957
1005
  event: ControlEvent;
1006
+ source?: "foreground" | "async";
958
1007
  }): void {
959
1008
  if (!shouldNotifyControlEvent(input.controlConfig, input.event)) return;
960
1009
  const childIntercomTarget = input.intercomBridge.active
@@ -962,7 +1011,7 @@ function emitControlNotification(input: {
962
1011
  : undefined;
963
1012
  const payload = {
964
1013
  event: input.event,
965
- source: "foreground" as const,
1014
+ source: input.source ?? "foreground",
966
1015
  childIntercomTarget,
967
1016
  noticeText: formatControlNoticeMessage(input.event, childIntercomTarget),
968
1017
  };
@@ -995,9 +1044,9 @@ function interruptAsyncRun(
995
1044
  };
996
1045
  }
997
1046
  const activeSteps = status.steps?.filter((step) => step.status === "running") ?? [];
998
- if (activeSteps.length > 0 && activeSteps.every((step) => step.runner?.type === "external-cli")) {
1047
+ if (activeSteps.length > 0 && activeSteps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) {
999
1048
  return {
1000
- content: [{ type: "text", text: `Interrupt is unsupported for one-shot external CLI async run ${target.asyncId}; use stop instead.` }],
1049
+ content: [{ type: "text", text: `Interrupt is unsupported for external async run ${target.asyncId}; use stop instead.` }],
1001
1050
  isError: true,
1002
1051
  details: { mode: "management", results: [] },
1003
1052
  };
@@ -1214,7 +1263,7 @@ function appendStepToAsyncChain(input: {
1214
1263
  const startIndex = (status.chainStepCount ?? status.steps?.length ?? 0) + pendingAppendRequests.reduce((total, request) => total + request.steps.length, 0);
1215
1264
  const appendPaths = chain.flatMap((step, localIndex) => {
1216
1265
  const absoluteIndex = startIndex + localIndex;
1217
- if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
1266
+ if (isDynamicParallelStep(step)) return [];
1218
1267
  if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${absoluteIndex}].parallel[${itemIndex}]`);
1219
1268
  return [`chain[${absoluteIndex}]`];
1220
1269
  });
@@ -1372,12 +1421,12 @@ async function directNestedAsyncSteer(input: { target: ResolvedSubagentRunId & {
1372
1421
  const targets = targetIndexes.map((index) => ({ index, state: steps[index]?.status === "pending" ? "scheduled" as const : "pending" as const }));
1373
1422
  if (targets.every((target) => target.state === "scheduled")) {
1374
1423
  const scheduled = { requestId, state: "scheduled" as const, deliveryStatus: "queued" as const, sourceRunId: run.id, targets };
1375
- return { content: [{ type: "text", text: `Steering scheduled for nested async run ${run.id} (request ${requestId}).` }], details: { mode: "management", results: [], steering: scheduled } };
1424
+ return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering scheduled for nested async run ${run.id} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: scheduled } };
1376
1425
  }
1377
1426
  const waited = await waitForSteeringAction(omitUndefinedProperties({ asyncDir, sourceRunId: run.id, requestId, timeoutMs: 3_000, signal: input.signal }));
1378
1427
  const result = waited ?? { requestId, state: "pending" as const, deliveryStatus: "queued" as const, sourceRunId: run.id, targets };
1379
1428
  const stateText = result.state === "failed" ? "failed" : result.state === "partial" ? "partial" : result.deliveryStatus === "queued" ? "queued" : result.state === "delivered" ? "delivered" : "pending";
1380
- return { content: [{ type: "text", text: `Steering ${stateText} for nested async run ${run.id} (request ${requestId}).` }], ...(result.state === "failed" || result.state === "partial" ? { isError: true } : {}), details: { mode: "management", results: [], steering: result } };
1429
+ return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering ${stateText} for nested async run ${run.id} (request ${requestId}).`) }], ...(result.state === "failed" || result.state === "partial" ? { isError: true } : {}), details: { mode: "management", results: [], steering: result } };
1381
1430
  }
1382
1431
 
1383
1432
  async function interruptNestedRun(target: ResolvedSubagentRunId & { kind: "nested" }): Promise<AgentToolResult<Details>> {
@@ -1409,10 +1458,10 @@ async function steerNestedRun(input: { target: ResolvedSubagentRunId & { kind: "
1409
1458
 
1410
1459
  function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"): AgentToolResult<Details> | undefined {
1411
1460
  const status = readStatus(asyncDir);
1412
- if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli")) return undefined;
1461
+ if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) return undefined;
1413
1462
  const message = action === "steer"
1414
- ? "One-shot external CLI runners do not accept live steer messages."
1415
- : "One-shot external CLI runners do not persist sessions and cannot be resumed.";
1463
+ ? "External runners do not accept live steer messages."
1464
+ : "External runners do not persist Pi sessions and cannot be resumed.";
1416
1465
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1417
1466
  }
1418
1467
 
@@ -1522,10 +1571,11 @@ async function resumeAsyncRun(input: {
1522
1571
  const modelScope = discovered.modelScope;
1523
1572
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1524
1573
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1574
+ const recoveryContext = recoveryDescriptor?.context ?? (input.params.context === "profile" ? undefined : input.params.context);
1525
1575
  const intercomBridge = resolveIntercomBridge({
1526
1576
  config: input.deps.config.intercomBridge,
1527
1577
  override: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1528
- context: input.params.context,
1578
+ context: recoveryContext,
1529
1579
  orchestratorTarget: sessionName,
1530
1580
  });
1531
1581
  const agents = intercomBridge.active
@@ -1565,7 +1615,7 @@ async function resumeAsyncRun(input: {
1565
1615
  details: { mode: "chain", results: [] },
1566
1616
  };
1567
1617
  }
1568
- const runId = randomUUID().slice(0, 8);
1618
+ const runId = randomUUID();
1569
1619
  const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1570
1620
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1571
1621
  try {
@@ -1657,10 +1707,10 @@ async function resumeAsyncRun(input: {
1657
1707
  if (!revivalSessionFile) {
1658
1708
  return { content: [{ type: "text", text: `Async child '${target.runId}' has no persisted session file to resume.` }], isError: true, details: { mode: "management", results: [] } };
1659
1709
  }
1660
- if (target.source === "async" && !recoveryDescriptor) {
1710
+ if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
1661
1711
  return { content: [{ type: "text", text: `Async child '${target.runId}' is missing its required run fan-out recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
1662
1712
  }
1663
- const runId = randomUUID().slice(0, 8);
1713
+ const runId = randomUUID();
1664
1714
  const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1665
1715
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1666
1716
  try {
@@ -1721,7 +1771,9 @@ async function resumeAsyncRun(input: {
1721
1771
  sourceRunId: target.runId,
1722
1772
  ...(input.deps.state.currentSessionId ? { parentSessionId: input.deps.state.currentSessionId } : {}),
1723
1773
  },
1774
+ context: recoveryContext,
1724
1775
  modelOverride: recoveryDescriptor?.model ?? target.model,
1776
+ modelOverrideFromParent: recoveryDescriptor?.modelOverrideFromParent,
1725
1777
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
1726
1778
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1727
1779
  maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
@@ -1729,6 +1781,7 @@ async function resumeAsyncRun(input: {
1729
1781
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1730
1782
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1731
1783
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1784
+ worktree: input.params.worktree === true,
1732
1785
  controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
1733
1786
  intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1734
1787
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
@@ -1772,7 +1825,7 @@ async function resumeAsyncRun(input: {
1772
1825
  const sourceStatus = readStatus(sourceAsyncDir);
1773
1826
  if (sourceStatus?.steering) {
1774
1827
  for (const brief of queuedBriefs) updateSteeringTarget(sourceStatus.steering, brief.request.id, target.index, "delivered", Date.now());
1775
- writeAtomicJson(path.join(sourceAsyncDir, "status.json"), sourceStatus);
1828
+ createCapacityResilientJsonWriter({ keepAlive: true }).write(path.join(sourceAsyncDir, "status.json"), sourceStatus);
1776
1829
  }
1777
1830
  }
1778
1831
 
@@ -1870,14 +1923,35 @@ function formatFailedSingleRunOutput(result: SingleResult, displayOutput: string
1870
1923
  return lines.join("\n");
1871
1924
  }
1872
1925
 
1873
- function createForegroundControlNotifier(data: Pick<ExecutionContextData, "controlConfig" | "intercomBridge">, deps: Pick<ExecutorDeps, "pi" | "state">): (event: ControlEvent) => void {
1926
+ function createForegroundControlNotifier(data: Pick<ExecutionContextData, "controlConfig" | "contextPolicy" | "intercomBridge" | "params">, deps: Pick<ExecutorDeps, "pi" | "state">): (event: ControlEvent) => void {
1874
1927
  return (event) => {
1875
1928
  applyControlEventToRememberedForegroundRun(deps.state, event);
1929
+ const eventBridge = intercomBridgeAppliesToAgent(data.intercomBridge, data.contextPolicy, event.agent)
1930
+ ? data.intercomBridge
1931
+ : { ...data.intercomBridge, active: false };
1932
+ const parentWorkflowRunId = data.params.workflowParentRunId;
1933
+ const asyncWorkflow = typeof parentWorkflowRunId === "string" ? deps.state.asyncJobs.get(parentWorkflowRunId) : undefined;
1934
+ const workflowKey = typeof data.params.workflowKey === "string" && data.params.workflowKey.trim()
1935
+ ? data.params.workflowKey.trim()
1936
+ : undefined;
1937
+ const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
1938
+ if (asyncWorkflow) {
1939
+ persistAsyncWorkflowControlEvent({
1940
+ job: asyncWorkflow,
1941
+ event: enriched,
1942
+ controlConfig: data.controlConfig,
1943
+ intercomBridge: eventBridge,
1944
+ childIntercomTarget: eventBridge.active
1945
+ ? resolveSubagentIntercomTarget(enriched.runId, enriched.agent, enriched.index)
1946
+ : undefined,
1947
+ });
1948
+ }
1876
1949
  emitControlNotification({
1877
1950
  pi: deps.pi,
1878
1951
  controlConfig: data.controlConfig,
1879
- intercomBridge: data.intercomBridge,
1880
- event,
1952
+ intercomBridge: eventBridge,
1953
+ event: enriched,
1954
+ source: asyncWorkflow ? "async" : "foreground",
1881
1955
  });
1882
1956
  };
1883
1957
  }
@@ -1963,16 +2037,19 @@ async function maybeBuildForegroundIntercomReceipt(input: {
1963
2037
  };
1964
2038
  }
1965
2039
 
1966
- function canonicalizeAgentName(name: string, agents: AgentConfig[]): { name?: string; error?: string } {
2040
+ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { name?: string; error?: string } {
1967
2041
  const resolved = resolveAgentName(name, agents);
2042
+ const candidates = resolved.error ? agents.filter((agent) => resolveAgentName(name, [agent]).agent) : resolved.agent;
2043
+ const diagnostic = findBlockingAgentDiagnostic(name, candidates, diagnostics);
2044
+ if (diagnostic) return { error: `Agent '${name}' has invalid configuration: ${diagnostic.error}` };
1968
2045
  if (resolved.error) return { error: resolved.error };
1969
2046
  if (!resolved.agent) return { error: `Unknown agent: ${name}` };
1970
2047
  return { name: resolved.agent.name };
1971
2048
  }
1972
2049
 
1973
- function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[]): { params?: SubagentParamsLike; error?: string } {
2050
+ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { params?: SubagentParamsLike; error?: string } {
1974
2051
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
1975
- const result = canonicalizeAgentName(name, agents);
2052
+ const result = canonicalizeAgentName(name, agents, diagnostics);
1976
2053
  return result.error && location ? { error: `${result.error} (${location})` } : result;
1977
2054
  };
1978
2055
  if (params.agent) {
@@ -2176,13 +2253,44 @@ interface AgentDefaultContextPolicy {
2176
2253
  usesFork: boolean;
2177
2254
  }
2178
2255
 
2179
- function resolveAgentDefaultContextPolicy(params: SubagentParamsLike, agents: AgentConfig[]): AgentDefaultContextPolicy {
2180
- if (params.context !== undefined) {
2181
- return resolveExplicitContextPolicy(params);
2256
+ type AgentDefaultContextPolicyResult = AgentDefaultContextPolicy | { error: string };
2257
+
2258
+ function resolveAgentDefaultContextPolicy(
2259
+ params: SubagentParamsLike,
2260
+ agents: AgentConfig[],
2261
+ defaultSubagentContext: ExtensionConfig["defaultSubagentContext"],
2262
+ canUseDefaultFork = false,
2263
+ ): AgentDefaultContextPolicyResult {
2264
+ if (params.context === "profile") {
2265
+ const byName = new Map(agents.map((agent) => [agent.name, agent]));
2266
+ for (const agentName of collectRequestedAgentNames(params)) {
2267
+ const agent = byName.get(agentName);
2268
+ if (agent && agent.defaultContext === undefined) {
2269
+ return { error: `context: "profile" requires agent '${agentName}' to declare defaultContext.` };
2270
+ }
2271
+ }
2272
+ const contextForAgent = (agentName: string): ContextMode => {
2273
+ const context = byName.get(agentName)?.defaultContext;
2274
+ if (context === undefined) throw new Error(`context: "profile" requires agent '${agentName}' to declare defaultContext.`);
2275
+ return context;
2276
+ };
2277
+ const contextSummary = summarizeContextModes(collectRequestedAgentNames(params).map(contextForAgent));
2278
+ return {
2279
+ params,
2280
+ contextForAgent,
2281
+ contextSummary,
2282
+ usesFork: contextSummary === "fork" || contextSummary === "mixed",
2283
+ };
2182
2284
  }
2285
+ if (params.context === "fresh" || params.context === "fork") return resolveExplicitContextPolicy(params);
2183
2286
  const byName = new Map(agents.map((agent) => [agent.name, agent]));
2184
2287
  const contextForAgent = (agentName: string): ContextMode =>
2185
- byName.get(agentName)?.defaultContext === "fork" ? "fork" : "fresh";
2288
+ resolveSubagentLaunchContext({
2289
+ explicitContext: undefined,
2290
+ agentDefaultContext: byName.get(agentName)?.defaultContext,
2291
+ defaultSubagentContext,
2292
+ canUseImplicitFork: canUseDefaultFork,
2293
+ });
2186
2294
  const requestedAgentNames = collectRequestedAgentNames(params);
2187
2295
  const contextSummary = summarizeContextModes(requestedAgentNames.map((name) => contextForAgent(name)));
2188
2296
  const usesFork = contextSummary === "fork" || contextSummary === "mixed";
@@ -2195,7 +2303,10 @@ function resolveAgentDefaultContextPolicy(params: SubagentParamsLike, agents: Ag
2195
2303
  }
2196
2304
 
2197
2305
  function resolveExplicitContextPolicy(params: SubagentParamsLike): AgentDefaultContextPolicy {
2198
- const context = params.context === "fork" ? "fork" : "fresh";
2306
+ const context = resolveSubagentLaunchContext({
2307
+ explicitContext: params.context === "profile" ? undefined : params.context,
2308
+ canUseImplicitFork: false,
2309
+ });
2199
2310
  return {
2200
2311
  params,
2201
2312
  contextForAgent: () => context,
@@ -2216,6 +2327,31 @@ function shouldForkAgent(contextPolicy: AgentDefaultContextPolicy, agentName: st
2216
2327
  return contextPolicy.contextForAgent(agentName) === "fork";
2217
2328
  }
2218
2329
 
2330
+ function intercomBridgeAppliesToAgent(bridge: IntercomBridgeState, contextPolicy: AgentDefaultContextPolicy, agentName: string): boolean {
2331
+ if (!bridge.active) return false;
2332
+ return bridge.mode !== "fork-only" || shouldForkAgent(contextPolicy, agentName);
2333
+ }
2334
+
2335
+ function applyScopedIntercomBridgeToAgents(agents: AgentConfig[], bridge: IntercomBridgeState, contextPolicy: AgentDefaultContextPolicy): AgentConfig[] {
2336
+ if (!bridge.active) return agents;
2337
+ return agents.map((agent) => intercomBridgeAppliesToAgent(bridge, contextPolicy, agent.name)
2338
+ ? applyIntercomBridgeToAgent(agent, bridge)
2339
+ : agent);
2340
+ }
2341
+
2342
+ function resolveChildIntercomTargetFactory(bridge: IntercomBridgeState, contextPolicy: AgentDefaultContextPolicy, runId: string): ((agent: string, index: number) => string | undefined) | undefined {
2343
+ if (!bridge.active) return undefined;
2344
+ return (agent, index) => intercomBridgeAppliesToAgent(bridge, contextPolicy, agent)
2345
+ ? resolveSubagentIntercomTarget(runId, agent, index)
2346
+ : undefined;
2347
+ }
2348
+
2349
+ function resolveRunLevelIntercomTarget(bridge: IntercomBridgeState, contextPolicy: AgentDefaultContextPolicy): string | undefined {
2350
+ if (!bridge.active) return undefined;
2351
+ if (bridge.mode === "fork-only" && contextPolicy.contextSummary === "mixed") return undefined;
2352
+ return bridge.orchestratorTarget;
2353
+ }
2354
+
2219
2355
  function summarizeResultContext(details: Details, fallback: ContextSummary | undefined): ContextSummary | undefined {
2220
2356
  return summarizeContextModes(details.results.map((result) => result.context)) ?? fallback;
2221
2357
  }
@@ -2227,7 +2363,7 @@ function buildRequestedModeError(params: SubagentParamsLike, message: string): A
2227
2363
  isError: true,
2228
2364
  details: { mode: getRequestedModeLabel(params), results: [] },
2229
2365
  },
2230
- params.context,
2366
+ params.context === "profile" ? undefined : params.context,
2231
2367
  );
2232
2368
  }
2233
2369
 
@@ -2235,12 +2371,16 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2235
2371
  if ((params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || !params.agent) return params;
2236
2372
  const agent = agents.find((candidate) => candidate.name === params.agent);
2237
2373
  if (!agent) return params;
2374
+ const parentTimeoutMs = params.timeoutMs === undefined && params.maxRuntimeMs === undefined && agent.defaultTimeoutMs === undefined && params.workflowParentDeadlineAt !== undefined
2375
+ ? Math.max(1, params.workflowParentDeadlineAt - Date.now())
2376
+ : undefined;
2238
2377
  return {
2239
2378
  ...params,
2240
2379
  ...(params.async === undefined && agent.defaultAsync !== undefined ? { async: agent.defaultAsync } : {}),
2241
2380
  ...(params.timeoutMs === undefined && params.maxRuntimeMs === undefined && agent.defaultTimeoutMs !== undefined
2242
2381
  ? { timeoutMs: agent.defaultTimeoutMs }
2243
2382
  : {}),
2383
+ ...(parentTimeoutMs !== undefined ? { timeoutMs: parentTimeoutMs } : {}),
2244
2384
  ...(params.turnBudget === undefined && agent.defaultTurnBudget !== undefined
2245
2385
  ? { turnBudget: agent.defaultTurnBudget }
2246
2386
  : {}),
@@ -2511,7 +2651,7 @@ function resolveStaticLaunchSummary(input: {
2511
2651
  thinkingOverrideForTask: ForkThinkingOverrideForTask;
2512
2652
  }): StaticLaunchSummary {
2513
2653
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2514
- const externalRunner = agentConfig?.runner?.type === "external-cli";
2654
+ const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
2515
2655
  const model = externalRunner
2516
2656
  ? undefined
2517
2657
  : resolveEffectiveSubagentModel(
@@ -2704,27 +2844,6 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2704
2844
  const hasSingle = !hasChain && !hasTasks && Boolean(params.agent);
2705
2845
  if (!effectiveAsync) return null;
2706
2846
 
2707
- if (hasChain && params.chain) {
2708
- const chainWorktreeTaskCwdError = buildChainWorktreeTaskCwdError(params.chain as ChainStep[], effectiveCwd);
2709
- if (chainWorktreeTaskCwdError) {
2710
- return {
2711
- content: [{ type: "text", text: chainWorktreeTaskCwdError }],
2712
- isError: true,
2713
- details: { mode: "chain" as const, results: [] },
2714
- };
2715
- }
2716
- }
2717
-
2718
- if (hasTasks && params.tasks) {
2719
- const maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
2720
- if (params.tasks.length > maxParallelTasks) {
2721
- return buildParallelModeError(`Max ${maxParallelTasks} tasks`);
2722
- }
2723
- if (params.worktree) {
2724
- const worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(params.tasks, effectiveCwd);
2725
- if (worktreeTaskCwdError) return buildParallelModeError(worktreeTaskCwdError);
2726
- }
2727
- }
2728
2847
 
2729
2848
  if (!isAsyncAvailable()) {
2730
2849
  return {
@@ -2749,121 +2868,9 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2749
2868
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
2750
2869
  const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
2751
2870
  const currentProvider = parentModel?.provider;
2752
- const controlIntercomTarget = intercomBridge.active ? intercomBridge.orchestratorTarget : undefined;
2753
- const childIntercomTarget = intercomBridge.active ? (agent: string, index: number) => resolveSubagentIntercomTarget(id, agent, index) : undefined;
2754
-
2755
- if (hasTasks && params.tasks) {
2756
- const skillOverrides = params.tasks.map((task) => normalizeSkillInput(task.skill));
2757
- const parallelTasks = params.tasks.map((task, index) => compactOptional<ParallelTaskItem>({
2758
- agent: task.agent,
2759
- task: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task) : task.task,
2760
- cwd: task.cwd,
2761
- ...(task.model !== undefined ? { model: task.model } : {}),
2762
- ...(skillOverrides[index] !== undefined ? { skill: skillOverrides[index] } : {}),
2763
- ...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),
2764
- ...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),
2765
- ...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),
2766
- ...(task.progress !== undefined ? { progress: task.progress } : {}),
2767
- ...(task.toolBudget !== undefined ? { toolBudget: task.toolBudget } : {}),
2768
- ...(task.outputSchema !== undefined ? { outputSchema: task.outputSchema } : {}),
2769
- ...(task.agentContract !== undefined ? { agentContract: task.agentContract } : {}),
2770
- ...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),
2771
- }));
2772
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2773
- chain: [compactOptional<ParallelStep>({
2774
- parallel: parallelTasks,
2775
- concurrency: resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency),
2776
- worktree: params.worktree,
2777
- })],
2778
- resultMode: "parallel",
2779
- goal: params.tasks[0]?.task ?? "",
2780
- agents,
2781
- ctx: asyncCtx,
2782
- availableModels,
2783
- cwd: effectiveCwd,
2784
- maxOutput: params.maxOutput,
2785
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2786
- artifactConfig,
2787
- shareEnabled,
2788
- sessionRoot,
2789
- chainSkills: [],
2790
- activeAsyncCapacity: data.activeAsyncCapacity,
2791
- sessionFilesByFlatIndex: params.tasks.map((task, index) => sessionFileForTask(task.agent, index, task.model)),
2792
- thinkingOverridesByFlatIndex: params.tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, task.model)),
2793
- contextForAgent: contextPolicy.contextForAgent,
2794
- maxSubagentDepth: currentMaxSubagentDepth,
2795
- waitToolEnabled: deps.waitToolEnabled,
2796
- worktreeSetupHook: deps.config.worktreeSetupHook,
2797
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2798
- worktreeBaseDir: deps.config.worktreeBaseDir,
2799
- controlConfig,
2800
- agentContract: params.agentContract,
2801
- controlIntercomTarget,
2802
- childIntercomTarget,
2803
- nestedRoute,
2804
- timeoutMs: data.timeoutMs,
2805
- turnBudget: data.turnBudget,
2806
- toolBudget: data.toolBudget,
2807
- usageBudget: data.usageBudget,
2808
- configToolBudget: data.configToolBudget,
2809
- callToolTimeoutMs: data.params?.toolTimeoutMs,
2810
- configToolTimeoutMs: data.configToolTimeoutMs,
2811
- capabilityCeiling: data.capabilityCeiling,
2812
- runFanoutBudget: data.runFanoutBudget,
2813
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2814
- parentWorkflowRunId: params.workflowParentRunId,
2815
- workflowKey: params.workflowKey,
2816
- }));
2817
- }
2871
+ const controlIntercomTarget = resolveRunLevelIntercomTarget(intercomBridge, contextPolicy);
2872
+ const childIntercomTarget = resolveChildIntercomTargetFactory(intercomBridge, contextPolicy, id);
2818
2873
 
2819
- if (hasChain && params.chain) {
2820
- const normalized = normalizeSkillInput(params.skill);
2821
- const chainSkills = normalized === false ? [] : (normalized ?? []);
2822
- const rawChain = params.chain as ChainStep[];
2823
- const chain = wrapChainTasksForFork(rawChain, contextPolicy);
2824
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2825
- chain,
2826
- task: params.task,
2827
- goal: resolveAsyncEventGoal(params.task, rawChain),
2828
- agents,
2829
- ctx: asyncCtx,
2830
- availableModels,
2831
- cwd: effectiveCwd,
2832
- maxOutput: params.maxOutput,
2833
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2834
- artifactConfig,
2835
- shareEnabled,
2836
- sessionRoot,
2837
- chainSkills,
2838
- activeAsyncCapacity: data.activeAsyncCapacity,
2839
- sessionFilesByFlatIndex: collectChainSessionFiles(chain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
2840
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(chain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
2841
- contextForAgent: contextPolicy.contextForAgent,
2842
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
2843
- maxSubagentDepth: currentMaxSubagentDepth,
2844
- waitToolEnabled: deps.waitToolEnabled,
2845
- worktreeSetupHook: deps.config.worktreeSetupHook,
2846
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2847
- worktreeBaseDir: deps.config.worktreeBaseDir,
2848
- controlConfig,
2849
- agentContract: params.agentContract,
2850
- controlIntercomTarget,
2851
- childIntercomTarget,
2852
- nestedRoute,
2853
- timeoutMs: data.timeoutMs,
2854
- turnBudget: data.turnBudget,
2855
- toolBudget: data.toolBudget,
2856
- usageBudget: data.usageBudget,
2857
- configToolBudget: data.configToolBudget,
2858
- callToolTimeoutMs: data.params?.toolTimeoutMs,
2859
- configToolTimeoutMs: data.configToolTimeoutMs,
2860
- capabilityCeiling: data.capabilityCeiling,
2861
- runFanoutBudget: data.runFanoutBudget,
2862
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2863
- parentWorkflowRunId: params.workflowParentRunId,
2864
- workflowKey: params.workflowKey,
2865
- }));
2866
- }
2867
2874
 
2868
2875
  if (hasSingle) {
2869
2876
  const a = agents.find((x) => x.name === params.agent);
@@ -2876,16 +2883,17 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2876
2883
  }
2877
2884
  const rawOutput = params.output !== undefined ? params.output : a.output;
2878
2885
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
2879
- const effectiveOutputMode = params.outputMode ?? "inline";
2886
+ const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
2880
2887
  const normalizedSkills = normalizeSkillInput(params.skill);
2881
2888
  const skills = normalizedSkills === false ? [] : normalizedSkills;
2882
2889
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth);
2883
- const externalRunnerWithoutExplicitModel = a.runner?.type === "external-cli"
2890
+ const externalRunnerWithoutExplicitModel = (a.runner?.type === "external-cli" || a.runner?.type === "external-job")
2884
2891
  && params.model === undefined
2885
2892
  && (a.model === undefined || (a.modelSource?.type === "subagents.defaultModel" && a.model === a.modelSource.model));
2886
- const modelOverride = a.runner?.type === "external-cli"
2893
+ const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
2887
2894
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
2888
2895
  : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2896
+ const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel);
2889
2897
  return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2890
2898
  agent: params.agent!,
2891
2899
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
@@ -2901,7 +2909,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2901
2909
  shareEnabled,
2902
2910
  activeAsyncCapacity: data.activeAsyncCapacity,
2903
2911
  sessionRoot,
2904
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
2912
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
2905
2913
  context: contextPolicy.contextForAgent(params.agent!),
2906
2914
  skills,
2907
2915
  output: effectiveOutput,
@@ -2909,9 +2917,11 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2909
2917
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
2910
2918
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
2911
2919
  modelOverride,
2912
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride),
2920
+ modelOverrideFromParent,
2921
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
2913
2922
  maxSubagentDepth,
2914
2923
  waitToolEnabled: deps.waitToolEnabled,
2924
+ ...(params.worktree === true ? { worktree: true } : {}),
2915
2925
  worktreeSetupHook: deps.config.worktreeSetupHook,
2916
2926
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2917
2927
  worktreeBaseDir: deps.config.worktreeBaseDir,
@@ -2940,308 +2950,11 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2940
2950
  return null;
2941
2951
  }
2942
2952
 
2943
- async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {
2944
- const {
2945
- params,
2946
- effectiveCwd,
2947
- agents,
2948
- ctx,
2949
- signal,
2950
- runId,
2951
- shareEnabled,
2952
- sessionDirForIndex,
2953
- sessionFileForIndex,
2954
- sessionFileForTask,
2955
- thinkingOverrideForTask,
2956
- artifactsDir,
2957
- artifactConfig,
2958
- onUpdate,
2959
- sessionRoot,
2960
- controlConfig,
2961
- contextPolicy,
2962
- } = data;
2963
- const onControlEvent = createForegroundControlNotifier(data, deps);
2964
- const childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;
2965
- const foregroundControl = deps.state.foregroundControls.get(runId);
2966
- const normalized = normalizeSkillInput(params.skill);
2967
- const chainSkills = normalized === false ? [] : (normalized ?? []);
2968
- const chain = wrapChainTasksForFork(params.chain as ChainStep[], contextPolicy);
2969
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
2970
- const chainCtx = normalizeParentModel(ctx.model) || !data.parentModel ? ctx : ({ ...ctx, model: data.parentModel } as ExtensionContext);
2971
- const chainResult = await executeChain(compactOptional<Parameters<typeof executeChain>[0]>({
2972
- chain,
2973
- task: params.task,
2974
- agents,
2975
- ctx: chainCtx,
2976
- modelScope: data.modelScope,
2977
- intercomEvents: deps.pi.events,
2978
- signal,
2979
- runId,
2980
- cwd: effectiveCwd,
2981
- shareEnabled,
2982
- sessionDirForIndex,
2983
- sessionFileForIndex,
2984
- sessionFileForTask,
2985
- thinkingOverrideForTask,
2986
- contextForAgent: contextPolicy.contextForAgent,
2987
- artifactsDir,
2988
- artifactConfig,
2989
- includeProgress: params.includeProgress,
2990
- clarify: params.clarify,
2991
- onUpdate,
2992
- onControlEvent,
2993
- controlConfig,
2994
- agentContract: params.agentContract,
2995
- childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : undefined,
2996
- orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
2997
- foregroundControl,
2998
- nestedRoute: foregroundControl?.nestedRoute,
2999
- chainSkills,
3000
- chainDir: params.chainDir ?? getChainRunsDir(effectiveCwd, artifactConfig.dir),
3001
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
3002
- maxSubagentDepth: currentMaxSubagentDepth,
3003
- worktreeSetupHook: deps.config.worktreeSetupHook,
3004
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3005
- worktreeBaseDir: deps.config.worktreeBaseDir,
3006
- timeoutMs: data.timeoutMs,
3007
- deadlineAt: data.deadlineAt,
3008
- turnBudget: data.turnBudget,
3009
- onDetachedExit: (index, result) => {
3010
- try {
3011
- updateRememberedForegroundChild(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, index, result, events: deps.pi.events });
3012
- } finally {
3013
- removeForegroundControlIfIdle(deps.state, runId);
3014
- }
3015
- },
3016
- onForegroundChildSettled: () => {
3017
- removeForegroundControlIfIdle(deps.state, runId);
3018
- },
3019
- toolBudget: data.toolBudget,
3020
- usageBudget: data.usageBudget,
3021
- configToolBudget: data.configToolBudget,
3022
- callToolTimeoutMs: data.params?.toolTimeoutMs,
3023
- configToolTimeoutMs: data.configToolTimeoutMs,
3024
- permissions: deps.config.permissions,
3025
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3026
- capabilityCeiling: data.capabilityCeiling,
3027
- runFanoutBudget: data.runFanoutBudget,
3028
- }));
3029
-
3030
- if (chainResult.requestedAsync) {
3031
- if (!isAsyncAvailable()) {
3032
- return {
3033
- content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
3034
- isError: true,
3035
- details: { mode: "chain" as const, results: [] },
3036
- };
3037
- }
3038
- const id = data.asyncRunId;
3039
- const capacity = acquireClarifiedBackgroundCapacity(data, deps, "chain", id);
3040
- if (capacity.errorResult) return capacity.errorResult;
3041
- const parentModel = data.parentModel;
3042
- const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3043
- pi: deps.pi,
3044
- cwd: ctx.cwd,
3045
- currentSessionId: data.parentSessionId!,
3046
- parentSessionId: data.parentPiSessionId,
3047
- currentModelProvider: parentModel?.provider,
3048
- currentModel: parentModel,
3049
- modelScope: data.modelScope,
3050
- interactive: ctx.hasUI,
3051
- permissions: deps.config.permissions,
3052
- });
3053
- const rawAsyncChain = chainResult.requestedAsync.chain;
3054
- const asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy);
3055
- const firstAgent = firstChainAgent(rawAsyncChain);
3056
- try {
3057
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3058
- chain: asyncChain,
3059
- task: params.task,
3060
- goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false),
3061
- agents,
3062
- ctx: asyncCtx,
3063
- availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
3064
- cwd: effectiveCwd,
3065
- maxOutput: params.maxOutput,
3066
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3067
- artifactConfig,
3068
- shareEnabled,
3069
- sessionRoot,
3070
- chainSkills: chainResult.requestedAsync.chainSkills,
3071
- activeAsyncCapacity: capacity.activeAsyncCapacity,
3072
- sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
3073
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
3074
- contextForAgent: contextPolicy.contextForAgent,
3075
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
3076
- maxSubagentDepth: currentMaxSubagentDepth,
3077
- waitToolEnabled: deps.waitToolEnabled,
3078
- worktreeSetupHook: deps.config.worktreeSetupHook,
3079
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3080
- worktreeBaseDir: deps.config.worktreeBaseDir,
3081
- controlConfig,
3082
- agentContract: params.agentContract,
3083
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3084
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3085
- nestedRoute: data.nestedRoute,
3086
- timeoutMs: data.timeoutMs,
3087
- turnBudget: data.turnBudget,
3088
- toolBudget: data.toolBudget,
3089
- usageBudget: data.usageBudget,
3090
- configToolBudget: data.configToolBudget,
3091
- callToolTimeoutMs: data.params?.toolTimeoutMs,
3092
- configToolTimeoutMs: data.configToolTimeoutMs,
3093
- capabilityCeiling: data.capabilityCeiling,
3094
- runFanoutBudget: data.runFanoutBudget,
3095
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3096
- }));
3097
- } finally {
3098
- finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3099
- }
3100
- }
3101
-
3102
- const rawChainDetails = chainResult.details ? compactOptional<Details>({ ...chainResult.details, runId, timeoutMs: data.timeoutMs }) : undefined;
3103
- if (foregroundControl && rawChainDetails) {
3104
- updateForegroundNestedProjection(foregroundControl);
3105
- attachRootChildrenToSteps(runId, rawChainDetails.results, foregroundControl.nestedChildren);
3106
- rawChainDetails.totalCost = sumResultsCost(rawChainDetails.results);
3107
- const usageBudget = usageBudgetState(data.usageBudget, rawChainDetails.totalCost);
3108
- if (usageBudget === undefined) delete rawChainDetails.usageBudget;
3109
- else rawChainDetails.usageBudget = usageBudget;
3110
- }
3111
- const chainDetails = rawChainDetails ? compactForegroundDetails(rawChainDetails) : undefined;
3112
- if (chainDetails) rememberForegroundRun(deps.state, { runId, mode: "chain", cwd: effectiveCwd, sessionId: data.parentSessionId, results: chainDetails.results, checkpoint: chainDetails.checkpoint });
3113
- const intercomReceipt = chainDetails && !chainDetails.results.some((result) => result.interrupted || result.detached)
3114
- ? await maybeBuildForegroundIntercomReceipt({
3115
- pi: deps.pi,
3116
- intercomBridge: data.intercomBridge,
3117
- runId,
3118
- mode: "chain",
3119
- details: chainDetails,
3120
- ...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),
3121
- })
3122
- : null;
3123
- if (intercomReceipt) {
3124
- return {
3125
- ...chainResult,
3126
- content: [{ type: "text", text: intercomReceipt.text }],
3127
- details: intercomReceipt.details,
3128
- };
3129
- }
3130
-
3131
- return chainDetails ? { ...chainResult, details: chainDetails } : chainResult;
3132
- }
3133
-
3134
- interface ForegroundParallelRunInput {
3135
- tasks: TaskParam[];
3136
- taskTexts: string[];
3137
- taskDescriptions: string[];
3138
- agents: AgentConfig[];
3139
- ctx: ExtensionContext;
3140
- state: SubagentState;
3141
- intercomEvents: IntercomEventBus;
3142
- parentSessionId: string | null;
3143
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
3144
- runFanoutBudget: RunFanoutBudgetDescriptor;
3145
- signal: AbortSignal;
3146
- runId: string;
3147
- sessionDirForIndex: (idx?: number) => string | undefined;
3148
- sessionFileForIndex: (idx?: number) => string | undefined;
3149
- sessionFileForTask: ForkSessionFileForTask;
3150
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
3151
- shareEnabled: boolean;
3152
- artifactConfig: ArtifactConfig;
3153
- artifactsDir: string;
3154
- outputBaseDir: string;
3155
- maxOutput?: MaxOutputConfig;
3156
- paramsCwd: string;
3157
- progressDir: string;
3158
- maxSubagentDepths: number[];
3159
- waitToolEnabled?: boolean;
3160
- availableModels: ModelInfo[];
3161
- modelScope?: ModelScopeConfig;
3162
- parentModel?: ParentModel;
3163
- modelOverrides: (string | undefined)[];
3164
- behaviors: Array<ReturnType<typeof resolveStepBehavior>>;
3165
- firstProgressIndex: number;
3166
- controlConfig: ResolvedControlConfig;
3167
- contextPolicy: AgentDefaultContextPolicy;
3168
- onControlEvent?: (event: ControlEvent) => void;
3169
- childIntercomTarget?: (agent: string, index: number) => string | undefined;
3170
- orchestratorIntercomTarget?: string;
3171
- foregroundControl?: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never;
3172
- concurrencyLimit: number;
3173
- globalSemaphore?: Semaphore;
3174
- liveResults: (SingleResult | undefined)[];
3175
- liveProgress: (AgentProgress | undefined)[];
3176
- onUpdate?: (r: AgentToolResult<Details>) => void;
3177
- worktreeSetup?: WorktreeSetup;
3178
- timeoutMs?: number;
3179
- deadlineAt?: number;
3180
- /** Per-call per-tool timeout, resolved separately for each task's agent. */
3181
- toolTimeoutMs?: number;
3182
- /** Raw global config.toolTimeoutMs, used by each task's resolver. */
3183
- configToolTimeoutMs?: number;
3184
- turnBudget?: ResolvedTurnBudget;
3185
- usageBudget?: UsageBudgetConfig;
3186
- toolBudgets: (ResolvedToolBudget | undefined)[];
3187
- agentContract?: AgentContract;
3188
- permissions?: ExtensionConfig["permissions"];
3189
- }
3190
- function buildParallelModeError(message: string): AgentToolResult<Details> {
3191
- return {
3192
- content: [{ type: "text", text: message }],
3193
- isError: true,
3194
- details: { mode: "parallel" as const, results: [] },
3195
- };
3196
- }
3197
-
3198
- function acquireClarifiedBackgroundCapacity(
3199
- data: ExecutionContextData,
3200
- deps: ExecutorDeps,
3201
- mode: "single" | "parallel" | "chain",
3202
- asyncRunId: string,
3203
- ): { activeAsyncCapacity?: ActiveAsyncCapacityHandle; errorResult?: AgentToolResult<Details> } {
3204
- if (!data.topLevelAsyncCapacityEligible || !data.parentSessionId) return {};
3205
- const liveWorkflowRunIds = new Set(deps.state.workflowControllers?.keys() ?? []);
3206
- const activeLimit = resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession);
3207
- try {
3208
- const activeAsyncCapacity = acquireActiveAsyncCapacity({
3209
- sessionId: data.parentSessionId,
3210
- limit: activeLimit,
3211
- runId: asyncRunId,
3212
- kind: "runner",
3213
- asyncDir: path.join(DIRS.async, asyncRunId),
3214
- }, { liveWorkflowRunIds });
3215
- deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(data.parentSessionId, activeLimit, { liveWorkflowRunIds });
3216
- return { activeAsyncCapacity };
3217
- } catch (error) {
3218
- if (error instanceof ActiveAsyncCapacityError) {
3219
- deps.state.activeAsyncCapacity = error.snapshot;
3220
- return { errorResult: { content: [{ type: "text", text: error.message }], isError: true, details: { mode, results: [], activeAsyncCapacity: error.snapshot } } };
3221
- }
3222
- throw error;
3223
- }
3224
- }
3225
-
3226
- function finalizeClarifiedBackgroundCapacity(
3227
- data: ExecutionContextData,
3228
- deps: ExecutorDeps,
3229
- activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined,
3230
- ): void {
3231
- if (!activeAsyncCapacity || !data.parentSessionId) return;
3232
- if (!activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
3233
- deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
3234
- data.parentSessionId,
3235
- resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession),
3236
- { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) },
3237
- );
3238
- }
3239
-
3240
- function createParallelWorktreeSetup(
2953
+ function createSingleWorktreeSetup(
3241
2954
  enabled: boolean | undefined,
3242
2955
  cwd: string,
3243
2956
  runId: string,
3244
- tasks: TaskParam[],
2957
+ agent: string,
3245
2958
  setupHook: ExtensionConfig["worktreeSetupHook"],
3246
2959
  setupHookTimeoutMs: ExtensionConfig["worktreeSetupHookTimeoutMs"],
3247
2960
  baseDir: ExtensionConfig["worktreeBaseDir"],
@@ -3249,8 +2962,8 @@ function createParallelWorktreeSetup(
3249
2962
  if (!enabled) return {};
3250
2963
  try {
3251
2964
  return {
3252
- setup: createWorktrees(cwd, runId, tasks.length, omitUndefinedProperties({
3253
- agents: tasks.map((task) => task.agent),
2965
+ setup: createWorktrees(cwd, runId, 1, omitUndefinedProperties({
2966
+ agents: [agent],
3254
2967
  setupHook: setupHook
3255
2968
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
3256
2969
  : undefined,
@@ -3259,27 +2972,25 @@ function createParallelWorktreeSetup(
3259
2972
  };
3260
2973
  } catch (error) {
3261
2974
  const message = error instanceof Error ? error.message : String(error);
3262
- return { errorResult: buildParallelModeError(message) };
2975
+ return { errorResult: { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } } };
3263
2976
  }
3264
2977
  }
3265
2978
 
3266
- function buildParallelWorktreeTaskCwdError(
3267
- tasks: ReadonlyArray<{ agent: string; cwd?: string }>,
3268
- sharedCwd: string,
3269
- ): string | undefined {
3270
- const conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);
3271
- if (!conflict) return undefined;
3272
- return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
3273
- }
3274
-
3275
2979
  function resolveConfiguredSingleRunOutputBaseDir(deps: ExecutorDeps): string | undefined {
3276
2980
  return deps.config.singleRunOutputBaseDir
3277
2981
  ? path.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir))
3278
2982
  : undefined;
3279
2983
  }
3280
2984
 
2985
+ export function sanitizeRunPathSegment(value: string, maxBytes = 120): string {
2986
+ const sanitized = value.trim().replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
2987
+ if (!sanitized) return "unknown";
2988
+ if (Buffer.byteLength(sanitized, "utf-8") <= maxBytes) return sanitized;
2989
+ return sanitized.slice(0, maxBytes).replace(/_+$/, "") || "unknown";
2990
+ }
2991
+
3281
2992
  function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {
3282
- return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", runId);
2993
+ return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", sanitizeRunPathSegment(runId));
3283
2994
  }
3284
2995
 
3285
2996
  function resolveWorkflowAggregateOutputPath(
@@ -3298,12 +3009,13 @@ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, art
3298
3009
  const parsed = path.parse(aggregateOutputPath);
3299
3010
  return path.join(parsed.dir, `${parsed.name}.${workflowKey}${parsed.ext || ".md"}`);
3300
3011
  }
3301
- return path.join(artifactsDir, "outputs", workflowRunId, `${workflowKey}.md`);
3012
+ return path.join(artifactsDir, "outputs", sanitizeRunPathSegment(workflowRunId), `${workflowKey}.md`);
3302
3013
  }
3303
3014
 
3304
- function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string): string | undefined {
3015
+ function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string, producedChildOutputPaths: ReadonlySet<string>): string | undefined {
3305
3016
  if (!outputPath) return undefined;
3306
3017
  try {
3018
+ if (producedChildOutputPaths.has(outputPath)) return undefined;
3307
3019
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3308
3020
  fs.writeFileSync(outputPath, text, "utf-8");
3309
3021
  return undefined;
@@ -3325,799 +3037,162 @@ function resolveWorkflowChildOutputPath(input: {
3325
3037
  configuredOutputBaseDir?: string;
3326
3038
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3327
3039
  workflowAgentScope?: unknown;
3040
+ state?: SubagentState;
3328
3041
  key: string;
3329
3042
  params: Record<string, unknown>;
3330
- }): string | undefined {
3043
+ }): { path?: string; inherited: boolean } {
3044
+ if (typeof input.params.resume === "string") {
3045
+ if (!input.state) return { path: undefined, inherited: false };
3046
+ const index = input.params.index;
3047
+ const target = resolveResumeTarget({
3048
+ id: input.params.resume.trim(),
3049
+ ...(typeof index === "number" && Number.isInteger(index) ? { index } : {}),
3050
+ }, input.state);
3051
+ return { path: "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined, inherited: false };
3052
+ }
3331
3053
  const rawOutput = input.params.output;
3332
3054
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3333
- const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3334
- const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3335
- const agents = input.discoverAgents(childCwd, agentScope).agents;
3336
- const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3337
- const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3338
- const output = rawOutput === true || rawOutput === "true"
3339
- ? agentOutput
3340
- : hasExplicitOutput
3341
- ? rawOutput
3342
- : workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key);
3343
- return resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir);
3344
- }
3345
-
3346
- function workflowChildOutputClaims(input: {
3347
- ctxCwd: string;
3348
- workflowCwd: string;
3349
- artifactsDir: string;
3350
- workflowRunId: string;
3351
- aggregateOutputPath?: string;
3352
- configuredOutputBaseDir?: string;
3353
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3354
- workflowAgentScope?: unknown;
3355
- claimedOutputPaths: Map<string, string>;
3356
- entries: Array<{ key: string; params: Record<string, unknown> }>;
3357
- }): { error?: string; claims?: Map<string, string> } {
3358
- const claims = new Map(input.claimedOutputPaths);
3359
- for (const { key, params } of input.entries) {
3360
- const resolved = resolveWorkflowChildOutputPath({ ...input, key, params });
3361
- if (!resolved) continue;
3362
- if (input.aggregateOutputPath && resolved === input.aggregateOutputPath) return { error: `Workflow child '${key}' output resolves to the workflow aggregate output path: ${resolved}. Use a distinct child output path.` };
3363
- const previous = claims.get(resolved);
3364
- if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3365
- claims.set(resolved, key);
3366
- }
3367
- return { claims };
3368
- }
3369
-
3370
- function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
3371
- target.clear();
3372
- for (const [resolved, key] of claims) target.set(resolved, key);
3373
- }
3374
-
3375
- function prepareWorkflowChildLaunchParams(input: {
3376
- workflowDefaults: SubagentParamsLike;
3377
- childParams: Record<string, unknown>;
3378
- parentWorkflowRunId: string;
3379
- workflowKey: string;
3380
- ctxCwd: string;
3381
- workflowCwd: string;
3382
- artifactsDir: string;
3383
- aggregateOutputPath?: string;
3384
- configuredOutputBaseDir?: string;
3385
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3386
- workflowAgentScope?: unknown;
3387
- options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor };
3388
- }): SubagentParamsLike {
3389
- let childParams = input.childParams;
3390
- if (input.childParams.output === undefined && input.childParams.resume === undefined) {
3391
- childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3392
- } else if (input.childParams.resume === undefined) {
3393
- const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
3394
- if (resolvedOutput) childParams = { ...input.childParams, output: resolvedOutput };
3395
- }
3396
- return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
3397
- }
3398
-
3399
- function buildChainWorktreeTaskCwdError(chain: ChainStep[], sharedCwd: string): string | undefined {
3400
- for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
3401
- const step = chain[stepIndex]!;
3402
- if (!isParallelStep(step) || !step.worktree) continue;
3403
- const stepCwd = resolveChildCwd(sharedCwd, step.cwd);
3404
- const conflict = findWorktreeTaskCwdConflict(step.parallel, stepCwd);
3405
- if (!conflict) continue;
3406
- const detail = formatWorktreeTaskCwdConflict(conflict, stepCwd);
3407
- return `parallel chain step ${stepIndex + 1}: ${detail}`;
3408
- }
3409
- return undefined;
3410
- }
3411
-
3412
- function resolveParallelTaskCwd(
3413
- task: TaskParam,
3414
- paramsCwd: string,
3415
- worktreeSetup: WorktreeSetup | undefined,
3416
- index: number,
3417
- ): string {
3418
- if (worktreeSetup) return worktreeSetup.worktrees[index]!.agentCwd;
3419
- return resolveChildCwd(paramsCwd, task.cwd);
3420
- }
3421
-
3422
- function finalizeParallelWorktreeHandoff(input: {
3423
- worktreeSetup: WorktreeSetup;
3424
- artifactsDir: string;
3425
- runId: string;
3426
- cwd: string;
3427
- tasks: TaskParam[];
3428
- results: SingleResult[];
3429
- }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3430
- const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3431
- const diffs = diffWorktrees(input.worktreeSetup, input.tasks.map((task) => task.agent), diffsDir);
3432
- const diffSummary = formatWorktreeDiffSummary(diffs);
3433
- const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
3434
- const handoff = {
3435
- manifestPath,
3436
- runId: input.runId,
3437
- mode: "parallel" as const,
3438
- source: "foreground" as const,
3439
- cwd: input.cwd,
3440
- stepIndex: 0,
3441
- flatStartIndex: 0,
3442
- setup: input.worktreeSetup,
3443
- diffs,
3444
- results: input.results.map((result) => ({
3445
- agent: result.agent,
3446
- status: resolveSubagentResultStatus(omitUndefinedProperties({
3447
- exitCode: result.exitCode,
3448
- interrupted: result.interrupted,
3449
- detached: result.detached,
3450
- state: result.stopped ? "stopped" : undefined,
3451
- processSignal: result.processSignal,
3452
- timedOut: result.timedOut,
3453
- stopped: result.stopped,
3454
- turnBudgetExceeded: result.turnBudgetExceeded,
3455
- })),
3456
- summary: resultSummaryForIntercom(result),
3457
- ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
3458
- ...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),
3459
- ...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),
3460
- ...(result.sessionFile ? { sessionPath: result.sessionFile } : {}),
3461
- })),
3462
- };
3463
- try {
3464
- writeParallelHandoffGroup(handoff);
3465
- const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
3466
- const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
3467
- return {
3468
- suffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n"),
3469
- reference,
3470
- };
3471
- } catch (error) {
3472
- return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
3473
- }
3474
- }
3475
-
3476
- function findDuplicateParallelOutputPath(input: {
3477
- tasks: TaskParam[];
3478
- behaviors: ResolvedStepBehavior[];
3479
- paramsCwd: string;
3480
- ctxCwd: string;
3481
- outputBaseDir: string;
3482
- worktreeSetup?: WorktreeSetup;
3483
- }): string | undefined {
3484
- const seen = new Map<string, { index: number; agent: string }>();
3485
- for (let index = 0; index < input.tasks.length; index++) {
3486
- const behavior = input.behaviors[index];
3487
- if (!behavior?.output) continue;
3488
- const task = input.tasks[index]!;
3489
- const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
3490
- const outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);
3491
- if (!outputPath) continue;
3492
- const previous = seen.get(outputPath);
3493
- if (previous) {
3494
- return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
3495
- }
3496
- seen.set(outputPath, { index, agent: task.agent });
3497
- }
3498
- return undefined;
3499
- }
3500
-
3501
- async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Promise<SingleResult[]> {
3502
- // Pre-warm fork session files sequentially before concurrent dispatch to avoid
3503
- // races where multiple workers simultaneously try to branch the same parent session.
3504
- for (let i = 0; i < input.tasks.length; i++) {
3505
- input.sessionFileForTask(input.tasks[i]!.agent, i, input.modelOverrides[i]);
3506
- }
3507
- const completedResults: SingleResult[] = [];
3508
- if (input.foregroundControl) retainForegroundSchedulingOwner(input.foregroundControl);
3509
- return mapConcurrent(input.tasks, input.concurrencyLimit, async (task, index) => {
3510
- const budgetState = usageBudgetState(input.usageBudget, sumResultsCost(completedResults));
3511
- if (budgetState?.exhausted) {
3512
- return {
3513
- index,
3514
- agent: task.agent,
3515
- task: input.taskTexts[index] ?? "(skipped)",
3516
- exitCode: 1,
3517
- messages: [],
3518
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
3519
- error: usageBudgetExceededMessage(budgetState),
3520
- skipped: true,
3521
- } as SingleResult;
3522
- }
3523
- const behavior = input.behaviors[index];
3524
- const effectiveSkills = behavior?.skills;
3525
- const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
3526
- const readInstructions = behavior
3527
- ? buildChainInstructions({ ...behavior, output: false, progress: false }, taskCwd, false)
3528
- : { prefix: "", suffix: "" };
3529
- const progressInstructions = behavior
3530
- ? buildChainInstructions({ ...behavior, output: false, reads: false }, input.progressDir, index === input.firstProgressIndex)
3531
- : { prefix: "", suffix: "" };
3532
- const outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir);
3533
- const agentConfig = input.agents.find((agent) => agent.name === task.agent);
3534
- const taskText = injectSingleOutputInstruction(
3535
- `${readInstructions.prefix}${input.taskTexts[index]!}${progressInstructions.suffix}`,
3536
- outputPath,
3537
- agentConfig,
3538
- );
3539
- const interruptController = new AbortController();
3540
- if (input.foregroundControl) {
3541
- const model = input.modelOverrides[index];
3542
- const thinking = resolveEffectiveThinking(model, input.thinkingOverrideForTask(task.agent, index, model));
3543
- beginForegroundChild(input.foregroundControl, {
3544
- index,
3545
- agent: task.agent,
3546
- authoredTask: input.taskDescriptions[index] ?? "",
3547
- effectivePrompt: taskText,
3548
- cwd: taskCwd,
3549
- ...(outputPath ? { outputPath } : {}),
3550
- rerun: { params: compactOptional<Record<string, unknown>>({
3551
- agent: task.agent,
3552
- task: input.taskDescriptions[index] ?? "",
3553
- async: false,
3554
- cwd: input.worktreeSetup ? undefined : taskCwd,
3555
- worktree: input.worktreeSetup ? true : false,
3556
- context: input.contextPolicy.contextForAgent(task.agent),
3557
- share: input.shareEnabled || undefined,
3558
- maxOutput: input.maxOutput,
3559
- timeoutMs: input.timeoutMs,
3560
- toolTimeoutMs: input.toolTimeoutMs,
3561
- configToolTimeoutMs: input.configToolTimeoutMs,
3562
- turnBudget: input.turnBudget,
3563
- ...(model ? { model } : {}),
3564
- ...(effectiveSkills !== undefined ? { skill: effectiveSkills } : {}),
3565
- ...(outputPath ? { output: outputPath } : {}),
3566
- ...(behavior?.outputMode !== undefined ? { outputMode: behavior.outputMode } : {}),
3567
- ...(behavior?.reads !== undefined ? { reads: behavior.reads } : {}),
3568
- ...(behavior?.progress !== undefined ? { progress: behavior.progress } : {}),
3569
- ...(task.toolBudget !== undefined ? { toolBudget: task.toolBudget } : {}),
3570
- ...(task.outputSchema !== undefined ? { outputSchema: task.outputSchema } : {}),
3571
- ...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),
3572
- ...(task.agentContract !== undefined || input.agentContract !== undefined ? { agentContract: task.agentContract ?? input.agentContract } : {}),
3573
- }) },
3574
- description: `${task.agent} child`,
3575
- ...(model ? { model } : {}),
3576
- ...(thinking ? { thinking } : {}),
3577
- interrupt: () => {
3578
- if (interruptController.signal.aborted) return false;
3579
- interruptController.abort();
3580
- return true;
3581
- },
3582
- });
3583
- }
3584
- const structuredRuntime = task.outputSchema
3585
- ? createStructuredOutputRuntime(task.outputSchema, path.join(input.artifactsDir, "structured-output", input.runId))
3586
- : undefined;
3587
- let detachedReceipt = false;
3588
- const result = await runSync(input.ctx.cwd, input.agents, task.agent, taskText, compactOptional<Parameters<typeof runSync>[4]>({
3589
- permissions: input.permissions,
3590
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
3591
- llmIntentArbiter: createTaskMutationArbiter(input.ctx),
3592
- ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, index),
3593
- context: input.contextPolicy.contextForAgent(task.agent),
3594
- runFanoutBudget: { ...input.runFanoutBudget, parentPath: `${input.runFanoutBudget.parentPath ? `${input.runFanoutBudget.parentPath}/` : ""}tasks[${index}]` },
3595
- cwd: taskCwd,
3596
- signal: input.signal,
3597
- interruptSignal: interruptController.signal,
3598
- allowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
3599
- intercomEvents: input.intercomEvents,
3600
- runId: input.runId,
3601
- index,
3602
- sessionDir: input.sessionDirForIndex(index),
3603
- sessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),
3604
- share: input.shareEnabled,
3605
- artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,
3606
- artifactConfig: input.artifactConfig,
3607
- maxOutput: input.maxOutput,
3608
- outputPath,
3609
- outputMode: behavior?.outputMode,
3610
- maxSubagentDepth: input.maxSubagentDepths[index],
3611
- waitToolEnabled: input.waitToolEnabled,
3612
- capabilityCeiling: input.capabilityCeiling,
3613
- controlConfig: input.controlConfig,
3614
- onControlEvent: input.onControlEvent,
3615
- onDetachedExit: (result) => {
3616
- try {
3617
- updateRememberedForegroundChild(input.state, { runId: input.runId, mode: "parallel", cwd: taskCwd, sessionId: input.parentSessionId, index, result, events: input.intercomEvents });
3618
- } finally {
3619
- try {
3620
- if (input.foregroundControl) finishForegroundChild(input.foregroundControl, index);
3621
- } finally {
3622
- removeForegroundControlIfIdle(input.state, input.runId);
3623
- }
3624
- }
3625
- },
3626
- intercomSessionName: input.childIntercomTarget?.(task.agent, index),
3627
- orchestratorIntercomTarget: input.orchestratorIntercomTarget,
3628
- nestedRoute: input.foregroundControl?.nestedRoute,
3629
- modelOverride: input.modelOverrides[index],
3630
- thinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),
3631
- availableModels: input.availableModels,
3632
- preferredModelProvider: input.parentModel?.provider,
3633
- modelScope: input.modelScope,
3634
- skills: effectiveSkills === false ? [] : effectiveSkills,
3635
- structuredOutput: structuredRuntime,
3636
- agentContract: task.agentContract ?? input.agentContract,
3637
- acceptance: task.acceptance,
3638
- acceptanceContext: { mode: "parallel" },
3639
- onEffectivePrompt: input.foregroundControl ? (prompt) => updateLiveEffectivePrompt(input.foregroundControl!, index, prompt) : undefined,
3640
- timeoutMs: input.timeoutMs,
3641
- toolTimeoutMs: input.toolTimeoutMs,
3642
- configToolTimeoutMs: input.configToolTimeoutMs,
3643
- deadlineAt: input.deadlineAt,
3644
- turnBudget: input.turnBudget,
3645
- toolBudget: input.toolBudgets[index],
3646
- onUpdate: input.onUpdate
3647
- ? (progressUpdate) => {
3648
- const stepResults = progressUpdate.details?.results || [];
3649
- const stepProgress = progressUpdate.details?.progress || [];
3650
- if (input.foregroundControl && stepProgress.length > 0) {
3651
- updateForegroundChild(input.foregroundControl, index, stepProgress[0]);
3652
- }
3653
- if (stepResults.length > 0) input.liveResults[index] = stepResults[0];
3654
- if (stepProgress.length > 0) input.liveProgress[index] = stepProgress[0];
3655
- const mergedResults = input.liveResults.filter((result): result is SingleResult => result !== undefined);
3656
- const mergedProgress = input.liveProgress.filter((progress): progress is AgentProgress => progress !== undefined);
3657
- input.onUpdate?.({
3658
- content: progressUpdate.content,
3659
- details: compactOptional<Details>({
3660
- mode: "parallel",
3661
- results: mergedResults,
3662
- progress: mergedProgress,
3663
- controlEvents: progressUpdate.details?.controlEvents,
3664
- totalSteps: input.tasks.length,
3665
- }),
3666
- });
3667
- }
3668
- : undefined,
3669
- })).then((result) => {
3670
- detachedReceipt = result.detached === true;
3671
- return result;
3672
- }).finally(() => {
3673
- // mapConcurrent rejects before siblings settle, so every attached child
3674
- // attempts idle removal after releasing its own control. Detached receipts
3675
- // transfer both responsibilities to the authoritative exit callback.
3676
- if (!detachedReceipt) {
3677
- if (input.foregroundControl) finishForegroundChild(input.foregroundControl, index);
3678
- removeForegroundControlIfIdle(input.state, input.runId);
3679
- }
3680
- });
3681
- completedResults.push(result);
3682
- return result;
3683
- }, input.globalSemaphore, () => {
3684
- if (input.foregroundControl) settleForegroundSchedulingOwner(input.foregroundControl);
3685
- removeForegroundControlIfIdle(input.state, input.runId);
3686
- });
3687
- }
3688
-
3689
- async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {
3690
- const {
3691
- params,
3692
- effectiveCwd,
3693
- agents,
3694
- ctx,
3695
- signal,
3696
- runId,
3697
- sessionDirForIndex,
3698
- sessionFileForIndex,
3699
- sessionFileForTask,
3700
- thinkingOverrideForTask,
3701
- shareEnabled,
3702
- artifactConfig,
3703
- artifactsDir,
3704
- backgroundRequestedWhileClarifying,
3705
- onUpdate,
3706
- sessionRoot,
3707
- controlConfig,
3708
- contextPolicy,
3709
- } = data;
3710
- const onControlEvent = createForegroundControlNotifier(data, deps);
3711
- const childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;
3712
- const allProgress: AgentProgress[] = [];
3713
- const allArtifactPaths: ArtifactPaths[] = [];
3714
- const tasks = params.tasks!;
3715
- const maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
3716
- const parallelConcurrency = resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency);
3717
-
3718
- if (tasks.length > maxParallelTasks)
3719
- return {
3720
- content: [{ type: "text", text: `Max ${maxParallelTasks} tasks` }],
3721
- isError: true,
3722
- details: { mode: "parallel" as const, results: [] },
3723
- };
3724
-
3725
- const agentConfigs: AgentConfig[] = [];
3726
- for (const t of tasks) {
3727
- const config = agents.find((a) => a.name === t.agent);
3728
- if (!config) {
3729
- return {
3730
- content: [{ type: "text", text: `Unknown agent: ${t.agent}` }],
3731
- isError: true,
3732
- details: { mode: "parallel" as const, results: [] },
3733
- };
3734
- }
3735
- agentConfigs.push(config);
3736
- }
3737
-
3738
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3739
- const maxSubagentDepths = agentConfigs.map((config) =>
3740
- resolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth),
3741
- );
3742
- const toolBudgets: (ResolvedToolBudget | undefined)[] = [];
3743
- for (let index = 0; index < tasks.length; index++) {
3744
- const resolved = resolveEffectiveToolBudget(omitUndefinedProperties({ stepBudget: tasks[index]?.toolBudget, runBudget: data.toolBudget, agentBudget: agentConfigs[index]?.toolBudget, configBudget: data.configToolBudget }));
3745
- if (resolved.error) return buildParallelModeError(resolved.error);
3746
- toolBudgets.push(resolved.toolBudget);
3747
- }
3748
-
3749
- if (params.worktree) {
3750
- const worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);
3751
- if (worktreeTaskCwdError) return buildParallelModeError(worktreeTaskCwdError);
3752
- }
3753
-
3754
- const parentModel = data.parentModel;
3755
- const currentProvider = parentModel?.provider;
3756
- const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3757
- let taskTexts = tasks.map((t) => t.task);
3758
- const skillOverrides: (string[] | false | undefined)[] = tasks.map((t) =>
3759
- normalizeSkillInput(t.skill),
3760
- );
3761
- const behaviorOverrides: StepOverrides[] = tasks.map((task, index) => ({
3762
- ...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),
3763
- ...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),
3764
- ...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),
3765
- ...(task.progress !== undefined ? { progress: task.progress } : {}),
3766
- ...(skillOverrides[index] !== undefined ? { skills: skillOverrides[index] } : {}),
3767
- ...(task.model !== undefined ? { model: task.model } : {}),
3768
- }));
3769
- const modelOverrides: (string | undefined)[] = tasks.map((_, i) =>
3770
- agentConfigs[i]?.runner?.type === "external-cli"
3771
- ? undefined
3772
- : resolveEffectiveSubagentModel(behaviorOverrides[i]?.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope }),
3773
- );
3774
-
3775
- if (params.clarify === true && ctx.hasUI) {
3776
- const behaviors = agentConfigs.map((c, i) =>
3777
- resolveStepBehavior(c, behaviorOverrides[i]!),
3778
- );
3779
- const availableSkills = discoverAvailableSkills(effectiveCwd);
3780
-
3781
- const result = await ctx.ui.custom<ChainClarifyResult>(
3782
- (tui, theme, _kb, done) =>
3783
- new ChainClarifyComponent(
3784
- tui, theme,
3785
- agentConfigs,
3786
- taskTexts,
3787
- "",
3788
- undefined,
3789
- behaviors,
3790
- availableModels,
3791
- currentProvider,
3792
- availableSkills,
3793
- done,
3794
- "parallel",
3795
- ),
3796
- { overlay: true, overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" } },
3797
- );
3798
-
3799
- if (!result || !result.confirmed) {
3800
- return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "parallel", results: [] } };
3801
- }
3802
-
3803
- taskTexts = result.templates;
3804
- for (let i = 0; i < result.behaviorOverrides.length; i++) {
3805
- const override = result.behaviorOverrides[i];
3806
- if (override?.model !== undefined) {
3807
- modelOverrides[i] = agentConfigs[i]?.runner?.type === "external-cli"
3808
- ? undefined
3809
- : resolveEffectiveSubagentModel(override.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
3810
- behaviorOverrides[i]!.model = override.model;
3811
- }
3812
- if (override?.output !== undefined) behaviorOverrides[i]!.output = override.output;
3813
- if (override?.reads !== undefined) behaviorOverrides[i]!.reads = override.reads;
3814
- if (override?.progress !== undefined) behaviorOverrides[i]!.progress = override.progress;
3815
- if (override?.skills !== undefined) {
3816
- skillOverrides[i] = override.skills;
3817
- behaviorOverrides[i]!.skills = override.skills;
3818
- }
3819
- }
3820
-
3821
- if (result.runInBackground) {
3822
- if (!isAsyncAvailable()) {
3823
- return {
3824
- content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
3825
- isError: true,
3826
- details: { mode: "parallel" as const, results: [] },
3827
- };
3828
- }
3829
- const id = data.asyncRunId;
3830
- const capacity = acquireClarifiedBackgroundCapacity(data, deps, "parallel", id);
3831
- if (capacity.errorResult) return capacity.errorResult;
3832
- const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3833
- pi: deps.pi,
3834
- cwd: ctx.cwd,
3835
- currentSessionId: data.parentSessionId!,
3836
- parentSessionId: data.parentPiSessionId,
3837
- currentModelProvider: parentModel?.provider,
3838
- currentModel: parentModel,
3839
- modelScope: data.modelScope,
3840
- interactive: ctx.hasUI,
3841
- permissions: deps.config.permissions,
3842
- });
3843
- const parallelTasks = tasks.map((t, i) => {
3844
- const taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]!) : taskTexts[i]!;
3845
- const progress = taskDisallowsFileUpdates(taskText) ? false : behaviorOverrides[i]?.progress;
3846
- return compactOptional<ParallelTaskItem>({
3847
- agent: t.agent,
3848
- task: taskText,
3849
- cwd: t.cwd,
3850
- ...(behaviorOverrides[i]?.model !== undefined ? { model: behaviorOverrides[i]!.model } : {}),
3851
- ...(skillOverrides[i] !== undefined ? { skill: skillOverrides[i] } : {}),
3852
- ...(behaviorOverrides[i]?.output !== undefined ? { output: behaviorOverrides[i]!.output } : {}),
3853
- ...(behaviorOverrides[i]?.outputMode !== undefined ? { outputMode: behaviorOverrides[i]!.outputMode } : {}),
3854
- ...(behaviorOverrides[i]?.reads !== undefined ? { reads: behaviorOverrides[i]!.reads } : {}),
3855
- ...(progress !== undefined ? { progress } : {}),
3856
- ...(t.toolBudget !== undefined ? { toolBudget: t.toolBudget } : {}),
3857
- ...(t.outputSchema !== undefined ? { outputSchema: t.outputSchema } : {}),
3858
- ...(t.acceptance !== undefined ? { acceptance: t.acceptance } : {}),
3859
- ...(t.agentContract !== undefined ? { agentContract: t.agentContract } : {}),
3860
- });
3861
- });
3862
- try {
3863
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3864
- chain: [compactOptional<ParallelStep>({ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree })],
3865
- resultMode: "parallel",
3866
- goal: taskTexts[0] ?? "",
3867
- agents,
3868
- ctx: asyncCtx,
3869
- availableModels,
3870
- cwd: effectiveCwd,
3871
- maxOutput: params.maxOutput,
3872
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3873
- artifactConfig,
3874
- shareEnabled,
3875
- sessionRoot,
3876
- chainSkills: [],
3877
- activeAsyncCapacity: capacity.activeAsyncCapacity,
3878
- sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
3879
- thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
3880
- contextForAgent: contextPolicy.contextForAgent,
3881
- maxSubagentDepth: currentMaxSubagentDepth,
3882
- waitToolEnabled: deps.waitToolEnabled,
3883
- worktreeSetupHook: deps.config.worktreeSetupHook,
3884
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3885
- worktreeBaseDir: deps.config.worktreeBaseDir,
3886
- controlConfig,
3887
- agentContract: params.agentContract,
3888
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3889
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3890
- nestedRoute: data.nestedRoute,
3891
- timeoutMs: data.timeoutMs,
3892
- turnBudget: data.turnBudget,
3893
- usageBudget: data.usageBudget,
3894
- toolBudget: data.toolBudget,
3895
- configToolBudget: data.configToolBudget,
3896
- callToolTimeoutMs: data.params?.toolTimeoutMs,
3897
- configToolTimeoutMs: data.configToolTimeoutMs,
3898
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3899
- runFanoutBudget: data.runFanoutBudget,
3900
- }));
3901
- } finally {
3902
- finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3903
- }
3904
- }
3905
- }
3906
-
3907
- const behaviors = tasks.map((task, index) => {
3908
- let behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agentConfigs[index]!, behaviorOverrides[index]!), taskTexts[index]);
3909
- if (behaviorOverrides[index]?.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output)) {
3910
- behavior = { ...behavior, output: path.join("parallel-0", `${index}-${task.agent}`, behavior.output) };
3911
- }
3912
- return behavior;
3913
- });
3914
- const firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress);
3915
- const liveResults: (SingleResult | undefined)[] = new Array(tasks.length).fill(undefined);
3916
- const liveProgress: (AgentProgress | undefined)[] = new Array(tasks.length).fill(undefined);
3917
- const foregroundControl = deps.state.foregroundControls.get(runId);
3918
- const { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(
3919
- params.worktree,
3920
- effectiveCwd,
3921
- runId,
3922
- tasks,
3923
- deps.config.worktreeSetupHook,
3924
- deps.config.worktreeSetupHookTimeoutMs,
3925
- deps.config.worktreeBaseDir,
3926
- );
3927
- if (errorResult) return errorResult;
3928
-
3929
- let worktreeCleanupHandled = false;
3930
- let pendingHandoff: Details["parallelHandoff"];
3931
- try {
3932
- if (worktreeSetup) {
3933
- pendingHandoff = writePendingParallelHandoff({
3934
- manifestPath: parallelHandoffPath(artifactsDir, runId),
3935
- runId,
3936
- mode: "parallel",
3937
- source: "foreground",
3938
- cwd: effectiveCwd,
3939
- stepIndex: 0,
3940
- flatStartIndex: 0,
3941
- setup: worktreeSetup,
3942
- });
3943
- }
3944
- const outputBaseDir = path.join(artifactsDir, "outputs", runId);
3945
- const duplicateOutputError = findDuplicateParallelOutputPath(omitUndefinedProperties({
3946
- tasks,
3947
- behaviors,
3948
- paramsCwd: effectiveCwd,
3949
- ctxCwd: ctx.cwd,
3950
- outputBaseDir,
3951
- worktreeSetup,
3952
- }));
3953
- if (duplicateOutputError) return buildParallelModeError(duplicateOutputError);
3954
- for (let index = 0; index < tasks.length; index++) {
3955
- const taskCwd = resolveParallelTaskCwd(tasks[index]!, effectiveCwd, worktreeSetup, index);
3956
- const outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir);
3957
- const validationError = validateFileOnlyOutputMode(behaviors[index]?.outputMode, outputPath, `Parallel task ${index + 1} (${tasks[index]!.agent})`);
3958
- if (validationError) return buildParallelModeError(validationError);
3959
- }
3960
-
3961
- const parallelProgressPrecreated = firstProgressIndex !== -1;
3962
- const parallelProgressDir = path.join(artifactsDir, "progress", runId);
3963
- if (parallelProgressPrecreated) writeInitialProgressFile(parallelProgressDir);
3964
-
3965
- const taskDescriptions = taskTexts.map((taskText) => taskText.trim());
3966
- for (let i = 0; i < taskTexts.length; i++) {
3967
- if (shouldForkAgent(contextPolicy, tasks[i]!.agent)) taskTexts[i] = wrapForkTask(taskTexts[i]!);
3968
- }
3969
-
3970
- const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
3971
- const results = await runForegroundParallelTasks(compactOptional<ForegroundParallelRunInput>({
3972
- tasks,
3973
- permissions: deps.config.permissions,
3974
- taskTexts,
3975
- taskDescriptions,
3976
- agents,
3977
- ctx,
3978
- state: deps.state,
3979
- intercomEvents: deps.pi.events,
3980
- parentSessionId: data.parentSessionId,
3981
- capabilityCeiling: data.capabilityCeiling,
3982
- runFanoutBudget: data.runFanoutBudget,
3983
- signal,
3984
- runId,
3985
- sessionDirForIndex,
3986
- sessionFileForIndex,
3987
- sessionFileForTask,
3988
- thinkingOverrideForTask,
3989
- shareEnabled,
3990
- artifactConfig,
3991
- artifactsDir,
3992
- outputBaseDir,
3993
- maxOutput: params.maxOutput,
3994
- paramsCwd: effectiveCwd,
3995
- progressDir: parallelProgressDir,
3996
- availableModels,
3997
- modelScope: data.modelScope,
3998
- parentModel,
3999
- modelOverrides,
4000
- behaviors,
4001
- firstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,
4002
- controlConfig,
4003
- contextPolicy,
4004
- onControlEvent,
4005
- childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : undefined,
4006
- orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
4007
- foregroundControl,
4008
- concurrencyLimit: parallelConcurrency,
4009
- globalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),
4010
- maxSubagentDepths,
4011
- waitToolEnabled: deps.waitToolEnabled,
4012
- liveResults,
4013
- liveProgress,
4014
- onUpdate,
4015
- worktreeSetup,
4016
- timeoutMs: data.timeoutMs,
4017
- deadlineAt,
4018
- toolTimeoutMs: data.params?.toolTimeoutMs,
4019
- configToolTimeoutMs: data.configToolTimeoutMs,
4020
- turnBudget: data.turnBudget,
4021
- usageBudget: data.usageBudget,
4022
- toolBudgets,
4023
- agentContract: params.agentContract,
4024
- }));
4025
- for (let i = 0; i < results.length; i++) {
4026
- const run = results[i]!;
4027
- recordRun(run.agent, taskTexts[i]!, run.exitCode, run.progressSummary?.durationMs ?? 0);
4028
- }
3055
+ const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3056
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3057
+ const agents = input.discoverAgents(childCwd, agentScope).agents;
3058
+ const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3059
+ const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3060
+ const output = rawOutput === true || rawOutput === "true"
3061
+ ? agentOutput
3062
+ : hasExplicitOutput
3063
+ ? rawOutput
3064
+ : input.aggregateOutputPath
3065
+ ? workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key)
3066
+ : agentOutput;
3067
+ return {
3068
+ path: resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir),
3069
+ inherited: !hasExplicitOutput && !input.aggregateOutputPath && agentOutput !== undefined,
3070
+ };
3071
+ }
4029
3072
 
4030
- for (const result of results) {
4031
- if (result.progress) allProgress.push(result.progress);
4032
- if (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);
3073
+ function workflowChildOutputClaims(input: {
3074
+ ctxCwd: string;
3075
+ workflowCwd: string;
3076
+ artifactsDir: string;
3077
+ workflowRunId: string;
3078
+ aggregateOutputPath?: string;
3079
+ configuredOutputBaseDir?: string;
3080
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3081
+ workflowAgentScope?: unknown;
3082
+ state: SubagentState;
3083
+ claimedOutputPaths: Map<string, string>;
3084
+ entries: Array<{ key: string; params: Record<string, unknown> }>;
3085
+ }): { error?: string; claims?: Map<string, string>; overrides?: Map<string, string> } {
3086
+ const resolvedEntries = input.entries.map(({ key, params }) => ({
3087
+ key,
3088
+ ...resolveWorkflowChildOutputPath({ ...input, key, params }),
3089
+ }));
3090
+ const paths = new Map<string, number>();
3091
+ for (const claimedPath of input.claimedOutputPaths.keys()) paths.set(claimedPath, 1);
3092
+ for (const { path: resolved } of resolvedEntries) {
3093
+ if (resolved) paths.set(resolved, (paths.get(resolved) ?? 0) + 1);
3094
+ }
3095
+ const overrides = new Map<string, string>();
3096
+ for (const entry of resolvedEntries) {
3097
+ if (entry.inherited && entry.path && (paths.get(entry.path) ?? 0) > 1) {
3098
+ const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3099
+ overrides.set(entry.key, output);
3100
+ entry.path = output;
4033
3101
  }
3102
+ }
3103
+ const claims = new Map(input.claimedOutputPaths);
3104
+ for (const { key, path: resolved } of resolvedEntries) {
3105
+ if (!resolved) continue;
3106
+ const previous = claims.get(resolved);
3107
+ if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3108
+ claims.set(resolved, key);
3109
+ }
3110
+ return { claims, overrides };
3111
+ }
4034
3112
 
4035
- if (foregroundControl) {
4036
- updateForegroundNestedProjection(foregroundControl);
4037
- attachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren);
4038
- }
4039
- const detached = results.find((result) => result.detached);
4040
- let handoff: ReturnType<typeof finalizeParallelWorktreeHandoff> | undefined;
4041
- if (worktreeSetup) {
4042
- worktreeCleanupHandled = true;
4043
- handoff = detached
4044
- ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
4045
- : finalizeParallelWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: effectiveCwd, tasks, results });
4046
- }
4047
- const interrupted = results.find((result) => result.interrupted);
4048
- const totalCost = sumResultsCost(results);
4049
- const details = compactForegroundDetails(compactOptional<Details>({
4050
- mode: "parallel",
4051
- runId,
4052
- timeoutMs: data.timeoutMs,
4053
- results,
4054
- progress: params.includeProgress ? allProgress : undefined,
4055
- artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
4056
- totalChildUsage: sumResultsUsage(results),
4057
- totalCost,
4058
- usageBudget: usageBudgetState(data.usageBudget, totalCost),
4059
- ...(handoff?.reference ? { parallelHandoff: handoff.reference } : {}),
4060
- }));
4061
- rememberForegroundRun(deps.state, { runId, mode: "parallel", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results });
4062
- if (interrupted) {
4063
- return {
4064
- content: [{ type: "text", text: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.` }],
4065
- details,
4066
- };
4067
- }
4068
- if (detached) {
4069
- const handoffSuffix = handoff?.suffix ? `\n\n${handoff.suffix}` : "";
4070
- return {
4071
- content: [{ type: "text", text: `Parallel run detached for intercom coordination (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.${handoffSuffix}` }],
4072
- details,
4073
- };
4074
- }
3113
+ function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
3114
+ target.clear();
3115
+ for (const [resolved, key] of claims) target.set(resolved, key);
3116
+ }
4075
3117
 
4076
- const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results });
4077
- if (foregroundControl) updateForegroundNestedProjection(foregroundControl);
4078
- if (!suppressRoutineResultIntercom) {
4079
- const intercomReceipt = await maybeBuildForegroundIntercomReceipt({
4080
- pi: deps.pi,
4081
- intercomBridge: data.intercomBridge,
4082
- runId,
4083
- mode: "parallel",
4084
- details,
4085
- ...(params.workflowParentRunId !== undefined ? { preserveDetailsOutputs: true } : {}),
4086
- ...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),
4087
- });
4088
- if (intercomReceipt) {
4089
- return {
4090
- content: [{ type: "text", text: intercomReceipt.text }],
4091
- details: intercomReceipt.details,
4092
- };
4093
- }
4094
- }
3118
+ function prepareWorkflowChildLaunchParams(input: {
3119
+ workflowDefaults: SubagentParamsLike;
3120
+ childParams: Record<string, unknown>;
3121
+ parentWorkflowRunId: string;
3122
+ workflowKey: string;
3123
+ ctxCwd: string;
3124
+ workflowCwd: string;
3125
+ artifactsDir: string;
3126
+ aggregateOutputPath?: string;
3127
+ configuredOutputBaseDir?: string;
3128
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3129
+ workflowAgentScope?: unknown;
3130
+ outputOverride?: string;
3131
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number };
3132
+ }): SubagentParamsLike {
3133
+ let childParams = input.childParams;
3134
+ if (input.childParams.output === undefined && input.childParams.resume === undefined && input.outputOverride !== undefined) {
3135
+ childParams = { ...input.childParams, output: input.outputOverride };
3136
+ } else if (input.childParams.output === undefined && input.childParams.resume === undefined && input.aggregateOutputPath !== undefined) {
3137
+ childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3138
+ } else if (input.childParams.resume === undefined) {
3139
+ const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
3140
+ if (resolvedOutput.path) childParams = { ...input.childParams, output: resolvedOutput.path };
3141
+ }
3142
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
3143
+ }
4095
3144
 
4096
- const worktreeSuffix = handoff?.suffix ?? "";
4097
- const ok = results.filter((result) => result.exitCode === 0).length;
4098
- const downgradeNote = backgroundRequestedWhileClarifying ? " (background requested, but clarify kept this run foreground)" : "";
4099
- const aggregatedOutput = aggregateParallelOutputs(
4100
- results.map((result) => ({
4101
- agent: result.agent,
4102
- output: result.truncation?.text || getSingleResultOutput(result),
4103
- exitCode: result.exitCode,
4104
- ...(result.error === undefined ? {} : { error: result.error }),
4105
- ...(result.timedOut === undefined ? {} : { timedOut: result.timedOut }),
3145
+ function finalizeSingleWorktreeHandoff(input: {
3146
+ worktreeSetup: WorktreeSetup;
3147
+ artifactsDir: string;
3148
+ runId: string;
3149
+ cwd: string;
3150
+ agent: string;
3151
+ result: SingleResult;
3152
+ }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3153
+ const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3154
+ const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
3155
+ const diffSummary = formatWorktreeDiffSummary(diffs);
3156
+ const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
3157
+ const handoff = {
3158
+ manifestPath,
3159
+ runId: input.runId,
3160
+ mode: "single" as const,
3161
+ source: "foreground" as const,
3162
+ cwd: input.cwd,
3163
+ stepIndex: 0,
3164
+ flatStartIndex: 0,
3165
+ setup: input.worktreeSetup,
3166
+ diffs,
3167
+ results: [{
3168
+ agent: input.result.agent,
3169
+ status: resolveSubagentResultStatus(omitUndefinedProperties({
3170
+ exitCode: input.result.exitCode,
3171
+ interrupted: input.result.interrupted,
3172
+ detached: input.result.detached,
3173
+ state: input.result.stopped ? "stopped" : undefined,
3174
+ processSignal: input.result.processSignal,
3175
+ timedOut: input.result.timedOut,
3176
+ stopped: input.result.stopped,
3177
+ turnBudgetExceeded: input.result.turnBudgetExceeded,
4106
3178
  })),
4107
- (i, agent) => `=== Task ${i + 1}: ${agent} ===`,
4108
- );
4109
-
4110
- const summary = `${ok}/${results.length} succeeded${downgradeNote}`;
4111
- const fullContent = worktreeSuffix
4112
- ? `${summary}\n\n${aggregatedOutput}\n\n${worktreeSuffix}`
4113
- : `${summary}\n\n${aggregatedOutput}`;
4114
-
3179
+ summary: resultSummaryForIntercom(input.result),
3180
+ ...(input.result.artifactPaths?.outputPath ? { outputPath: input.result.artifactPaths.outputPath } : {}),
3181
+ ...(input.result.structuredOutput !== undefined ? { structuredOutput: input.result.structuredOutput } : {}),
3182
+ ...(input.result.structuredOutputPath ? { structuredOutputPath: input.result.structuredOutputPath } : {}),
3183
+ ...(input.result.sessionFile ? { sessionPath: input.result.sessionFile } : {}),
3184
+ }],
3185
+ };
3186
+ try {
3187
+ writeParallelHandoffGroup(handoff);
3188
+ const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
3189
+ const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
4115
3190
  return {
4116
- content: [{ type: "text", text: fullContent }],
4117
- details,
3191
+ suffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n"),
3192
+ reference,
4118
3193
  };
4119
- } finally {
4120
- if (worktreeSetup && !worktreeCleanupHandled) cleanupWorktrees(worktreeSetup);
3194
+ } catch (error) {
3195
+ return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
4121
3196
  }
4122
3197
  }
4123
3198
 
@@ -4141,7 +3216,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4141
3216
  contextPolicy,
4142
3217
  } = data;
4143
3218
  const onControlEvent = createForegroundControlNotifier(data, deps);
4144
- const childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget(runId, params.agent!, 0) : undefined;
3219
+ const childBridgeActive = intercomBridgeAppliesToAgent(data.intercomBridge, contextPolicy, params.agent!);
3220
+ const childIntercomTarget = childBridgeActive ? resolveSubagentIntercomTarget(runId, params.agent!, 0) : undefined;
4145
3221
  const allProgress: AgentProgress[] = [];
4146
3222
  const allArtifactPaths: ArtifactPaths[] = [];
4147
3223
  const agentConfig = agents.find((a) => a.name === params.agent);
@@ -4167,117 +3243,44 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4167
3243
  currentProvider,
4168
3244
  data.modelScope === undefined ? {} : { scope: data.modelScope },
4169
3245
  );
3246
+ const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, agentConfig.model, parentModel);
4170
3247
  let skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);
4171
3248
  let readsOverride: string[] | false | undefined = params.reads;
4172
3249
  const rawOutput = params.output !== undefined ? params.output : agentConfig.output;
4173
3250
  let effectiveOutput = normalizeSingleOutputOverride(rawOutput, agentConfig.output);
4174
- const effectiveOutputMode = params.outputMode ?? "inline";
3251
+ const effectiveOutputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
4175
3252
  const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
4176
3253
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
4177
3254
 
4178
- if (params.clarify === true && ctx.hasUI) {
4179
- const behavior = resolveStepBehavior(agentConfig, omitUndefinedProperties({ output: effectiveOutput, skills: skillOverride }));
4180
- const availableSkills = discoverAvailableSkills(effectiveCwd);
4181
-
4182
- const result = await ctx.ui.custom<ChainClarifyResult>(
4183
- (tui, theme, _kb, done) =>
4184
- new ChainClarifyComponent(
4185
- tui, theme,
4186
- [agentConfig],
4187
- [task],
4188
- task,
4189
- undefined,
4190
- [behavior],
4191
- availableModels,
4192
- currentProvider,
4193
- availableSkills,
4194
- done,
4195
- "single",
4196
- ),
4197
- { overlay: true, overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" } },
4198
- );
4199
-
4200
- if (!result || !result.confirmed) {
4201
- return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "single", results: [] } };
4202
- }
4203
-
4204
- task = result.templates[0]!;
4205
- const override = result.behaviorOverrides[0];
4206
- if (override?.model !== undefined) modelOverride = resolveEffectiveSubagentModel(override.model, agentConfig.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
4207
- if (override?.output !== undefined) effectiveOutput = normalizeSingleOutputOverride(override.output, agentConfig.output);
4208
- if (override?.skills !== undefined) skillOverride = override.skills;
4209
- if (override?.reads !== undefined) readsOverride = override.reads;
4210
3255
 
4211
- if (result.runInBackground) {
4212
- if (!isAsyncAvailable()) {
4213
- return {
4214
- content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
4215
- isError: true,
4216
- details: { mode: "single" as const, results: [] },
4217
- };
4218
- }
4219
- const id = data.asyncRunId;
4220
- const capacity = acquireClarifiedBackgroundCapacity(data, deps, "single", id);
4221
- if (capacity.errorResult) return capacity.errorResult;
4222
- const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
4223
- pi: deps.pi,
4224
- cwd: ctx.cwd,
4225
- currentSessionId: data.parentSessionId!,
4226
- parentSessionId: data.parentPiSessionId,
4227
- currentModelProvider: parentModel?.provider,
4228
- currentModel: parentModel,
4229
- modelScope: data.modelScope,
4230
- interactive: ctx.hasUI,
4231
- permissions: deps.config.permissions,
3256
+ const sourceCwd = effectiveCwd;
3257
+ const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3258
+ params.worktree,
3259
+ sourceCwd,
3260
+ runId,
3261
+ params.agent!,
3262
+ deps.config.worktreeSetupHook,
3263
+ deps.config.worktreeSetupHookTimeoutMs,
3264
+ deps.config.worktreeBaseDir,
3265
+ );
3266
+ if (worktreeSetupError) return worktreeSetupError;
3267
+ const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3268
+ let pendingHandoff: Details["parallelHandoff"];
3269
+ if (worktreeSetup) {
3270
+ try {
3271
+ pendingHandoff = writePendingParallelHandoff({
3272
+ manifestPath: parallelHandoffPath(artifactsDir, runId),
3273
+ runId,
3274
+ mode: "single",
3275
+ source: "foreground",
3276
+ cwd: sourceCwd,
3277
+ stepIndex: 0,
3278
+ flatStartIndex: 0,
3279
+ setup: worktreeSetup,
4232
3280
  });
4233
- try {
4234
- return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
4235
- agent: params.agent!,
4236
- task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,
4237
- goal: task,
4238
- agentConfig,
4239
- recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
4240
- ctx: asyncCtx,
4241
- availableModels,
4242
- cwd: effectiveCwd,
4243
- maxOutput: params.maxOutput,
4244
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4245
- artifactConfig,
4246
- shareEnabled,
4247
- activeAsyncCapacity: capacity.activeAsyncCapacity,
4248
- sessionRoot,
4249
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
4250
- context: contextPolicy.contextForAgent(params.agent!),
4251
- skills: skillOverride === false ? [] : skillOverride,
4252
- output: effectiveOutput,
4253
- outputMode: effectiveOutputMode,
4254
- ...(readsOverride !== undefined ? { reads: readsOverride } : {}),
4255
- outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
4256
- modelOverride,
4257
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
4258
- maxSubagentDepth,
4259
- waitToolEnabled: deps.waitToolEnabled,
4260
- worktreeSetupHook: deps.config.worktreeSetupHook,
4261
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
4262
- worktreeBaseDir: deps.config.worktreeBaseDir,
4263
- controlConfig,
4264
- intercomBridge: params.intercomBridge,
4265
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
4266
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
4267
- nestedRoute: data.nestedRoute,
4268
- agentContract: params.agentContract,
4269
- structuredOutputSchema: params.outputSchema,
4270
- acceptance: params.acceptance,
4271
- timeoutMs: data.timeoutMs,
4272
- turnBudget: data.turnBudget,
4273
- toolBudget: effectiveToolBudget.toolBudget,
4274
- usageBudget: data.usageBudget,
4275
- allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4276
- runFanoutBudget: data.runFanoutBudget,
4277
- }));
4278
- } finally {
4279
- finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
4280
- }
3281
+ } catch (error) {
3282
+ cleanupWorktrees(worktreeSetup);
3283
+ return { content: [{ type: "text", text: formatParallelHandoffError(error) }], isError: true, details: { mode: "single", results: [] } };
4281
3284
  }
4282
3285
  }
4283
3286
 
@@ -4286,9 +3289,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4286
3289
  task = wrapForkTask(task);
4287
3290
  }
4288
3291
  const cleanTask = task;
4289
- const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, effectiveCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId));
3292
+ const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, singleCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId));
4290
3293
  const validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`);
4291
3294
  if (validationError) {
3295
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4292
3296
  return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
4293
3297
  }
4294
3298
  const structuredRuntime = params.outputSchema
@@ -4297,7 +3301,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4297
3301
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
4298
3302
  // absolute paths pass through; relative paths resolve against the child cwd.
4299
3303
  const reads = readsOverride !== undefined ? readsOverride : agentConfig.defaultReads ?? false;
4300
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, effectiveCwd) : [];
3304
+ const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, singleCwd) : [];
4301
3305
  const readsInstruction = readPaths.length > 0
4302
3306
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
4303
3307
  : "";
@@ -4314,13 +3318,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4314
3318
  let detachForeground: ((reason?: string) => boolean) | undefined;
4315
3319
  const foregroundControl = deps.state.foregroundControls.get(runId);
4316
3320
  if (foregroundControl) {
4317
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride));
3321
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent));
4318
3322
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
4319
3323
  index: 0,
4320
3324
  agent: params.agent!,
4321
3325
  authoredTask,
4322
3326
  effectivePrompt: task,
4323
- cwd: effectiveCwd,
3327
+ cwd: singleCwd,
4324
3328
  outputPath,
4325
3329
  rerun: { params: { ...params, task: authoredTask, async: params.async ?? false } },
4326
3330
  description: foregroundControl.description,
@@ -4352,14 +3356,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4352
3356
  ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
4353
3357
  context: data.contextPolicy.contextForAgent(params.agent!),
4354
3358
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
4355
- cwd: effectiveCwd,
3359
+ cwd: singleCwd,
4356
3360
  signal,
4357
3361
  interruptSignal: interruptController.signal,
4358
3362
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
4359
3363
  intercomEvents: deps.pi.events,
4360
3364
  runId,
4361
3365
  sessionDir: sessionDirForIndex(0),
4362
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
3366
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
4363
3367
  share: shareEnabled,
4364
3368
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4365
3369
  artifactConfig,
@@ -4372,11 +3376,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4372
3376
  controlConfig,
4373
3377
  onControlEvent,
4374
3378
  intercomSessionName: childIntercomTarget,
4375
- orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3379
+ orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : undefined,
4376
3380
  nestedRoute: foregroundControl?.nestedRoute,
4377
3381
  index: 0,
4378
3382
  modelOverride,
4379
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
3383
+ modelOverrideFromParent,
3384
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
4380
3385
  availableModels,
4381
3386
  preferredModelProvider: currentProvider,
4382
3387
  modelScope: data.modelScope,
@@ -4392,10 +3397,21 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4392
3397
  onDetachedExit: (result) => {
4393
3398
  try {
4394
3399
  try {
4395
- updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: effectiveCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: params.workflowParentRunId === undefined });
3400
+ updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
4396
3401
  } catch {
4397
3402
  // Remembered foreground state is best-effort; run history and cleanup must still complete.
4398
3403
  }
3404
+ const workflowParentRunId = params.workflowParentRunId ?? foregroundControl?.parentWorkflowRunId;
3405
+ if (workflowParentRunId) {
3406
+ reconcileDetachedWorkflowChildCompletion({
3407
+ state: deps.state,
3408
+ workflowRunId: workflowParentRunId,
3409
+ childRunId: runId,
3410
+ result,
3411
+ events: deps.pi.events,
3412
+ workflowKey: params.workflowKey ?? foregroundControl?.workflowKey,
3413
+ });
3414
+ }
4399
3415
  } finally {
4400
3416
  try {
4401
3417
  if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
@@ -4419,6 +3435,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4419
3435
  capabilityCeiling: data.capabilityCeiling,
4420
3436
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4421
3437
  }));
3438
+ } catch (error) {
3439
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3440
+ throw error;
4422
3441
  } finally {
4423
3442
  // An attached runSync rejection still owns its child and structured runtime.
4424
3443
  // A successful detached receipt transfers both to onDetachedExit while the
@@ -4432,6 +3451,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4432
3451
  recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
4433
3452
  }
4434
3453
 
3454
+ let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
3455
+ if (worktreeSetup) {
3456
+ worktreeHandoff = r.detached
3457
+ ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
3458
+ : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r });
3459
+ }
3460
+
4435
3461
  if (r.progress) allProgress.push(r.progress);
4436
3462
  if (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);
4437
3463
 
@@ -4466,8 +3492,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4466
3492
  totalChildUsage: sumResultsUsage([r]),
4467
3493
  totalCost,
4468
3494
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
3495
+ ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
4469
3496
  }));
4470
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results });
3497
+ rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results });
4471
3498
 
4472
3499
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
4473
3500
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -4490,6 +3517,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4490
3517
  }
4491
3518
  }
4492
3519
 
3520
+ const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
4493
3521
  if (r.detached) {
4494
3522
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
4495
3523
  const blockingRecovery = `subagent_wait({ id: "${runId}" }). Use ${statusRecovery}`;
@@ -4499,26 +3527,26 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4499
3527
  ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with subagent_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4500
3528
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
4501
3529
  return {
4502
- content: [{ type: "text", text: message }],
3530
+ content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
4503
3531
  details,
4504
3532
  };
4505
3533
  }
4506
3534
 
4507
3535
  if (r.interrupted) {
4508
3536
  return {
4509
- content: [{ type: "text", text: `Run paused after interrupt (${params.agent}). Waiting for explicit next action.` }],
3537
+ content: [{ type: "text", text: `Run paused after interrupt (${params.agent}). Waiting for explicit next action.${worktreeSuffix}` }],
4510
3538
  details,
4511
3539
  };
4512
3540
  }
4513
3541
 
4514
3542
  if (r.exitCode !== 0)
4515
3543
  return {
4516
- content: [{ type: "text", text: formatFailedSingleRunOutput(r, finalizedOutput.displayOutput) }],
3544
+ content: [{ type: "text", text: `${formatFailedSingleRunOutput(r, finalizedOutput.displayOutput)}${worktreeSuffix}` }],
4517
3545
  details,
4518
3546
  isError: true,
4519
3547
  };
4520
3548
  return {
4521
- content: [{ type: "text", text: finalizedOutput.displayOutput || "(no output)" }],
3549
+ content: [{ type: "text", text: `${finalizedOutput.displayOutput || "(no output)"}${worktreeSuffix}` }],
4522
3550
  details,
4523
3551
  };
4524
3552
  }
@@ -4610,7 +3638,12 @@ export function bindMissionWorkflowChildAsyncLaunch(
4610
3638
  return { ...params, workflowChildAsyncId: id };
4611
3639
  }
4612
3640
 
4613
- function workflowChildResult(key: string, result: AgentToolResult<Details>): WorkflowScriptChildResult {
3641
+ function workflowChildResult(
3642
+ key: string,
3643
+ result: AgentToolResult<Details>,
3644
+ childParams: Record<string, unknown> = {},
3645
+ resumeState?: SubagentState,
3646
+ ): WorkflowScriptChildResult {
4614
3647
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
4615
3648
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
4616
3649
  ? result.details.results[0].finalOutput
@@ -4627,27 +3660,168 @@ function workflowChildResult(key: string, result: AgentToolResult<Details>): Wor
4627
3660
  }
4628
3661
  const structured = result.details.results.map((child) => child.structuredOutput).filter((value) => value !== undefined);
4629
3662
  const resolvedAgents = [...new Set(result.details.results.map((child) => child.agent).filter((agent): agent is string => Boolean(agent)))];
3663
+ const resolvedContexts = [...new Set(result.details.results.map((child) => child.context).filter((context): context is "fresh" | "fork" => context === "fresh" || context === "fork"))];
3664
+ const runId = result.details.runId ?? result.details.asyncId;
3665
+ let resumability: WorkflowScriptChildResult["resumability"];
3666
+ if (!runId || !resumeState) {
3667
+ resumability = { state: "not-resumable", reason: runId ? "resumability was not inspected" : "child produced no run id" };
3668
+ } else {
3669
+ try {
3670
+ const target = resolveResumeTarget({ id: runId }, resumeState, { asyncRequireSessionFile: true, exactOnly: true });
3671
+ resumability = target.kind === "revive"
3672
+ ? { state: "resumable" }
3673
+ : { state: "not-resumable", reason: "child is still running" };
3674
+ } catch (error) {
3675
+ resumability = { state: "not-resumable", reason: error instanceof Error ? error.message : String(error) };
3676
+ }
3677
+ }
3678
+ const requestedContext = childParams.context === "fresh" || childParams.context === "fork" ? childParams.context : undefined;
3679
+ const resolvedContext = result.details.context ?? (resolvedContexts.length === 1 ? resolvedContexts[0] : resolvedContexts.length > 1 ? "mixed" : undefined);
3680
+ const resumeSourceRunId = typeof childParams.resume === "string" && childParams.resume.trim() ? childParams.resume.trim() : undefined;
3681
+ const continuationRunIds = [...new Set([resumeSourceRunId, runId].filter((value): value is string => Boolean(value)))];
3682
+ const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
3683
+ ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4630
3684
  return {
4631
3685
  key,
4632
3686
  ok,
4633
3687
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
4634
- ...(result.details.runId || result.details.asyncId ? { runId: result.details.runId ?? result.details.asyncId } : {}),
3688
+ ...(runId ? { runId } : {}),
4635
3689
  output,
4636
3690
  ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
4637
3691
  ...(detached ? { detached: true } : {}),
4638
3692
  ...(structured.length === 1 ? { structuredOutput: structured[0] } : structured.length > 1 ? { structuredOutput: structured } : {}),
3693
+ ...(requestedContext ? { requestedContext } : {}),
3694
+ ...(resolvedContext ? { resolvedContext } : {}),
3695
+ ...(outputReference ? { outputReference } : {}),
3696
+ resumability,
3697
+ continuation: { runIds: continuationRunIds },
4639
3698
  artifactPaths: [...artifactPaths],
4640
3699
  results: result.details.results,
4641
3700
  };
4642
3701
  }
4643
3702
 
3703
+ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
3704
+ const steering = result.details.steering;
3705
+ const error = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n") || undefined;
3706
+ if (!steering) return { key, state: "failed", ...(error ? { error } : {}) };
3707
+ const state = result.isError === true || steering.state === "failed" || steering.state === "partial"
3708
+ ? "failed"
3709
+ : steering.deliveryStatus === "delivered" ? "delivered" : "queued";
3710
+ return {
3711
+ key,
3712
+ state,
3713
+ requestId: steering.requestId,
3714
+ deliveryStatus: steering.deliveryStatus,
3715
+ targets: steering.targets.map((target) => ({ index: target.index, state: target.state, ...(target.reason ? { reason: target.reason } : {}) })),
3716
+ ...(state === "failed" && error ? { error } : {}),
3717
+ };
3718
+ }
3719
+
3720
+ function resolveKeyedWorkflowResume(
3721
+ reference: WorkflowReceiptResumeReference,
3722
+ state: SubagentState,
3723
+ ): { runId: string; runIds: string[] } {
3724
+ const entry = resolveWorkflowReceiptResumeEntry({
3725
+ reference,
3726
+ asyncDirRoot: DIRS.async,
3727
+ assertResumable(runId) {
3728
+ const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
3729
+ if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
3730
+ },
3731
+ });
3732
+ const runId = entry.latestRunId;
3733
+ if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
3734
+ return { runId, runIds: entry.continuation.runIds };
3735
+ }
3736
+
3737
+ function terminalWorkflowReceipt(
3738
+ workflowRunId: string,
3739
+ state: WorkflowReceiptState,
3740
+ children: WorkflowScriptChildResult[],
3741
+ ): WorkflowReceipt {
3742
+ return buildWorkflowReceipt({ workflowRunId, state, children });
3743
+ }
3744
+
3745
+ export async function steerWorkflowChildByKey(input: {
3746
+ state: SubagentState;
3747
+ workflowRunId: string;
3748
+ key: string;
3749
+ message: string;
3750
+ options: WorkflowSteerOptions;
3751
+ signal?: AbortSignal;
3752
+ asyncDirRoot?: string;
3753
+ resolveRunId?: () => string | undefined;
3754
+ }): Promise<WorkflowSteerResult> {
3755
+ const asyncDirRoot = input.asyncDirRoot ?? DIRS.async;
3756
+ const ackTimeoutMs = input.options.ackTimeoutMs ?? 3_000;
3757
+ const deadline = Date.now() + ackTimeoutMs;
3758
+ while (true) {
3759
+ const control = [...input.state.foregroundControls.values()].find((candidate) => candidate.parentWorkflowRunId === input.workflowRunId
3760
+ && candidate.workflowKey === input.key
3761
+ && Boolean(candidate.workflowSteeringDir)
3762
+ && (candidate.activeChildren?.size ?? 0) > 0);
3763
+ if (control) {
3764
+ const result = await steerWorkflowForegroundTarget({
3765
+ target: { control, workflowRunId: input.workflowRunId, sourceRunId: control.runId },
3766
+ message: input.message,
3767
+ mode: input.options.mode,
3768
+ index: input.options.index,
3769
+ ackTimeoutMs: Math.max(1, deadline - Date.now()),
3770
+ signal: input.signal,
3771
+ });
3772
+ return workflowSteerReceipt(input.key, result);
3773
+ }
3774
+
3775
+ const workflowStatus = readStatus(path.join(asyncDirRoot, input.workflowRunId));
3776
+ const step = workflowStatus?.steps?.find((candidate) => candidate.workflowKey === input.key);
3777
+ const childRunId = step?.runId ?? input.resolveRunId?.();
3778
+ if (childRunId) {
3779
+ const asyncDir = path.join(asyncDirRoot, childRunId);
3780
+ const childStatus = reconcileAsyncRun(asyncDir).status;
3781
+ if (childStatus && childStatus.state !== "running" && childStatus.state !== "queued" && (input.options.mode !== "follow_up" || !canQueueRetainedAsyncFollowUp(childStatus, input.options.index))) {
3782
+ return { key: input.key, state: "missed", error: `Workflow child '${input.key}' is ${childStatus.state}.` };
3783
+ }
3784
+ if (childStatus) {
3785
+ const result = await steerAsyncRun({
3786
+ state: input.state,
3787
+ runId: childRunId,
3788
+ message: input.message,
3789
+ mode: input.options.mode,
3790
+ index: input.options.index,
3791
+ ackTimeoutMs: Math.max(1, deadline - Date.now()),
3792
+ location: { asyncDir },
3793
+ signal: input.signal,
3794
+ });
3795
+ return workflowSteerReceipt(input.key, result);
3796
+ }
3797
+ }
3798
+ if (step && step.status !== "running" && step.status !== "pending") {
3799
+ return { key: input.key, state: "missed", error: `Workflow child '${input.key}' is ${step.status}.` };
3800
+ }
3801
+ if (workflowStatus && workflowStatus.state !== "running" && workflowStatus.state !== "queued") {
3802
+ return { key: input.key, state: "missed", error: `Workflow '${input.workflowRunId}' is ${workflowStatus.state}.` };
3803
+ }
3804
+ if (input.signal?.aborted || Date.now() >= deadline) {
3805
+ return { key: input.key, state: "missed", error: `Workflow child '${input.key}' had no live steering route.` };
3806
+ }
3807
+ await new Promise<void>((resolve) => setTimeout(resolve, Math.min(10, Math.max(1, deadline - Date.now()))));
3808
+ }
3809
+ }
3810
+
4644
3811
  export function prepareWorkflowLaunchParams(
4645
3812
  workflowDefaults: SubagentParamsLike,
4646
3813
  childParams: Record<string, unknown>,
4647
3814
  parentWorkflowRunId: string,
4648
3815
  workflowKey: string,
4649
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor } = {},
3816
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number } = {},
4650
3817
  ): SubagentParamsLike {
3818
+ const parentTimeoutMs = options.parentDeadlineAt === undefined
3819
+ || childParams.timeoutMs !== undefined
3820
+ || childParams.maxRuntimeMs !== undefined
3821
+ || workflowDefaults.timeoutMs !== undefined
3822
+ || workflowDefaults.maxRuntimeMs !== undefined
3823
+ ? undefined
3824
+ : Math.max(1, options.parentDeadlineAt - Date.now());
4651
3825
  if (typeof childParams.resume === "string") {
4652
3826
  if (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {
4653
3827
  throw new Error("gate is not supported with retained resume; resume uses the retained child contract.");
@@ -4656,12 +3830,15 @@ export function prepareWorkflowLaunchParams(
4656
3830
  const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
4657
3831
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
4658
3832
  const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
3833
+ const worktree = childParams.worktree ?? workflowDefaults.worktree;
4659
3834
  return {
4660
3835
  action: "resume",
4661
3836
  id: childParams.resume.trim(),
3837
+ ...(typeof childParams.index === "number" && Number.isInteger(childParams.index) ? { index: childParams.index } : {}),
4662
3838
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4663
3839
  workflowParentRunId: parentWorkflowRunId,
4664
3840
  workflowKey,
3841
+ ...(worktree !== undefined ? { worktree: worktree as boolean } : {}),
4665
3842
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4666
3843
  ...(options.missionDetached ? { mission: false } : {}),
4667
3844
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
@@ -4677,12 +3854,13 @@ export function prepareWorkflowLaunchParams(
4677
3854
  ...(options.missionDetached ? { mission: false } : {}),
4678
3855
  workflowParentRunId: parentWorkflowRunId,
4679
3856
  workflowKey,
3857
+ ...(parentTimeoutMs !== undefined ? { workflowParentDeadlineAt: options.parentDeadlineAt } : {}),
4680
3858
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4681
3859
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4682
3860
  } as SubagentParamsLike;
4683
3861
  const normalizedGate = normalizeGateParams(launchParams);
4684
3862
  if (!normalizedGate.ok) throw new Error(normalizedGate.error);
4685
- return prepareWorkflowChildParams(normalizedGate.params);
3863
+ return normalizedGate.params;
4686
3864
  }
4687
3865
 
4688
3866
  type GateParamsNormalizationResult =
@@ -4700,41 +3878,6 @@ function normalizeGateParams(params: SubagentParamsLike): GateParamsNormalizatio
4700
3878
  return { ok: true, params: { ...rest, ...(normalized.acceptance !== undefined ? { acceptance: normalized.acceptance } : {}) } };
4701
3879
  }
4702
3880
 
4703
- function prepareWorkflowChildParams(params: SubagentParamsLike): SubagentParamsLike {
4704
- if (params.worktree !== true || !params.agent) return params;
4705
- const {
4706
- agent,
4707
- task = "",
4708
- model,
4709
- skill,
4710
- output,
4711
- outputMode,
4712
- outputSchema,
4713
- acceptance,
4714
- agentContract,
4715
- toolBudget,
4716
- reads,
4717
- ...runParams
4718
- } = params;
4719
- return {
4720
- ...runParams,
4721
- worktree: true,
4722
- tasks: [{
4723
- agent,
4724
- task,
4725
- ...(model !== undefined ? { model } : {}),
4726
- ...(skill !== undefined ? { skill } : {}),
4727
- ...(output !== undefined ? { output } : {}),
4728
- ...(reads !== undefined ? { reads } : {}),
4729
- ...(outputMode !== undefined ? { outputMode } : {}),
4730
- ...(outputSchema !== undefined ? { outputSchema } : {}),
4731
- ...(acceptance !== undefined ? { acceptance } : {}),
4732
- ...(agentContract !== undefined ? { agentContract } : {}),
4733
- ...(toolBudget !== undefined ? { toolBudget } : {}),
4734
- }],
4735
- };
4736
- }
4737
-
4738
3881
  function formatWorkflowValue(value: unknown): string {
4739
3882
  if (value === undefined) return "(undefined)";
4740
3883
  if (typeof value === "string") return value;
@@ -4865,7 +4008,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4865
4008
  const warning = getProjectArtifactPackagingWarning(workflowCwd);
4866
4009
  if (warning) console.warn(`[pi-subagents] ${warning}`);
4867
4010
  }
4868
- const workflowPrompts = { render: (ref: string, vars?: unknown) => renderWorkflowPrompt(ref, vars, workflowCwd) };
4869
4011
  const chatProgressResult = resolveWorkflowChatProgress({ requested: requestParams.chatProgress, parentCwd, workflowCwd, background: requestParams.async !== false });
4870
4012
  if (chatProgressResult.error) return { content: [{ type: "text", text: chatProgressResult.error }], isError: true, details: { mode: "workflow", results: [] } };
4871
4013
  const chatProgress = chatProgressResult.projection!;
@@ -4942,12 +4084,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4942
4084
  };
4943
4085
  if (workflowRunId) {
4944
4086
  const toolCallId = _id;
4087
+ const workflowSessionRoot = requestParams.sessionDir
4088
+ ? path.resolve(deps.expandTilde(requestParams.sessionDir))
4089
+ : trustedSessionRootsForStatus(ctx, deps)[0];
4945
4090
  const asyncDir = path.join(DIRS.async, workflowRunId);
4946
4091
  const resultPath = resultFilePath(DIRS.results, workflowRunId);
4947
4092
  const statusPath = path.join(asyncDir, "status.json");
4948
4093
  const eventsPath = path.join(asyncDir, "events.jsonl");
4949
4094
  const startedAt = Date.now();
4950
4095
  const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4096
+ const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
4097
+ deps.state.completionOwnerId = completionOwnerId;
4951
4098
  try {
4952
4099
  fs.mkdirSync(asyncDir, { recursive: true });
4953
4100
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
@@ -4965,51 +4112,114 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4965
4112
  runId: workflowRunId,
4966
4113
  toolCallId,
4967
4114
  sessionId: currentSessionId ?? undefined,
4115
+ completionOwnerId,
4968
4116
  mode: "workflow",
4969
4117
  state: "running",
4970
4118
  startedAt,
4971
4119
  lastUpdate: startedAt,
4972
4120
  ...(timeout !== undefined ? { deadlineAt: startedAt + timeout, timeoutMs: timeout } : {}),
4973
4121
  cwd: workflowCwd,
4122
+ ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}),
4123
+ ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
4974
4124
  pid: process.pid,
4975
4125
  steps: [],
4976
4126
  workflow: { trace: [], emits: [], console: [] },
4977
4127
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4978
4128
  };
4979
- const appendWorkflowEvent = (event: Record<string, unknown>) => fs.appendFileSync(eventsPath, `${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\n`, "utf-8");
4129
+ const appendWorkflowEvent = (event: Record<string, unknown>) => {
4130
+ try {
4131
+ fs.appendFileSync(eventsPath, `${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\n`, "utf-8");
4132
+ } catch (error) {
4133
+ // The event log is a journal, not workflow truth. Callers append from
4134
+ // inside run-result handling, so losing an entry to a full disk or to a
4135
+ // transient Windows lock must not fail the run being recorded.
4136
+ console.error(`Failed to append async workflow event '${eventsPath}':`, error);
4137
+ }
4138
+ };
4980
4139
  let indexedState: AsyncStatus["state"] | undefined;
4981
- const persist = () => {
4140
+ const indexPersistence = createCapacityResilientJsonWriter({
4141
+ keepAlive: true,
4142
+ onSuccess: (_filePath, payload) => { indexedState = (payload as { state: AsyncStatus["state"] }).state; },
4143
+ onError: (error, filePath) => console.error(`Failed to update async workflow index '${filePath}':`, error),
4144
+ });
4145
+ const queueActiveRunIndex = (): void => {
4146
+ const state = status.state;
4147
+ if (indexedState === state && indexPersistence.pendingCount() === 0) return;
4148
+ indexPersistence.write(asyncDir, { state, toolCallId: status.toolCallId }, (_filePath, payload) => {
4149
+ const indexPayload = payload as { state: AsyncStatus["state"]; toolCallId?: string };
4150
+ updateActiveRunIndex(asyncDir, indexPayload.state, indexPayload.toolCallId, { retryCapacityErrors: true });
4151
+ });
4152
+ };
4153
+ const runPersistence = createCapacityResilientJsonWriter({
4154
+ keepAlive: true,
4155
+ onSuccess: (filePath) => { if (filePath === statusPath) queueActiveRunIndex(); },
4156
+ onError: (error, filePath) => console.error(`Failed to persist async workflow state '${filePath}':`, error),
4157
+ write: (filePath, payload) => filePath === resultPath
4158
+ ? writeAsyncResultFile(filePath, payload as Record<string, unknown>)
4159
+ : writeAtomicJson(filePath, payload),
4160
+ });
4161
+ let initialPersistenceComplete = false;
4162
+ let persistClosed = false;
4163
+ let statusPersistenceDegraded = false;
4164
+ // Progress journalling runs from admit, launch, the launch and progress observers,
4165
+ // onTrace and onEmit -- all inside the promises a workflowScript awaits. Those
4166
+ // callers pass tolerateStatusWriteFailure so a transient lock on status.json cannot
4167
+ // mark a finished child failed or abort its still-running siblings. Initial and
4168
+ // terminal writes stay fail-fast on purpose: no child work is at risk by then, and
4169
+ // silently dropping a terminal write would leave status.json and the active-run
4170
+ // index pinned at "running" after the result already says complete.
4171
+ const persist = (options: { tolerateStatusWriteFailure?: boolean } = {}) => {
4172
+ if (persistClosed) return;
4173
+ const liveJob = deps.state.asyncJobs.get(workflowRunId);
4174
+ if (liveJob && (liveJob.status === "complete" || liveJob.status === "failed") && status.state !== "complete" && status.state !== "failed") return;
4982
4175
  status.lastUpdate = Date.now();
4983
- writeAtomicJson(statusPath, status);
4984
- if (indexedState !== status.state) {
4985
- updateActiveRunIndex(asyncDir, status.state, status.toolCallId);
4986
- indexedState = status.state;
4176
+ if (!initialPersistenceComplete) {
4177
+ writeAtomicJson(statusPath, status);
4178
+ initialPersistenceComplete = true;
4179
+ queueActiveRunIndex();
4180
+ } else if (options.tolerateStatusWriteFailure) {
4181
+ try {
4182
+ runPersistence.write(statusPath, status);
4183
+ statusPersistenceDegraded = false;
4184
+ } catch (error) {
4185
+ const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
4186
+ console.error(message, error);
4187
+ if (!statusPersistenceDegraded) {
4188
+ statusPersistenceDegraded = true;
4189
+ try {
4190
+ appendWorkflowEvent({ type: "subagent.workflow.status_write_failed", error: message });
4191
+ } catch (eventError) {
4192
+ console.error(`Failed to record degraded status persistence for '${statusPath}':`, eventError);
4193
+ }
4194
+ }
4195
+ }
4196
+ } else {
4197
+ runPersistence.write(statusPath, status);
4987
4198
  }
4988
- const job = deps.state.asyncJobs.get(workflowRunId);
4989
- if (job) {
4990
- job.status = status.state;
4991
- job.updatedAt = status.lastUpdate;
4992
- job.activityState = status.activityState;
4993
- job.lastActivityAt = status.lastActivityAt;
4994
- job.currentTool = status.currentTool;
4995
- job.currentToolStartedAt = status.currentToolStartedAt;
4996
- job.currentPath = status.currentPath;
4997
- job.turnCount = status.turnCount;
4998
- job.toolCount = status.toolCount;
4999
- job.currentStep = status.currentStep;
4199
+ if (liveJob) {
4200
+ liveJob.status = status.state;
4201
+ liveJob.updatedAt = status.lastUpdate;
4202
+ liveJob.activityState = status.activityState;
4203
+ liveJob.lastActivityAt = status.lastActivityAt;
4204
+ liveJob.currentTool = status.currentTool;
4205
+ liveJob.currentToolStartedAt = status.currentToolStartedAt;
4206
+ liveJob.currentPath = status.currentPath;
4207
+ liveJob.turnCount = status.turnCount;
4208
+ liveJob.toolCount = status.toolCount;
4209
+ liveJob.currentStep = status.currentStep;
5000
4210
  if (status.steps) {
5001
- job.steps = status.steps.map((step, index) => ({ ...step, index }));
5002
- job.agents = status.steps.map((step) => step.agent);
4211
+ liveJob.steps = status.steps.map((step, index) => ({ ...step, index }));
4212
+ liveJob.agents = status.steps.map((step) => step.agent);
5003
4213
  } else {
5004
- delete job.steps;
5005
- delete job.agents;
4214
+ delete liveJob.steps;
4215
+ delete liveJob.agents;
5006
4216
  }
5007
- job.workflow = status.workflow;
4217
+ liveJob.workflow = status.workflow;
5008
4218
  }
5009
4219
  };
5010
4220
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
5011
4221
  try {
5012
- writeAsyncResultFile(resultPath, payload);
4222
+ runPersistence.write(resultPath, payload);
5013
4223
  return true;
5014
4224
  } catch (error) {
5015
4225
  const message = `Failed to write async workflow result ${resultPath}: ${error instanceof Error ? error.message : String(error)}`;
@@ -5039,20 +4249,33 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5039
4249
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
5040
4250
  status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
5041
4251
  };
5042
- const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
4252
+ const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
5043
4253
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
5044
4254
  deps.state.fleetJobs ??= new Map();
5045
4255
  deps.state.fleetJobs.set(workflowRunId, workflowJob);
5046
- persist();
4256
+ try {
4257
+ persist();
4258
+ } catch (error) {
4259
+ deps.state.workflowControllers?.delete(workflowRunId);
4260
+ deps.state.asyncJobs.delete(workflowRunId);
4261
+ deps.state.fleetJobs?.delete(workflowRunId);
4262
+ workflowCapacity?.rollback();
4263
+ indexPersistence.dispose();
4264
+ return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
4265
+ }
5047
4266
  appendWorkflowEvent({ type: "subagent.workflow.started" });
5048
4267
  const { workflowScript, async: _workflowAsync, chatProgress: _chatProgress, ...workflowRequest } = requestParams;
5049
4268
  void Promise.resolve().then(async () => {
4269
+ const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5050
4270
  const workflowResults: SingleResult[] = [];
4271
+ const workflowChildRunIds = new Map<string, string>();
5051
4272
  const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = workflowRequest;
5052
4273
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5053
4274
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5054
4275
  const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId), configuredOutputBaseDir);
5055
4276
  const claimedOutputPaths = new Map<string, string>();
4277
+ const childOutputOverrides = new Map<string, string>();
4278
+ const producedChildOutputPaths = new Set<string>();
5056
4279
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5057
4280
  let projectedTraceLength = 0;
5058
4281
  let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
@@ -5114,7 +4337,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5114
4337
  projectedTraceLength = trace.length;
5115
4338
  projectedTraceTail = trace.at(-1);
5116
4339
  projectWorkflowActivity();
5117
- persist();
4340
+ persist({ tolerateStatusWriteFailure: true });
5118
4341
  appendWorkflowEvent({ type: "subagent.workflow.trace", trace });
5119
4342
  };
5120
4343
  try {
@@ -5122,26 +4345,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5122
4345
  script: workflowScript,
5123
4346
  timeoutMs: timeout,
5124
4347
  signal: controller.signal,
5125
- prompts: workflowPrompts,
5126
4348
  ...(workflowState ? { state: workflowState } : {}),
5127
4349
  onTrace: updateTrace,
5128
4350
  admit: (calls) => {
5129
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
4351
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5130
4352
  if (outputClaims.error) throw new Error(outputClaims.error);
5131
4353
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5132
4354
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5133
- persist();
4355
+ if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4356
+ persist({ tolerateStatusWriteFailure: true });
5134
4357
  },
5135
4358
  onEmit: (emits) => {
5136
4359
  // Each emit is validated at the host boundary in runWorkflowScript before onEmit fires.
5137
4360
  status.workflow = { ...(status.workflow ?? { trace: [], console: [] }), emits };
5138
- persist();
4361
+ persist({ tolerateStatusWriteFailure: true });
5139
4362
  appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
5140
4363
  },
5141
4364
  launch: async (key, childParams, workflowSignal, admission) => {
5142
- if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4365
+ if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
5143
4366
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
5144
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4367
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5145
4368
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5146
4369
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5147
4370
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
@@ -5153,7 +4376,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5153
4376
  });
5154
4377
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
5155
4378
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
5156
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget } }), runFanoutAdmitted: admission.admitted },
4379
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), runFanoutAdmitted: admission.admitted },
5157
4380
  missionBinding,
5158
4381
  deps.asyncByDefault,
5159
4382
  );
@@ -5164,7 +4387,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5164
4387
  step.sessionFile = launch.sessionFile;
5165
4388
  step.async = launch.async;
5166
4389
  if (launch.runId) step.runId = launch.runId;
5167
- persist();
4390
+ persist({ tolerateStatusWriteFailure: true });
5168
4391
  }
5169
4392
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
5170
4393
  });
@@ -5187,7 +4410,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5187
4410
  step.thinking = progress.thinking;
5188
4411
  step.error = progress.error;
5189
4412
  projectWorkflowActivity();
5190
- persist();
4413
+ persist({ tolerateStatusWriteFailure: true });
5191
4414
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
5192
4415
  status: step.status,
5193
4416
  heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
@@ -5195,7 +4418,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5195
4418
  }, ctx, preserveActiveSession);
5196
4419
  });
5197
4420
  workflowResults.push(...result.details.results);
5198
- const child = workflowChildResult(key, result);
4421
+ for (const childResult of result.details.results) {
4422
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
4423
+ }
4424
+ const child = workflowChildResult(key, result, childParams, deps.state);
4425
+ if (child.runId) workflowChildRunIds.set(key, child.runId);
5199
4426
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5200
4427
  if (step) {
5201
4428
  step.async = Boolean(result.details.asyncId || result.details.asyncDir);
@@ -5219,16 +4446,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5219
4446
  return child;
5220
4447
  },
5221
4448
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
4449
+ resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4450
+ steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5222
4451
  });
5223
4452
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
5224
4453
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
5225
4454
  const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
5226
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary);
4455
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
5227
4456
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
5228
4457
  const workflowUsage = sumResultsUsage(workflowResults);
5229
4458
  status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
5230
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4459
+ const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children);
4460
+ let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4461
+ try {
4462
+ workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4463
+ } catch (receiptError) {
4464
+ appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4465
+ }
4466
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5231
4467
  persist();
4468
+ persistClosed = true;
5232
4469
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
5233
4470
  } catch (error) {
5234
4471
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
@@ -5239,17 +4476,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5239
4476
  const state = stopped ? "stopped" : pauseForDetached ? "paused" : "failed";
5240
4477
  for (const step of status.steps ?? []) {
5241
4478
  if (step.workflowKey && detachedChildKeys.has(step.workflowKey)) {
4479
+ if (step.status === "completed" || step.status === "complete" || step.status === "failed") continue;
5242
4480
  step.status = "paused";
5243
4481
  step.activityState = "needs_attention";
4482
+ } else if (pauseForDetached && step.status === "running") {
4483
+ step.status = "stopped";
4484
+ step.stopped = true;
4485
+ delete step.activityState;
5244
4486
  }
5245
4487
  }
5246
4488
  status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
5247
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed."));
5248
- const resultSummary = appendWorkflowOutputWarning(status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed."), outputWarning);
5249
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: resultSummary, error: status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.detached ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4489
+ if (pauseForDetached) {
4490
+ const promoted = promotePausedWorkflowIfSettled(status);
4491
+ if (promoted) status = promoted;
4492
+ }
4493
+ const terminalSummary = status.state === "complete"
4494
+ ? "Workflow completed after detached child finished."
4495
+ : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.");
4496
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
4497
+ const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
4498
+ const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
4499
+ const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children);
4500
+ let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4501
+ try {
4502
+ workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4503
+ } catch (receiptError) {
4504
+ appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4505
+ }
4506
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5250
4507
  persist();
5251
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, error: status.error, ...(status.activityState ? { activityState: status.activityState } : {}) });
4508
+ persistClosed = true;
4509
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
5252
4510
  } finally {
4511
+ persistClosed = true;
5253
4512
  deps.state.workflowControllers?.delete(workflowRunId);
5254
4513
  deps.state.activeAsyncCapacity = workflowCapacity?.reconcile(new Set(deps.state.workflowControllers?.keys() ?? []))
5255
4514
  ?? deps.state.activeAsyncCapacity;
@@ -5265,8 +4524,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5265
4524
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5266
4525
  const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id), configuredOutputBaseDir);
5267
4526
  const claimedOutputPaths = new Map<string, string>();
4527
+ const childOutputOverrides = new Map<string, string>();
4528
+ const producedChildOutputPaths = new Set<string>();
5268
4529
  const workflowResults: SingleResult[] = [];
4530
+ const workflowChildRunIds = new Map<string, string>();
5269
4531
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
4532
+ const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5270
4533
  const sendWorkflowProgress = () => {
5271
4534
  const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);
5272
4535
  if (update) onUpdate?.(update);
@@ -5276,26 +4539,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5276
4539
  script: requestParams.workflowScript,
5277
4540
  timeoutMs: timeout,
5278
4541
  signal,
5279
- prompts: workflowPrompts,
5280
4542
  ...(workflowState ? { state: workflowState } : {}),
5281
4543
  onTrace: (trace) => {
5282
4544
  liveWorkflow = { ...liveWorkflow, trace };
5283
4545
  sendWorkflowProgress();
5284
4546
  },
5285
4547
  admit: (calls) => {
5286
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
4548
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5287
4549
  if (outputClaims.error) throw new Error(outputClaims.error);
5288
4550
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5289
4551
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
4552
+ if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
5290
4553
  },
5291
4554
  onEmit: (emits) => {
5292
4555
  liveWorkflow = { ...liveWorkflow, emits };
5293
4556
  sendWorkflowProgress();
5294
4557
  },
5295
4558
  launch: async (key, childParams, workflowSignal, admission) => {
5296
- if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4559
+ if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
5297
4560
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
5298
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4561
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5299
4562
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5300
4563
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5301
4564
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -5307,7 +4570,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5307
4570
  });
5308
4571
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
5309
4572
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
5310
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget } }), runFanoutAdmitted: admission.admitted },
4573
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), runFanoutAdmitted: admission.admitted },
5311
4574
  missionBinding,
5312
4575
  deps.asyncByDefault,
5313
4576
  );
@@ -5327,8 +4590,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5327
4590
  }, ctx, preserveActiveSession);
5328
4591
  });
5329
4592
  workflowResults.push(...result.details.results);
4593
+ for (const childResult of result.details.results) {
4594
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
4595
+ }
5330
4596
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
5331
- const child = workflowChildResult(key, result);
4597
+ const child = workflowChildResult(key, result, childParams, deps.state);
4598
+ if (child.runId) workflowChildRunIds.set(key, child.runId);
5332
4599
  const childStatus = missionWorkflowChildStatus(result);
5333
4600
  recordMissionWorkflowChild(missionBinding, _id, key, {
5334
4601
  status: childStatus,
@@ -5342,18 +4609,21 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5342
4609
  return child;
5343
4610
  },
5344
4611
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
4612
+ resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4613
+ steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: _id, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5345
4614
  });
4615
+ const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children);
5346
4616
  const traceLines = workflow.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
5347
4617
  const sections = ["Workflow completed.", `Return:\n${formatWorkflowValue(workflow.value)}`];
5348
4618
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
5349
4619
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
5350
4620
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5351
4621
  const workflowText = sections.join("\n\n");
5352
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
4622
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
5353
4623
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5354
4624
  return attachWorkflowMission(withRunFanoutBudget({
5355
4625
  content: [{ type: "text", text: displayText }],
5356
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, chatProgress }),
4626
+ details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console, receipt }, chatProgress }),
5357
4627
  }, workflowFanoutBudget));
5358
4628
  } catch (error) {
5359
4629
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
@@ -5364,16 +4634,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5364
4634
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
5365
4635
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5366
4636
  const workflowText = sections.join("\n\n");
5367
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
4637
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
5368
4638
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4639
+ const receipt = terminalWorkflowReceipt(_id, "failed", partial.children);
5369
4640
  return attachWorkflowMission(withRunFanoutBudget({
5370
4641
  content: [{ type: "text", text: displayText }],
5371
4642
  isError: true,
5372
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console }, chatProgress }),
4643
+ details: compactOptional<Details>({ mode: "workflow", runId: _id, results: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console, receipt }, chatProgress }),
5373
4644
  }, workflowFanoutBudget));
5374
4645
  }
5375
4646
  }
5376
- const directParams = prepareWorkflowChildParams(requestParams);
4647
+ const directParams = requestParams;
5377
4648
  const requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);
5378
4649
  const paramsWithResolvedCwd = directParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };
5379
4650
  const action = paramsWithResolvedCwd.action;
@@ -5619,7 +4890,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5619
4890
  cwd: requestCwd,
5620
4891
  config: deps.config,
5621
4892
  state: deps.state,
5622
- context: paramsWithResolvedCwd.context,
4893
+ context: paramsWithResolvedCwd.context === "profile" ? undefined : paramsWithResolvedCwd.context,
5623
4894
  requestedSessionDir: paramsWithResolvedCwd.sessionDir,
5624
4895
  currentSessionFile,
5625
4896
  currentSessionId,
@@ -5690,61 +4961,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5690
4961
  }
5691
4962
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5692
4963
  }
5693
-
5694
- if (action === "approve-checkpoint" || action === "reject-checkpoint") {
5695
- deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5696
- const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5697
- if (!targetRunId && !paramsWithResolvedCwd.dir) {
5698
- return { content: [{ type: "text", text: `action='${action}' requires id or dir.` }], isError: true, details: { mode: "management", results: [] } };
5699
- }
5700
- try {
5701
- const resolved = targetRunId ? resolveSubagentRunId(targetRunId, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) })) : undefined;
5702
- const decision = action === "approve-checkpoint" ? "approved" : "rejected";
5703
- if (resolved?.kind === "foreground") {
5704
- const run = deps.state.foregroundRuns?.get(resolved.id);
5705
- if (!run?.checkpoint || run.checkpoint.status !== "pending") {
5706
- return { content: [{ type: "text", text: `Run '${resolved.id}' is not paused at an approval checkpoint.` }], isError: true, details: { mode: "management", results: [] } };
5707
- }
5708
- if (deps.state.currentSessionId && run.sessionId !== deps.state.currentSessionId) {
5709
- return { content: [{ type: "text", text: `Run '${resolved.id}' was not found in the active session.` }], isError: true, details: { mode: "management", results: [] } };
5710
- }
5711
- const decidedAt = Date.now();
5712
- const checkpoint: NonNullable<Details["checkpoint"]> = decision === "approved"
5713
- ? { ...run.checkpoint, status: "approved", approvedAt: decidedAt }
5714
- : { ...run.checkpoint, status: "rejected", rejectedAt: decidedAt };
5715
- run.checkpoint = checkpoint;
5716
- run.updatedAt = decidedAt;
5717
- return {
5718
- content: [{ type: "text", text: `Checkpoint '${checkpoint.name}' ${decision} for foreground run ${resolved.id}.` }],
5719
- details: { mode: "management", results: [], checkpoint },
5720
- };
5721
- }
5722
- const location = paramsWithResolvedCwd.dir
5723
- ? resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results)
5724
- : resolved?.kind === "async"
5725
- ? resolved.location
5726
- : undefined;
5727
- if (!location?.asyncDir) {
5728
- return { content: [{ type: "text", text: `action='${action}' targets paused foreground or async checkpoints. No matching run found.` }], isError: true, details: { mode: "management", results: [] } };
5729
- }
5730
- const status = readStatus(location.asyncDir);
5731
- const runId = status?.runId ?? location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir);
5732
- if (!status?.checkpoint || status.state !== "paused") {
5733
- return { content: [{ type: "text", text: `Run '${runId}' is not paused at an approval checkpoint.` }], isError: true, details: { mode: "management", results: [] } };
5734
- }
5735
- if (deps.state.currentSessionId && status.sessionId !== deps.state.currentSessionId) {
5736
- return { content: [{ type: "text", text: `Run '${runId}' was not found in the active session.` }], isError: true, details: { mode: "management", results: [] } };
5737
- }
5738
- deliverCheckpointDecisionRequest({ asyncDir: location.asyncDir, decision, source: "subagent-action", ...(paramsWithResolvedCwd.message ? { reason: paramsWithResolvedCwd.message } : {}) });
5739
- return {
5740
- content: [{ type: "text", text: `Checkpoint '${status.checkpoint.name}' ${decision} for run ${runId}.` }],
5741
- details: { mode: "management", results: [], checkpoint: { ...status.checkpoint, status: decision } },
5742
- };
5743
- } catch (error) {
5744
- const text = error instanceof Error ? error.message : String(error);
5745
- return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
5746
- }
5747
- }
5748
4964
  if (action === "resume") {
5749
4965
  return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
5750
4966
  }
@@ -5988,6 +5204,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5988
5204
  cwd: requestCwd,
5989
5205
  config: deps.config,
5990
5206
  currentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,
5207
+ runtimeAgentOwner: deps.pi,
5991
5208
  });
5992
5209
  }
5993
5210
 
@@ -6033,26 +5250,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6033
5250
  const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
6034
5251
  const discovered = deps.discoverAgents(effectiveCwd, scope);
6035
5252
  const discoveredAgents = discovered.agents;
6036
- const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents);
5253
+ const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics);
6037
5254
  if (canonicalParams.error) return buildRequestedModeError(effectiveParams, canonicalParams.error);
6038
5255
  effectiveParams = canonicalParams.params!;
6039
5256
  const modelScope = discovered.modelScope;
6040
5257
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
6041
5258
  const turnBudget = resolveTurnBudgetConfig(effectiveParams.turnBudget ?? deps.config.turnBudget);
6042
5259
  if (turnBudget.error) return buildRequestedModeError(effectiveParams, turnBudget.error);
6043
- const contextPolicy = resolveAgentDefaultContextPolicy(effectiveParams, discoveredAgents);
5260
+ // An agent-level defaultContext is a preference, unlike an explicit request.
5261
+ // Prefer fork only when the parent session is persisted and has a current leaf;
5262
+ // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
5263
+ // Explicit context:"fork" remains strict.
5264
+ const contextPolicyResult = resolveAgentDefaultContextPolicy(
5265
+ effectiveParams,
5266
+ discoveredAgents,
5267
+ deps.config.defaultSubagentContext,
5268
+ canPreferFork(ctx.sessionManager),
5269
+ );
5270
+ if ("error" in contextPolicyResult) return buildRequestedModeError(effectiveParams, contextPolicyResult.error);
5271
+ const contextPolicy = contextPolicyResult;
6044
5272
  effectiveParams = contextPolicy.params;
6045
5273
  const sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6046
5274
  const intercomBridge = resolveIntercomBridge({
6047
5275
  config: deps.config.intercomBridge,
6048
5276
  override: effectiveParams.intercomBridge,
6049
- context: effectiveParams.context ?? (contextPolicy.usesFork ? "fork" : undefined),
5277
+ context: effectiveParams.context === "fresh" || effectiveParams.context === "fork"
5278
+ ? effectiveParams.context
5279
+ : contextPolicy.usesFork ? "fork" : undefined,
6050
5280
  orchestratorTarget: sessionName,
6051
5281
  });
6052
- const agents = intercomBridge.active
6053
- ? discoveredAgents.map((agent) => applyIntercomBridgeToAgent(agent, intercomBridge))
6054
- : discoveredAgents;
6055
- const runId = randomUUID().slice(0, 8);
5282
+ const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
5283
+ const runId = randomUUID();
6056
5284
  const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
6057
5285
  const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
6058
5286
  const shareEnabled = effectiveParams.share === true;
@@ -6086,30 +5314,33 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6086
5314
 
6087
5315
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6088
5316
  let forkThinkingOverrideForIndex: (idx?: number) => AgentConfig["thinking"] | undefined = () => undefined;
6089
- let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string): void => {};
5317
+ let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean): void => {};
6090
5318
  const forkThinkingRequirements = new Map<number, boolean>();
6091
5319
  const forkThinkingDowngrades = new Map<number, string>();
6092
5320
  try {
6093
5321
  const forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
6094
5322
  const parentModel = requestParentModel;
6095
- prepareForkThinking = (agentName, index, modelOverride) => {
5323
+ prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent) => {
6096
5324
  const agentConfig = agents.find((agent) => agent.name === agentName);
6097
- if (agentConfig?.runner?.type === "external-cli") {
5325
+ if (agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job") {
6098
5326
  forkThinkingRequirements.set(index, true);
6099
5327
  return;
6100
5328
  }
6101
- const primaryModel = resolveEffectiveSubagentModel(
6102
- modelOverride,
6103
- agentConfig?.model,
6104
- parentModel,
6105
- forkAvailableModels,
6106
- parentModel?.provider,
6107
- );
5329
+ const primaryModel = modelOverrideFromParent
5330
+ ? modelOverride
5331
+ : resolveEffectiveSubagentModel(
5332
+ modelOverride,
5333
+ agentConfig?.model,
5334
+ parentModel,
5335
+ forkAvailableModels,
5336
+ parentModel?.provider,
5337
+ );
6108
5338
  const candidates = buildModelCandidates(
6109
5339
  primaryModel,
6110
5340
  agentConfig?.fallbackModels,
6111
5341
  forkAvailableModels,
6112
5342
  parentModel?.provider,
5343
+ { primaryModelFromParent: modelOverrideFromParent ?? inheritsParentModel(modelOverride, agentConfig?.model, parentModel) },
6113
5344
  );
6114
5345
  forkThinkingRequirements.set(
6115
5346
  index,
@@ -6135,9 +5366,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6135
5366
  : (effectiveParams.chain ?? []).flatMap((step) => getStepAgents(step as ChainStep));
6136
5367
  const externalAgent = selectedAgentNames
6137
5368
  .map((name) => agents.find((agent) => agent.name === name))
6138
- .find((agent) => agent?.runner?.type === "external-cli");
5369
+ .find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
6139
5370
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
6140
- return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='external-cli', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
5371
+ return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='${externalAgent.runner?.type}', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
6141
5372
  }
6142
5373
  const foregroundTimeout = resolveSingleAgentLaunchTimeout(
6143
5374
  effectiveParams,
@@ -6221,20 +5452,20 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6221
5452
  }
6222
5453
  const sessionDirForIndex = (idx?: number) =>
6223
5454
  path.join(sessionRoot, `run-${idx ?? 0}`);
6224
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride) => {
5455
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6225
5456
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
6226
- prepareForkThinking(agentName, idx, modelOverride);
5457
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6227
5458
  return forkSessionFileForIndex(idx);
6228
5459
  };
6229
- const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride) => {
5460
+ const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6230
5461
  if (!shouldForkAgent(contextPolicy, agentName)) return delegatedThinkingOverride;
6231
- prepareForkThinking(agentName, idx, modelOverride);
5462
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6232
5463
  const override = forkThinkingOverrideForIndex(idx);
6233
5464
  if (override === "off") forkThinkingDowngrades.set(idx, agentName);
6234
5465
  return override ?? delegatedThinkingOverride;
6235
5466
  };
6236
- const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride) =>
6237
- forkSessionFileForTask(agentName, idx, modelOverride) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
5467
+ const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent) =>
5468
+ forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
6238
5469
  const childSessionFileForIndex = (idx?: number) =>
6239
5470
  path.join(sessionDirForIndex(idx), "session.jsonl");
6240
5471
  try {
@@ -6416,6 +5647,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6416
5647
  };
6417
5648
  deps.state.foregroundControls.set(runId, foregroundControl);
6418
5649
  deps.state.lastForegroundControlId = runId;
5650
+ deps.activateSupervisorTransport?.();
5651
+ deps.refreshResultDelivery?.();
6419
5652
  }
6420
5653
 
6421
5654
  const writeNestedForegroundEvent = (type: "subagent.nested.started" | "subagent.nested.completed", result?: AgentToolResult<Details>): void => {
@@ -6449,7 +5682,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6449
5682
  startedLaunches = selectedAgentNames.map((agent) => ({ agent }));
6450
5683
  }
6451
5684
  const agentsForSummary = startedLaunches.map((launch) => launch.agent);
6452
- const leafIntercomTarget = intercomBridge.active && agentsForSummary[0]
5685
+ const leafIntercomTarget = agentsForSummary[0] && intercomBridgeAppliesToAgent(intercomBridge, contextPolicy, agentsForSummary[0])
6453
5686
  ? resolveSubagentIntercomTarget(runId, agentsForSummary[0], 0)
6454
5687
  : undefined;
6455
5688
  try {
@@ -6532,16 +5765,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6532
5765
  nestedForegroundStarted = true;
6533
5766
  }
6534
5767
  const runFanoutAnnotateContent = !delegatedExecution;
6535
- if (hasChain && effectiveParams.chain) {
6536
- const result = await runChainPath(execData, deps);
6537
- writeNestedForegroundEvent("subagent.nested.completed", result);
6538
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
6539
- }
6540
- if (hasTasks && effectiveParams.tasks) {
6541
- const result = await runParallelPath(execData, deps);
6542
- writeNestedForegroundEvent("subagent.nested.completed", result);
6543
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
6544
- }
6545
5768
  if (hasSingle) {
6546
5769
  const result = await runSinglePath(execData, deps);
6547
5770
  writeNestedForegroundEvent("subagent.nested.completed", result);
@@ -6598,7 +5821,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6598
5821
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
6599
5822
  ctx: ExtensionContext,
6600
5823
  ): Promise<AgentToolResult<Details>> => {
6601
- const normalized = normalizePublicSubagentExecution(params);
5824
+ const normalized = normalizePublicSubagentExecution(params, { asyncByDefault: deps.asyncByDefault });
6602
5825
  if (!normalized.ok) {
6603
5826
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
6604
5827
  }