@xzzpig/pi-subagents 0.1.0 → 0.2.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 (81) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +342 -0
  5. package/docs/configuration.md +328 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +119 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +174 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +17 -8
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/project-panes.ts +30 -0
  22. package/src/extension/config.ts +28 -1
  23. package/src/extension/fanout-child.ts +5 -4
  24. package/src/extension/index.ts +75 -30
  25. package/src/extension/rpc.ts +7 -6
  26. package/src/extension/schemas.ts +29 -8
  27. package/src/extension/subagent-guide.ts +39 -0
  28. package/src/extension/tool-description.ts +30 -12
  29. package/src/inspectors/herdr/project-panes.ts +459 -63
  30. package/src/intercom/native-supervisor-channel.ts +102 -4
  31. package/src/missions/actions.ts +25 -2
  32. package/src/missions/lifecycle.ts +21 -2
  33. package/src/missions/store.ts +79 -2
  34. package/src/missions/types.ts +33 -0
  35. package/src/missions/workflow-state.ts +19 -13
  36. package/src/runs/background/active-run-index.ts +42 -0
  37. package/src/runs/background/async-execution.ts +17 -6
  38. package/src/runs/background/async-job-tracker.ts +293 -133
  39. package/src/runs/background/async-resume.ts +19 -3
  40. package/src/runs/background/async-status.ts +33 -5
  41. package/src/runs/background/completion-replay.ts +267 -0
  42. package/src/runs/background/control-channel.ts +95 -54
  43. package/src/runs/background/result-watcher.ts +113 -10
  44. package/src/runs/background/resume-guidance.ts +33 -0
  45. package/src/runs/background/run-status.ts +18 -0
  46. package/src/runs/background/scheduled-runs.ts +25 -1
  47. package/src/runs/background/stale-run-reconciler.ts +12 -24
  48. package/src/runs/background/subagent-runner.ts +69 -11
  49. package/src/runs/background/subagent-wait.ts +5 -2
  50. package/src/runs/background/wait-completions.ts +39 -5
  51. package/src/runs/background/wait-subscriptions.ts +21 -5
  52. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  53. package/src/runs/foreground/async-steering-action.ts +7 -8
  54. package/src/runs/foreground/chain-execution.ts +3 -0
  55. package/src/runs/foreground/execution.ts +7 -0
  56. package/src/runs/foreground/foreground-history.ts +137 -0
  57. package/src/runs/foreground/subagent-executor.ts +466 -61
  58. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  59. package/src/runs/shared/dynamic-fanout.ts +1 -1
  60. package/src/runs/shared/model-fallback.ts +8 -4
  61. package/src/runs/shared/model-scope.ts +12 -2
  62. package/src/runs/shared/parallel-utils.ts +1 -0
  63. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  64. package/src/runs/shared/worktree.ts +3 -2
  65. package/src/shared/artifacts.ts +15 -15
  66. package/src/shared/display-text.ts +100 -0
  67. package/src/shared/file-coalescer.ts +9 -0
  68. package/src/shared/fork-context.ts +13 -0
  69. package/src/shared/formatters.ts +4 -6
  70. package/src/shared/prompt-resources.ts +51 -0
  71. package/src/shared/settings.ts +15 -2
  72. package/src/shared/types.ts +45 -2
  73. package/src/shared/utf8.ts +11 -0
  74. package/src/shared/utils.ts +43 -33
  75. package/src/slash/prompt-workflows.ts +2 -15
  76. package/src/slash/slash-commands.ts +22 -2
  77. package/src/tui/fleet-status.ts +22 -12
  78. package/src/tui/fleet.ts +135 -25
  79. package/src/tui/render.ts +150 -33
  80. package/src/watchdog/change-signature.ts +4 -3
  81. package/src/workflows/scripted-workflow.ts +210 -13
@@ -4,7 +4,7 @@ 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
6
  import { resolveAgentName, type AgentConfig, type AgentScope } from "../../agents/agents.ts";
7
- import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning } from "../../shared/artifacts.ts";
7
+ import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { ChainClarifyComponent, type ChainClarifyResult } from "./chain-clarify.ts";
10
10
  import { resolveEffectiveThinking, toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
@@ -17,10 +17,12 @@ import {
17
17
  settleForegroundSchedulingOwner,
18
18
  updateForegroundChild,
19
19
  } from "./foreground-control.ts";
20
+ import { persistForegroundRunHistory, MAX_REMEMBERED_FOREGROUND_RUNS } from "./foreground-history.ts";
20
21
  import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
21
22
  import { handleManagementAction } from "../../agents/agent-management.ts";
22
23
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
23
24
  import { buildDoctorReport } from "../../extension/doctor.ts";
25
+ import { readSubagentGuide } from "../../extension/subagent-guide.ts";
24
26
  import { normalizePublicSubagentExecution } from "../../extension/public-execution.ts";
25
27
  import { runSync } from "./execution.ts";
26
28
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
@@ -37,6 +39,7 @@ import {
37
39
  isParallelStep,
38
40
  isDynamicParallelStep,
39
41
  resolveChainPath,
42
+ resolveExistingReadPaths,
40
43
  resolveStepBehavior,
41
44
  suppressProgressForReadOnlyTask,
42
45
  taskDisallowsFileUpdates,
@@ -49,8 +52,9 @@ import {
49
52
  type StepOverrides,
50
53
  } from "../../shared/settings.ts";
51
54
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
52
- import { buildAsyncRunnerSteps, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable } from "../background/async-execution.ts";
53
- import type { ScheduledRunAction } from "../background/scheduled-runs.ts";
55
+ import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
56
+ import { updateActiveRunIndex } from "../background/active-run-index.ts";
57
+ import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
54
58
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
55
59
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
56
60
  import { normalizeGateAcceptance, validateExecutionAcceptance } from "../shared/acceptance.ts";
@@ -82,22 +86,32 @@ import { applySteeringRecoveryAgentConfig, buildRevivedAsyncTask, resolveAsyncRe
82
86
  import { deliverCheckpointDecisionRequest, deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
83
87
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
84
88
  import { steerAsyncRun } from "./async-steering-action.ts";
89
+ import {
90
+ removeWorkflowForegroundSteeringRoute,
91
+ resolveWorkflowForegroundSteeringTarget,
92
+ steerWorkflowForegroundTarget,
93
+ workflowForegroundSteeringDir,
94
+ workflowForegroundSteeringLaunchOptions,
95
+ } from "./workflow-foreground-steering.ts";
85
96
  import { stopAsyncRun } from "./async-stop-action.ts";
97
+ import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
86
98
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
87
- import { resolveAsyncRootResultPath } from "../background/chain-root-attachment.ts";
99
+ import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
88
100
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
89
101
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
90
102
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
91
103
  import { inspectSubagentStatus } from "../background/run-status.ts";
92
104
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
93
105
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
94
- import { attachMissionToLaunchResult, prepareMissionLaunch, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
106
+ import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
95
107
  import { updateMission } from "../../missions/store.ts";
108
+ import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
96
109
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
97
110
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
98
111
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
99
112
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
100
113
  import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowScriptChildResult } from "../../workflows/scripted-workflow.ts";
114
+ import { renderWorkflowPrompt } from "../../shared/prompt-resources.ts";
101
115
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
102
116
  import {
103
117
  cleanupWorktrees,
@@ -150,7 +164,48 @@ import {
150
164
  wrapForkTask,
151
165
  } from "../../shared/types.ts";
152
166
 
153
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
167
+ 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"]);
168
+ 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"]);
169
+
170
+ function editDistance(left: string, right: string): number {
171
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
172
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
173
+ let diagonal = previous[0]!;
174
+ previous[0] = leftIndex;
175
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
176
+ const above = previous[rightIndex]!;
177
+ previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
178
+ ? diagonal
179
+ : Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
180
+ diagonal = above;
181
+ }
182
+ }
183
+ return previous[right.length]!;
184
+ }
185
+
186
+ function hasSingleAdjacentTransposition(left: string, right: string): boolean {
187
+ if (left.length !== right.length) return false;
188
+ const mismatch = [...left].findIndex((character, index) => character !== right[index]);
189
+ return mismatch >= 0
190
+ && left[mismatch] === right[mismatch + 1]
191
+ && left[mismatch + 1] === right[mismatch]
192
+ && left.slice(mismatch + 2) === right.slice(mismatch + 2);
193
+ }
194
+
195
+ export function unknownSubagentActionMessage(action: string): string {
196
+ const requested = action.toLowerCase();
197
+ const suggestion = SUBAGENT_ACTIONS.find((candidate) => {
198
+ const distance = editDistance(requested, candidate);
199
+ const closeMatch = distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate);
200
+ if (DESTRUCTIVE_MANAGEMENT_ACTIONS.has(candidate)) return distance === 1 && requested.length >= candidate.length - 1;
201
+ return closeMatch;
202
+ });
203
+ const nextStep = 'Use subagent({ action: "status" }) to inspect runs or subagent({ action: "list" }) to inspect agents.';
204
+ const validActions = `Valid: ${SUBAGENT_ACTIONS.join(", ")}.`;
205
+ return suggestion
206
+ ? `Unknown action: ${action}. Did you mean ${suggestion}? ${nextStep} ${validActions}`
207
+ : `Unknown action: ${action}. ${nextStep} ${validActions}`;
208
+ }
154
209
 
155
210
  type UndefinedOmitted<T extends object> = {
156
211
  [K in keyof T as undefined extends T[K] ? never : K]: T[K];
@@ -209,6 +264,7 @@ export interface SubagentParamsLike {
209
264
  index?: number;
210
265
  view?: "fleet" | "transcript";
211
266
  lines?: number;
267
+ topic?: string;
212
268
  chainName?: string;
213
269
  config?: unknown;
214
270
  name?: string;
@@ -226,6 +282,7 @@ export interface SubagentParamsLike {
226
282
  /** Internal workflow ownership metadata; not part of the public schema. */
227
283
  workflowParentRunId?: string;
228
284
  workflowKey?: string;
285
+ workflowChildAsyncId?: string;
229
286
  suppressRoutineResultIntercom?: boolean;
230
287
  /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
231
288
  chain?: ChainStep[];
@@ -356,6 +413,7 @@ function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefine
356
413
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
357
414
  const control = state.foregroundControls.get(runId);
358
415
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
416
+ if (control) removeWorkflowForegroundSteeringRoute(control);
359
417
  state.foregroundControls.delete(runId);
360
418
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
361
419
  return true;
@@ -473,7 +531,7 @@ function foregroundStatusResult(control: SubagentState["foregroundControls"] ext
473
531
 
474
532
  function trimRememberedForegroundRuns(state: SubagentState): void {
475
533
  if (!state.foregroundRuns) return;
476
- while (state.foregroundRuns.size > 50) {
534
+ while (state.foregroundRuns.size > MAX_REMEMBERED_FOREGROUND_RUNS) {
477
535
  const oldestTerminal = [...state.foregroundRuns.values()]
478
536
  .filter((run) => !run.children.some((child) => child.status === "detached"))
479
537
  .sort((left, right) => left.updatedAt - right.updatedAt)[0];
@@ -482,6 +540,14 @@ function trimRememberedForegroundRuns(state: SubagentState): void {
482
540
  }
483
541
  }
484
542
 
543
+ function persistRememberedForegroundRuns(state: SubagentState): void {
544
+ try {
545
+ persistForegroundRunHistory(state);
546
+ } catch (error) {
547
+ console.error("Failed to persist foreground run history:", error);
548
+ }
549
+ }
550
+
485
551
  function foregroundChildActivityFromProgress(progress: SingleResult["progress"] | undefined) {
486
552
  return {
487
553
  ...(progress?.activityState ? { activityState: progress.activityState } : {}),
@@ -548,6 +614,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
548
614
  }),
549
615
  });
550
616
  trimRememberedForegroundRuns(state);
617
+ persistRememberedForegroundRuns(state);
551
618
  }
552
619
 
553
620
  function applyControlEventToRememberedForegroundRun(state: SubagentState, event: ControlEvent): void {
@@ -623,6 +690,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
623
690
  ...(input.result.capabilityAudit ? { capabilityAudit: input.result.capabilityAudit } : {}),
624
691
  });
625
692
  trimRememberedForegroundRuns(state);
693
+ persistRememberedForegroundRuns(state);
626
694
  const output = getSingleResultOutput(input.result).trim();
627
695
  const success = terminalStatus === "completed";
628
696
  const summary = !success && input.result.error
@@ -868,8 +936,15 @@ function interruptAsyncRun(
868
936
  details: { mode: "management", results: [] },
869
937
  };
870
938
  }
939
+ if (status.mode === "workflow") {
940
+ return {
941
+ content: [{ type: "text", text: `Interrupt is unsupported for async workflow ${target.asyncId}; use stop instead.` }],
942
+ isError: true,
943
+ details: { mode: "management", results: [] },
944
+ };
945
+ }
871
946
  try {
872
- deliverInterruptRequest(omitUndefinedProperties({ asyncDir: target.asyncDir, pid: status.pid, kill, source: "interrupt-action" }));
947
+ deliverInterruptRequest({ asyncDir: target.asyncDir, source: "interrupt-action" });
873
948
  const tracked = state.asyncJobs.get(target.asyncId);
874
949
  if (tracked) {
875
950
  delete tracked.activityState;
@@ -1178,7 +1253,7 @@ function directNestedAsyncInterrupt(target: ResolvedSubagentRunId & { kind: "nes
1178
1253
  const pid = typeof status?.pid === "number" && status.pid > 0 ? status.pid : run.pid;
1179
1254
  if (!status || status.state !== "running" || typeof pid !== "number" || pid <= 0) return undefined;
1180
1255
  try {
1181
- deliverInterruptRequest({ asyncDir, pid, source: "nested-interrupt" });
1256
+ deliverInterruptRequest({ asyncDir, source: "nested-interrupt" });
1182
1257
  return { content: [{ type: "text", text: `Interrupt requested for nested async run ${run.id}.` }], details: { mode: "management", results: [] } };
1183
1258
  } catch (error) {
1184
1259
  const message = error instanceof Error ? error.message : String(error);
@@ -1270,6 +1345,7 @@ async function resumeAsyncRun(input: {
1270
1345
  deps: ExecutorDeps;
1271
1346
  parentModel?: ParentModel;
1272
1347
  absoluteDeadlineAt?: number;
1348
+ signal?: AbortSignal;
1273
1349
  }): Promise<AgentToolResult<Details>> {
1274
1350
  const followUp = (input.params.message ?? input.params.task ?? "").trim();
1275
1351
  const attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain as ChainStep[] : undefined;
@@ -1385,7 +1461,7 @@ async function resumeAsyncRun(input: {
1385
1461
  inheritProjectContext: recoveryDescriptor.inheritProjectContext,
1386
1462
  inheritSkills: recoveryDescriptor.inheritSkills,
1387
1463
  source: "project",
1388
- filePath: recoveryDescriptor.agentFilePath ?? path.join(recoveryDescriptor.cwd, ".pi-subagents-recovery-agent"),
1464
+ filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
1389
1465
  } : undefined);
1390
1466
  if (!agentConfig) {
1391
1467
  return {
@@ -1556,6 +1632,58 @@ async function resumeAsyncRun(input: {
1556
1632
  }
1557
1633
 
1558
1634
  const revivedId = result.details.asyncId ?? runId;
1635
+ if (input.params.workflowParentRunId !== undefined && result.details.asyncDir) {
1636
+ const asyncDir = result.details.asyncDir;
1637
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
1638
+ const stopOnAbort = () => { stopAsyncRun(input.deps.state, revivedId, input.deps.kill, { asyncDir, resolvedId: revivedId }); };
1639
+ if (input.signal?.aborted) stopOnAbort();
1640
+ else input.signal?.addEventListener("abort", stopOnAbort, { once: true });
1641
+ let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
1642
+ try {
1643
+ completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 });
1644
+ } finally {
1645
+ input.signal?.removeEventListener("abort", stopOnAbort);
1646
+ }
1647
+ fs.rmSync(resultPath, { force: true });
1648
+ const totalCost = completed.totalCost;
1649
+ const childResult: SingleResult = {
1650
+ index: 0,
1651
+ agent: completed.agent,
1652
+ task: effectiveFollowUp,
1653
+ exitCode: completed.exitCode,
1654
+ usage: {
1655
+ input: totalCost?.inputTokens ?? 0,
1656
+ output: totalCost?.outputTokens ?? 0,
1657
+ cacheRead: 0,
1658
+ cacheWrite: 0,
1659
+ cost: totalCost?.costUsd ?? 0,
1660
+ turns: 0,
1661
+ },
1662
+ finalOutput: completed.output,
1663
+ outputState: completed.output.trim() ? "present" : "absent",
1664
+ ...(completed.error ? { error: completed.error } : {}),
1665
+ ...(completed.timedOut ? { timedOut: true } : {}),
1666
+ ...(completed.stopped ? { stopped: true } : {}),
1667
+ ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
1668
+ ...(completed.model ? { model: completed.model } : {}),
1669
+ ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
1670
+ ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
1671
+ ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
1672
+ ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
1673
+ ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
1674
+ ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
1675
+ };
1676
+ return {
1677
+ content: [{ type: "text", text: completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
1678
+ ...(completed.success ? {} : { isError: true }),
1679
+ details: {
1680
+ ...result.details,
1681
+ runId: revivedId,
1682
+ results: [childResult],
1683
+ ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
1684
+ },
1685
+ };
1686
+ }
1559
1687
  const revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;
1560
1688
  const sourceLabel = target.source;
1561
1689
  const lines = [
@@ -1979,7 +2107,17 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
1979
2107
 
1980
2108
  export const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;
1981
2109
 
1982
- function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
2110
+ // Async single-agent runs also need a wall-clock backstop: a child whose bash
2111
+ // tool blocks forever (e.g. a background process inheriting the terminal with
2112
+ // no bash `timeout` arg) would otherwise hang the parent indefinitely with
2113
+ // zero signal. Same generous default as foreground; explicit timeoutMs/
2114
+ // maxRuntimeMs and agent-level defaultTimeoutMs remain authoritative.
2115
+ //
2116
+ // Deliberately NOT applied at the workflow level: async scripted workflows
2117
+ // stay unbounded as a whole, while each runner child has its own deadline.
2118
+ export { DEFAULT_ASYNC_TIMEOUT_MS };
2119
+
2120
+ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
1983
2121
  const rawTimeout = params.timeoutMs;
1984
2122
  const rawMaxRuntime = params.maxRuntimeMs;
1985
2123
  if (rawTimeout === undefined && rawMaxRuntime === undefined) {
@@ -1998,6 +2136,21 @@ function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?:
1998
2136
  return timeoutMs === undefined ? {} : { timeoutMs };
1999
2137
  }
2000
2138
 
2139
+ /**
2140
+ * Resolve the effective launch timeout for a single-agent run, applying the
2141
+ * async/foreground default when neither the caller nor the agent set one.
2142
+ *
2143
+ * The async default is deliberately applied only to plain single-agent
2144
+ * launches. Composite launches keep their top-level execution unbounded when
2145
+ * no timeout is set; their runner children resolve separate deadlines.
2146
+ * Exported so the executor wiring is directly testable.
2147
+ */
2148
+ export function resolveSingleAgentLaunchTimeout(params: SubagentParamsLike, async: boolean): { timeoutMs?: number; error?: string } {
2149
+ const isComposite = (params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || params.workflowScript !== undefined;
2150
+ const defaultTimeoutMs = !async ? DEFAULT_FOREGROUND_TIMEOUT_MS : isComposite ? undefined : DEFAULT_ASYNC_TIMEOUT_MS;
2151
+ return resolveForegroundTimeout(params, defaultTimeoutMs);
2152
+ }
2153
+
2001
2154
  function resolveToolBudget(
2002
2155
  raw: unknown,
2003
2156
  label = "toolBudget",
@@ -2407,7 +2560,8 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2407
2560
  details: { mode: "single" as const, results: [] },
2408
2561
  };
2409
2562
  }
2410
- const id = randomUUID();
2563
+ const requestedWorkflowChildAsyncId = typeof params.workflowChildAsyncId === "string" ? params.workflowChildAsyncId.trim() : "";
2564
+ const id = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId ? requestedWorkflowChildAsyncId : randomUUID();
2411
2565
  const parentModel = data.parentModel;
2412
2566
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2413
2567
  pi: deps.pi,
@@ -3037,6 +3191,7 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3037
3191
  const result = await runSync(input.ctx.cwd, input.agents, task.agent, taskText, compactOptional<Parameters<typeof runSync>[4]>({
3038
3192
  permissions: input.permissions,
3039
3193
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
3194
+ ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, index),
3040
3195
  context: input.contextPolicy.contextForAgent(task.agent),
3041
3196
  cwd: taskCwd,
3042
3197
  signal: input.signal,
@@ -3712,8 +3867,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3712
3867
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3713
3868
  // absolute paths pass through; relative paths resolve against the child cwd.
3714
3869
  const reads = readsOverride !== undefined ? readsOverride : agentConfig.defaultReads ?? false;
3715
- const readsInstruction = Array.isArray(reads) && reads.length > 0
3716
- ? `[Read from: ${reads.map((f) => resolveChainPath(f, effectiveCwd)).join(", ")}]\n\n`
3870
+ const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, effectiveCwd) : [];
3871
+ const readsInstruction = readPaths.length > 0
3872
+ ? `[Read from: ${readPaths.join(", ")}]\n\n`
3717
3873
  : "";
3718
3874
  task = readsInstruction + task;
3719
3875
  task = injectSingleOutputInstruction(task, outputPath, agentConfig);
@@ -3757,6 +3913,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3757
3913
  r = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3758
3914
  permissions: deps.config.permissions,
3759
3915
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3916
+ ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3760
3917
  context: data.contextPolicy.contextForAgent(params.agent!),
3761
3918
  cwd: effectiveCwd,
3762
3919
  signal,
@@ -3935,6 +4092,63 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
3935
4092
  };
3936
4093
  }
3937
4094
 
4095
+ const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string }) => void>();
4096
+
4097
+ function recordMissionWorkflowChild(
4098
+ binding: MissionLaunchBinding | undefined,
4099
+ workflowRunId: string,
4100
+ key: string,
4101
+ update: Omit<MissionWorkflowChildUpdate, "workflowRunId" | "key">,
4102
+ ): void {
4103
+ if (!binding) return;
4104
+ try {
4105
+ updateMission(binding.location, binding.missionId, { upsertWorkflowChildren: [{ workflowRunId, key, ...update }] });
4106
+ } catch (error) {
4107
+ console.warn(`[pi-subagents] Failed to record mission workflow child '${key}': ${error instanceof Error ? error.message : String(error)}`);
4108
+ }
4109
+ }
4110
+
4111
+ export function missionWorkflowChildStatus(result: AgentToolResult<Details>): string {
4112
+ const childResults = result.details.results;
4113
+ if (childResults.some((child) => child.detached || child.interrupted)) return "paused";
4114
+ if (result.isError === true || childResults.some((child) => child.exitCode !== 0)) return "failed";
4115
+ if (childResults.length === 0 && (result.details.asyncId || result.details.asyncDir)) return "running";
4116
+ return "completed";
4117
+ }
4118
+
4119
+ export async function runMissionWorkflowChild(
4120
+ binding: MissionLaunchBinding | undefined,
4121
+ workflowRunId: string,
4122
+ key: string,
4123
+ phase: string | undefined,
4124
+ run: () => Promise<AgentToolResult<Details>>,
4125
+ ): Promise<AgentToolResult<Details>> {
4126
+ try {
4127
+ return await run();
4128
+ } catch (error) {
4129
+ recordMissionWorkflowChild(binding, workflowRunId, key, {
4130
+ status: "failed",
4131
+ completedAt: new Date().toISOString(),
4132
+ heartbeat: { status: "failed", ...(phase ? { phase } : {}), message: error instanceof Error ? error.message : String(error) },
4133
+ });
4134
+ throw error;
4135
+ }
4136
+ }
4137
+
4138
+ export function bindMissionWorkflowChildAsyncLaunch(
4139
+ params: SubagentParamsLike,
4140
+ binding: MissionLaunchBinding | undefined,
4141
+ asyncByDefault: boolean,
4142
+ asyncId: string = randomUUID(),
4143
+ ): SubagentParamsLike {
4144
+ const requestedAsync = params.async ?? asyncByDefault;
4145
+ if (!binding || !requestedAsync || params.clarify === true) return params;
4146
+ const id = asyncId.trim();
4147
+ if (!id || path.basename(id) !== id) throw new Error("workflow child async id must be a single path segment");
4148
+ writeMissionAsyncBinding(path.join(DIRS.async, id), binding);
4149
+ return { ...params, workflowChildAsyncId: id };
4150
+ }
4151
+
3938
4152
  function workflowChildResult(key: string, result: AgentToolResult<Details>): WorkflowScriptChildResult {
3939
4153
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
3940
4154
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
@@ -3951,9 +4165,11 @@ function workflowChildResult(key: string, result: AgentToolResult<Details>): Wor
3951
4165
  if (child.sessionFile) artifactPaths.add(child.sessionFile);
3952
4166
  }
3953
4167
  const structured = result.details.results.map((child) => child.structuredOutput).filter((value) => value !== undefined);
4168
+ const resolvedAgents = [...new Set(result.details.results.map((child) => child.agent).filter((agent): agent is string => Boolean(agent)))];
3954
4169
  return {
3955
4170
  key,
3956
4171
  ok,
4172
+ ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
3957
4173
  ...(result.details.runId || result.details.asyncId ? { runId: result.details.runId ?? result.details.asyncId } : {}),
3958
4174
  output,
3959
4175
  ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
@@ -3991,6 +4207,7 @@ export function prepareWorkflowLaunchParams(
3991
4207
  }
3992
4208
  const launchParams = {
3993
4209
  ...workflowDefaults,
4210
+ async: false,
3994
4211
  ...childParams,
3995
4212
  ...(options.missionDetached ? { mission: false } : {}),
3996
4213
  workflowParentRunId: parentWorkflowRunId,
@@ -4152,6 +4369,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4152
4369
  ctx: ExtensionContext,
4153
4370
  preserveActiveSession = false,
4154
4371
  ): Promise<AgentToolResult<Details>> => {
4372
+ const workflowLaunchObserver = workflowLaunchObservers.get(params);
4155
4373
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4156
4374
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4157
4375
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
@@ -4168,6 +4386,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4168
4386
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
4169
4387
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
4170
4388
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4389
+ const workflowPrompts = { render: (ref: string, vars?: unknown) => renderWorkflowPrompt(ref, vars, workflowCwd) };
4171
4390
  const chatProgressResult = resolveWorkflowChatProgress({ requested: requestParams.chatProgress, parentCwd, workflowCwd, background: requestParams.async !== false });
4172
4391
  if (chatProgressResult.error) return { content: [{ type: "text", text: chatProgressResult.error }], isError: true, details: { mode: "workflow", results: [] } };
4173
4392
  const chatProgress = chatProgressResult.projection!;
@@ -4247,9 +4466,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4247
4466
  workflow: { trace: [], emits: [], console: [] },
4248
4467
  };
4249
4468
  const appendWorkflowEvent = (event: Record<string, unknown>) => fs.appendFileSync(eventsPath, `${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\n`, "utf-8");
4469
+ let indexedState: AsyncStatus["state"] | undefined;
4250
4470
  const persist = () => {
4251
4471
  status.lastUpdate = Date.now();
4252
4472
  writeAtomicJson(statusPath, status);
4473
+ if (indexedState !== status.state) {
4474
+ updateActiveRunIndex(asyncDir, status.state);
4475
+ indexedState = status.state;
4476
+ }
4253
4477
  const job = deps.state.asyncJobs.get(workflowRunId);
4254
4478
  if (job) {
4255
4479
  job.status = status.state;
@@ -4273,7 +4497,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4273
4497
  }
4274
4498
  };
4275
4499
  const projectWorkflowActivity = () => {
4276
- const runningSteps = (status.steps ?? []).filter((step) => step.status === "running");
4500
+ const steps = status.steps ?? [];
4501
+ const runningSteps = steps.filter((step) => step.status === "running");
4277
4502
  const lastActivityAt = runningSteps.reduce<number | undefined>((latest, step) => step.lastActivityAt === undefined ? latest : Math.max(latest ?? step.lastActivityAt, step.lastActivityAt), undefined);
4278
4503
  const activeToolStep = runningSteps
4279
4504
  .filter((step) => step.currentTool)
@@ -4286,11 +4511,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4286
4511
  status.currentTool = activeToolStep?.currentTool;
4287
4512
  status.currentToolStartedAt = activeToolStep?.currentToolStartedAt;
4288
4513
  status.currentPath = activeToolStep?.currentPath;
4289
- const turnCounts = (status.steps ?? []).flatMap((step) => step.turnCount === undefined ? [] : [step.turnCount]);
4290
- const toolCounts = (status.steps ?? []).flatMap((step) => step.toolCount === undefined ? [] : [step.toolCount]);
4514
+ const turnCounts = steps.flatMap((step) => step.turnCount === undefined ? [] : [step.turnCount]);
4515
+ const toolCounts = steps.flatMap((step) => step.toolCount === undefined ? [] : [step.toolCount]);
4291
4516
  status.turnCount = turnCounts.length > 0 ? turnCounts.reduce((total, count) => total + count, 0) : undefined;
4292
4517
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4293
- status.currentStep = runningSteps.length === 1 ? status.steps?.indexOf(runningSteps[0]!) : undefined;
4518
+ status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4294
4519
  };
4295
4520
  const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, cwd: workflowCwd, status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
4296
4521
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
@@ -4302,22 +4527,41 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4302
4527
  void Promise.resolve().then(async () => {
4303
4528
  const workflowResults: SingleResult[] = [];
4304
4529
  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;
4530
+ const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
4531
+ let projectedTraceLength = 0;
4532
+ let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
4305
4533
  const updateTrace = (trace: NonNullable<Details["workflow"]>["trace"]) => {
4306
4534
  status.workflow = { ...(status.workflow ?? { emits: [], console: [] }), trace };
4307
- for (const entry of trace.filter((candidate) => candidate.operation === "run")) {
4308
- const existing = status.steps?.find((step) => step.workflowKey === entry.key);
4535
+ const rebuild = trace.length < projectedTraceLength
4536
+ || (projectedTraceLength > 0 && trace[projectedTraceLength - 1] !== projectedTraceTail);
4537
+ if (rebuild) {
4538
+ workflowSteps.clear();
4539
+ for (const step of status.steps ?? []) {
4540
+ if (step.workflowKey) workflowSteps.set(step.workflowKey, step);
4541
+ }
4542
+ projectedTraceLength = 0;
4543
+ }
4544
+ for (let index = projectedTraceLength; index < trace.length; index += 1) {
4545
+ const entry = trace[index]!;
4546
+ if (entry.operation !== "run") continue;
4547
+ const existing = workflowSteps.get(entry.key);
4309
4548
  if (entry.state === "reused" && existing) continue;
4310
4549
  const mapped = entry.state === "started" || entry.state === "reused" ? "running" : entry.state === "completed" ? "completed" : "failed";
4311
4550
  if (existing) {
4312
4551
  existing.status = mapped;
4552
+ if (entry.agent) existing.agent = entry.agent;
4313
4553
  if (entry.error === undefined) delete existing.error;
4314
4554
  else existing.error = entry.error;
4315
4555
  if (entry.durationMs === undefined) delete existing.durationMs;
4316
4556
  else existing.durationMs = entry.durationMs;
4317
4557
  } else {
4318
- status.steps?.push({ agent: entry.key, label: entry.key, workflowKey: entry.key, parentWorkflowRunId: workflowRunId, status: mapped, startedAt: Date.now() });
4558
+ const step: NonNullable<AsyncStatus["steps"]>[number] = { agent: entry.agent ?? entry.key, label: entry.key, workflowKey: entry.key, parentWorkflowRunId: workflowRunId, status: mapped, startedAt: Date.now() };
4559
+ status.steps?.push(step);
4560
+ workflowSteps.set(entry.key, step);
4319
4561
  }
4320
4562
  }
4563
+ projectedTraceLength = trace.length;
4564
+ projectedTraceTail = trace.at(-1);
4321
4565
  projectWorkflowActivity();
4322
4566
  persist();
4323
4567
  appendWorkflowEvent({ type: "subagent.workflow.trace", trace });
@@ -4327,6 +4571,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4327
4571
  script: workflowScript,
4328
4572
  timeoutMs: timeout,
4329
4573
  signal: controller.signal,
4574
+ prompts: workflowPrompts,
4330
4575
  ...(workflowState ? { state: workflowState } : {}),
4331
4576
  onTrace: updateTrace,
4332
4577
  onEmit: (emits) => {
@@ -4340,30 +4585,70 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4340
4585
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4341
4586
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4342
4587
  patchMissionObjective(childParams.task);
4343
- const childRequest = prepareWorkflowLaunchParams(workflowChildDefaults, childParams, workflowRunId, key, { missionDetached: detachWorkflowChildMissions });
4344
- const result = await execute(randomUUID(), childRequest, workflowSignal, (update) => {
4345
- const progress = update.details.progress?.[0];
4346
- const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4347
- if (!progress || !step) return;
4348
- step.status = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
4349
- step.activityState = progress.activityState;
4350
- step.lastActivityAt = progress.lastActivityAt;
4351
- step.currentTool = progress.currentTool;
4352
- step.currentToolArgs = progress.currentToolArgs;
4353
- step.currentToolStartedAt = progress.currentToolStartedAt;
4354
- step.currentPath = progress.currentPath;
4355
- step.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
4356
- step.recentOutput = [...progress.recentOutput];
4357
- step.turnCount = progress.turnCount;
4358
- step.toolCount = progress.toolCount;
4359
- step.model = progress.model;
4360
- step.thinking = progress.thinking;
4361
- step.error = progress.error;
4362
- projectWorkflowActivity();
4363
- persist();
4364
- }, ctx, preserveActiveSession);
4588
+ const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4589
+ const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4590
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
4591
+ status: "running",
4592
+ ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
4593
+ ...(typeof childParams.task === "string" && childParams.task.trim() ? { task: childParams.task.trim() } : {}),
4594
+ ...(childLabel ? { label: childLabel } : {}),
4595
+ ...(childPhase ? { phase: childPhase } : {}),
4596
+ heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4597
+ });
4598
+ const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4599
+ const childRequest = bindMissionWorkflowChildAsyncLaunch(
4600
+ prepareWorkflowLaunchParams(workflowChildDefaults, childParams, workflowRunId, key, { missionDetached: detachWorkflowChildMissions }),
4601
+ missionBinding,
4602
+ deps.asyncByDefault,
4603
+ );
4604
+ workflowLaunchObservers.set(childRequest, (launch) => {
4605
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4606
+ if (step) {
4607
+ step.agent = launch.agent;
4608
+ step.sessionFile = launch.sessionFile;
4609
+ persist();
4610
+ }
4611
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
4612
+ });
4613
+ return execute(randomUUID(), childRequest, workflowSignal, (update) => {
4614
+ const progress = update.details.progress?.[0];
4615
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4616
+ if (!progress || !step) return;
4617
+ step.status = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
4618
+ step.activityState = progress.activityState;
4619
+ step.lastActivityAt = progress.lastActivityAt;
4620
+ step.currentTool = progress.currentTool;
4621
+ step.currentToolArgs = progress.currentToolArgs;
4622
+ step.currentToolStartedAt = progress.currentToolStartedAt;
4623
+ step.currentPath = progress.currentPath;
4624
+ step.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
4625
+ step.recentOutput = [...progress.recentOutput];
4626
+ step.turnCount = progress.turnCount;
4627
+ step.toolCount = progress.toolCount;
4628
+ step.model = progress.model;
4629
+ step.thinking = progress.thinking;
4630
+ step.error = progress.error;
4631
+ projectWorkflowActivity();
4632
+ persist();
4633
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
4634
+ status: step.status,
4635
+ heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
4636
+ });
4637
+ }, ctx, preserveActiveSession);
4638
+ });
4365
4639
  workflowResults.push(...result.details.results);
4640
+ if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4366
4641
  const child = workflowChildResult(key, result);
4642
+ const childStatus = missionWorkflowChildStatus(result);
4643
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
4644
+ status: childStatus,
4645
+ ...(child.runId ? { runId: child.runId } : {}),
4646
+ ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
4647
+ ...(result.details.results[0]?.sessionFile ? { sessionPath: result.details.results[0].sessionFile } : {}),
4648
+ artifactPaths: child.artifactPaths,
4649
+ ...(["completed", "failed"].includes(childStatus) ? { completedAt: new Date().toISOString() } : {}),
4650
+ heartbeat: { status: childStatus, ...(childPhase ? { phase: childPhase } : {}) },
4651
+ });
4367
4652
  if (result.details.asyncId) {
4368
4653
  const childJob = deps.state.asyncJobs.get(result.details.asyncId);
4369
4654
  if (childJob) { childJob.parentWorkflowRunId = workflowRunId; childJob.workflowKey = key; }
@@ -4377,14 +4662,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4377
4662
  const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
4378
4663
  const workflowUsage = sumResultsUsage(workflowResults);
4379
4664
  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) };
4380
- writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary, output: summary, results: workflow.children.map((child) => ({ agent: child.key, ...(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 });
4665
+ writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary, output: summary, 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 });
4381
4666
  persist();
4382
4667
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: "complete" });
4383
4668
  } catch (error) {
4384
4669
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4385
4670
  const stopped = controller.signal.aborted;
4386
4671
  status = compactOptional<AsyncStatus>({ ...status, state: stopped ? "stopped" : "failed", stopped: stopped || undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
4387
- writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: status.error, error: status.error, stopped: status.stopped, results: partial.children.map((child) => ({ agent: child.key, ...(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 });
4672
+ writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: status.error, error: status.error, stopped: status.stopped, 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.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt });
4388
4673
  persist();
4389
4674
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, error: status.error });
4390
4675
  } finally {
@@ -4408,6 +4693,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4408
4693
  script: requestParams.workflowScript,
4409
4694
  timeoutMs: timeout,
4410
4695
  signal,
4696
+ prompts: workflowPrompts,
4411
4697
  ...(workflowState ? { state: workflowState } : {}),
4412
4698
  onTrace: (trace) => {
4413
4699
  liveWorkflow = { ...liveWorkflow, trace };
@@ -4422,10 +4708,51 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4422
4708
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4423
4709
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4424
4710
  patchMissionObjective(childParams.task);
4425
- const childRequest = prepareWorkflowLaunchParams(workflowChildDefaults, childParams, _id, key, { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card" });
4426
- const result = await execute(randomUUID(), childRequest, workflowSignal, undefined, ctx, preserveActiveSession);
4711
+ const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4712
+ const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4713
+ recordMissionWorkflowChild(missionBinding, _id, key, {
4714
+ status: "running",
4715
+ ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
4716
+ ...(typeof childParams.task === "string" && childParams.task.trim() ? { task: childParams.task.trim() } : {}),
4717
+ ...(childLabel ? { label: childLabel } : {}),
4718
+ ...(childPhase ? { phase: childPhase } : {}),
4719
+ heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4720
+ });
4721
+ const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4722
+ const childRequest = bindMissionWorkflowChildAsyncLaunch(
4723
+ prepareWorkflowLaunchParams(workflowChildDefaults, childParams, _id, key, { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card" }),
4724
+ missionBinding,
4725
+ deps.asyncByDefault,
4726
+ );
4727
+ workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
4728
+ status: "running",
4729
+ agent: launch.agent,
4730
+ ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}),
4731
+ }));
4732
+ return execute(randomUUID(), childRequest, workflowSignal, (update) => {
4733
+ const progress = update.details.progress?.[0];
4734
+ if (!progress) return;
4735
+ const progressStatus = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
4736
+ recordMissionWorkflowChild(missionBinding, _id, key, {
4737
+ status: progressStatus,
4738
+ heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
4739
+ });
4740
+ }, ctx, preserveActiveSession);
4741
+ });
4427
4742
  workflowResults.push(...result.details.results);
4428
- return workflowChildResult(key, result);
4743
+ if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4744
+ const child = workflowChildResult(key, result);
4745
+ const childStatus = missionWorkflowChildStatus(result);
4746
+ recordMissionWorkflowChild(missionBinding, _id, key, {
4747
+ status: childStatus,
4748
+ ...(child.runId ? { runId: child.runId } : {}),
4749
+ ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
4750
+ ...(result.details.results[0]?.sessionFile ? { sessionPath: result.details.results[0].sessionFile } : {}),
4751
+ artifactPaths: child.artifactPaths,
4752
+ ...(["completed", "failed"].includes(childStatus) ? { completedAt: new Date().toISOString() } : {}),
4753
+ heartbeat: { status: childStatus, ...(childPhase ? { phase: childPhase } : {}) },
4754
+ });
4755
+ return child;
4429
4756
  },
4430
4757
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
4431
4758
  });
@@ -4467,7 +4794,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4467
4794
  ? normalizeParentModel(ctx.model)
4468
4795
  : rememberParentModel(deps.state, requestSessionId, ctx.model);
4469
4796
  } catch (error) {
4470
- if (action?.toLowerCase() !== "doctor") throw error;
4797
+ if (action?.toLowerCase() !== "doctor" && action?.toLowerCase() !== "guide") throw error;
4471
4798
  requestParentModel = normalizeParentModel(ctx.model);
4472
4799
  }
4473
4800
  if (action) {
@@ -4649,6 +4976,20 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4649
4976
  details: { mode: "management", results: [], spawnBudget: granted.snapshot },
4650
4977
  };
4651
4978
  }
4979
+ if (action === "guide") {
4980
+ try {
4981
+ return {
4982
+ content: [{ type: "text", text: readSubagentGuide(paramsWithResolvedCwd.topic) }],
4983
+ details: { mode: "management", results: [] },
4984
+ };
4985
+ } catch (error) {
4986
+ return {
4987
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
4988
+ isError: true,
4989
+ details: { mode: "management", results: [] },
4990
+ };
4991
+ }
4992
+ }
4652
4993
  if (action === "children.list") {
4653
4994
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4654
4995
  const children = listRetainedChildren(DIRS.async, deps.state.currentSessionId);
@@ -4799,7 +5140,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4799
5140
  }
4800
5141
  }
4801
5142
  if (action === "resume") {
4802
- return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel }));
5143
+ return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
4803
5144
  }
4804
5145
  if (action === "steer") {
4805
5146
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
@@ -4810,6 +5151,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4810
5151
  try {
4811
5152
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
4812
5153
  const runId = location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
5154
+ const directoryStatus = location.asyncDir ? readStatus(location.asyncDir) : null;
5155
+ if (directoryStatus?.mode === "workflow") {
5156
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
5157
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5158
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5159
+ }
4813
5160
  if (location.asyncDir) {
4814
5161
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
4815
5162
  if (unsupported) return unsupported;
@@ -4845,8 +5192,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4845
5192
  return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
4846
5193
  }
4847
5194
  if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal }));
4848
- if (resolved?.kind === "foreground") return { content: [{ type: "text", text: "action='steer' currently supports live async Pi child sessions only; use action='interrupt' or action='resume' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
5195
+ if (resolved?.kind === "foreground") {
5196
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, childRunId: resolved.id, asyncDirRoot: DIRS.async });
5197
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5198
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5199
+ }
4849
5200
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5201
+ const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
5202
+ if (resolvedStatus?.mode === "workflow") {
5203
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
5204
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5205
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5206
+ }
4850
5207
  if (resolved.location.asyncDir) {
4851
5208
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
4852
5209
  if (unsupported) return unsupported;
@@ -4880,6 +5237,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4880
5237
  return appendStepToAsyncChain(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel }));
4881
5238
  }
4882
5239
  if (action.startsWith("schedule.")) {
5240
+ if (!isScheduledRunAction(action)) {
5241
+ return { content: [{ type: "text", text: unknownSubagentActionMessage(action) }], isError: true, details: { mode: "management", results: [] } };
5242
+ }
4883
5243
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4884
5244
  return {
4885
5245
  content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
@@ -4896,6 +5256,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4896
5256
  }
4897
5257
  return deps.handleScheduledRunAction(paramsWithResolvedCwd, ctx);
4898
5258
  }
5259
+ if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5260
+ return {
5261
+ content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
5262
+ isError: true,
5263
+ details: { mode: "management" as const, results: [] },
5264
+ };
5265
+ }
5266
+ if (action === "dismiss") {
5267
+ const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5268
+ if (!targetRunId) return { content: [{ type: "text", text: "action='dismiss' requires id." }], isError: true, details: { mode: "management", results: [] } };
5269
+ let resolved: ResolvedSubagentRunId | undefined;
5270
+ try {
5271
+ resolved = resolveSubagentRunId(targetRunId, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }));
5272
+ } catch (error) {
5273
+ const message = error instanceof Error ? error.message : String(error);
5274
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
5275
+ }
5276
+ if (resolved?.kind !== "async") {
5277
+ return { content: [{ type: "text", text: `Run '${targetRunId}' is not a recovered workflow.` }], isError: true, details: { mode: "management", results: [] } };
5278
+ }
5279
+ return dismissRecoveredWorkflow(deps.state, resolved.location);
5280
+ }
4899
5281
  if (action === "stop") {
4900
5282
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
4901
5283
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
@@ -4907,6 +5289,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4907
5289
  if (paramsWithResolvedCwd.dir) {
4908
5290
  try {
4909
5291
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
5292
+ const existingStatus = readStatus(location.asyncDir ?? "");
5293
+ if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5294
+ return { content: [{ type: "text", text: `Workflow ${existingStatus.runId} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5295
+ }
4910
5296
  const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
4911
5297
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
4912
5298
  } catch (error) {
@@ -4986,14 +5372,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4986
5372
  }
4987
5373
  if (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {
4988
5374
  return {
4989
- content: [{ type: "text", text: `Unknown action: ${action}. Valid: ${SUBAGENT_ACTIONS.join(", ")}` }],
4990
- isError: true,
4991
- details: { mode: "management" as const, results: [] },
4992
- };
4993
- }
4994
- if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4995
- return {
4996
- content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
5375
+ content: [{ type: "text", text: unknownSubagentActionMessage(action) }],
4997
5376
  isError: true,
4998
5377
  details: { mode: "management" as const, results: [] },
4999
5378
  };
@@ -5150,9 +5529,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5150
5529
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
5151
5530
  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.`);
5152
5531
  }
5153
- const foregroundTimeout = resolveForegroundTimeout(
5532
+ const foregroundTimeout = resolveSingleAgentLaunchTimeout(
5154
5533
  effectiveParams,
5155
- effectiveAsync ? undefined : DEFAULT_FOREGROUND_TIMEOUT_MS,
5534
+ effectiveAsync,
5156
5535
  );
5157
5536
  if (foregroundTimeout.error) return buildRequestedModeError(effectiveParams, foregroundTimeout.error);
5158
5537
  const controlConfig = resolveControlConfig(deps.config.control, effectiveParams.control);
@@ -5302,12 +5681,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5302
5681
  const foregroundDescription = effectiveParams.task?.trim()
5303
5682
  || effectiveParams.tasks?.[0]?.task?.trim()
5304
5683
  || (effectiveParams.chain ? firstRawChainTask(effectiveParams.chain)?.trim() : undefined);
5684
+ const parentWorkflowStatus = effectiveParams.workflowParentRunId
5685
+ ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
5686
+ : null;
5687
+ const workflowSteeringDir = effectiveParams.workflowParentRunId
5688
+ && requestSessionId
5689
+ && deps.state.workflowControllers?.has(effectiveParams.workflowParentRunId)
5690
+ && parentWorkflowStatus?.mode === "workflow"
5691
+ && (parentWorkflowStatus.state === "running" || parentWorkflowStatus.state === "queued")
5692
+ && parentWorkflowStatus.sessionId === requestSessionId
5693
+ ? workflowForegroundSteeringDir(DIRS.async, effectiveParams.workflowParentRunId, runId)
5694
+ : undefined;
5305
5695
  const foregroundControl: ForegroundRunControl | undefined = effectiveAsync
5306
5696
  ? undefined
5307
5697
  : compactOptional<ForegroundRunControl>({
5308
5698
  runId,
5309
5699
  sessionId: requestSessionId,
5310
5700
  mode: foregroundMode,
5701
+ ...(effectiveParams.workflowParentRunId ? { parentWorkflowRunId: effectiveParams.workflowParentRunId } : {}),
5702
+ ...(effectiveParams.workflowKey ? { workflowKey: effectiveParams.workflowKey } : {}),
5703
+ workflowSteeringDir,
5311
5704
  startedAt: Date.now(),
5312
5705
  updatedAt: Date.now(),
5313
5706
  cwd: effectiveCwd,
@@ -5413,6 +5806,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5413
5806
 
5414
5807
  let nestedForegroundStarted = false;
5415
5808
  try {
5809
+ if (workflowLaunchObserver) {
5810
+ const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
5811
+ const launch = hasSingle
5812
+ ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model) }
5813
+ : singleTask
5814
+ ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model) }
5815
+ : undefined;
5816
+ if (launch) {
5817
+ workflowLaunchObservers.delete(params);
5818
+ workflowLaunchObserver(launch);
5819
+ }
5820
+ }
5416
5821
  const asyncResult = runAsyncPath(execData, deps);
5417
5822
  if (asyncResult) return attachMission(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary));
5418
5823
  if (foregroundControl) {