@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,4 +1,4 @@
1
- import type { AsyncStatus } from "../../shared/types.ts";
1
+ import type { AsyncStatus, NestedRunSummary } from "../../shared/types.ts";
2
2
 
3
3
  export type AsyncStatusStep = NonNullable<AsyncStatus["steps"]>[number];
4
4
 
@@ -6,6 +6,7 @@ export interface ResolvedAsyncStatusChild {
6
6
  index: number;
7
7
  step: AsyncStatusStep;
8
8
  id: string;
9
+ nested?: NestedRunSummary;
9
10
  }
10
11
 
11
12
  export type AsyncStatusChildResolution =
@@ -13,18 +14,32 @@ export type AsyncStatusChildResolution =
13
14
  | { ok: false; code: "not_found" | "ambiguous"; message: string };
14
15
 
15
16
  export function asyncStatusChildIdentity(step: AsyncStatusStep, index: number): string {
16
- return step.workflowKey ?? step.runId ?? `step:${index}`;
17
+ return asyncStatusChildIdentityCandidates(step, index)[0]!;
17
18
  }
18
19
 
19
20
  export function asyncStatusChildIdentityCandidates(step: AsyncStatusStep, index: number): string[] {
20
- return [...new Set([step.workflowKey, step.runId, `step:${index}`].filter((value): value is string => typeof value === "string" && value.length > 0))];
21
+ return [...new Set([step.childId, step.workflowKey, step.runId, `step:${index}`].filter((value): value is string => typeof value === "string" && value.length > 0))];
21
22
  }
22
23
 
23
- export function resolveAsyncStatusChild(status: Pick<AsyncStatus, "runId" | "steps">, childId: string): AsyncStatusChildResolution {
24
+ export function resolveAsyncStatusChild(
25
+ status: Pick<AsyncStatus, "runId" | "steps">,
26
+ childId: string,
27
+ options: { includeNested?: boolean } = {},
28
+ ): AsyncStatusChildResolution {
24
29
  const matches: ResolvedAsyncStatusChild[] = [];
25
30
  for (const [index, step] of (status.steps ?? []).entries()) {
26
- if (!asyncStatusChildIdentityCandidates(step, index).includes(childId)) continue;
27
- matches.push({ index, step, id: asyncStatusChildIdentity(step, index) });
31
+ if (asyncStatusChildIdentityCandidates(step, index).includes(childId)) {
32
+ matches.push({ index, step, id: asyncStatusChildIdentity(step, index) });
33
+ }
34
+ if (options.includeNested) {
35
+ const findNested = (children: readonly NestedRunSummary[] | undefined): void => {
36
+ for (const nested of children ?? []) {
37
+ if (nested.id === childId) matches.push({ index, step, id: nested.id, nested });
38
+ findNested(nested.children);
39
+ }
40
+ };
41
+ findNested(step.children);
42
+ }
28
43
  }
29
44
  if (matches.length === 1) return { ok: true, child: matches[0]! };
30
45
  if (matches.length > 1) return { ok: false, code: "ambiguous", message: `Child '${childId}' is ambiguous under async run '${status.runId}'.` };
@@ -34,3 +49,14 @@ export function resolveAsyncStatusChild(status: Pick<AsyncStatus, "runId" | "ste
34
49
  export function isStoppableAsyncStatusStep(step: AsyncStatusStep): boolean {
35
50
  return step.status === "pending" || step.status === "running";
36
51
  }
52
+
53
+ export function stopStoppableAsyncStatusChildren(
54
+ status: Pick<AsyncStatus, "steps">,
55
+ stopChild: ((childId: string, message?: string) => boolean) | undefined,
56
+ message: string,
57
+ ): void {
58
+ if (!stopChild) return;
59
+ for (const [index, step] of (status.steps ?? []).entries()) {
60
+ if (isStoppableAsyncStatusStep(step)) stopChild(asyncStatusChildIdentity(step, index), message);
61
+ }
62
+ }
@@ -0,0 +1,151 @@
1
+ import * as path from "node:path";
2
+ import type { AgentConfig } from "../../agents/agents.ts";
3
+ import { resolveChildCwd } from "../../shared/utils.ts";
4
+ import type { OutputMode } from "../../shared/types.ts";
5
+ import { resolveSingleOutputPath } from "./single-output.ts";
6
+
7
+ export interface ResolvedStepBehavior {
8
+ output: string | false;
9
+ outputMode: OutputMode;
10
+ reads: string[] | false;
11
+ progress: boolean;
12
+ skills: string[] | false;
13
+ model?: string;
14
+ fast?: boolean;
15
+ }
16
+
17
+ export type OutputOverrideInput = string | boolean;
18
+
19
+ export interface StepOverrides {
20
+ output?: OutputOverrideInput;
21
+ outputMode?: OutputMode;
22
+ reads?: string[] | false;
23
+ progress?: boolean;
24
+ skills?: string[] | false;
25
+ model?: string;
26
+ fast?: boolean;
27
+ }
28
+
29
+ export interface ChildLaunchPlanInput {
30
+ agentConfig: AgentConfig;
31
+ stepOverrides: StepOverrides;
32
+ task?: string;
33
+ originalTask?: string;
34
+ runnerCwd: string;
35
+ runtimeCwd: string;
36
+ stepCwdInput?: string;
37
+ behaviorCwd?: string;
38
+ chainSkills?: string[];
39
+ outputBaseDir?: string;
40
+ parallelOutputNamespace?: { stepIndex: number; taskIndex?: number };
41
+ resolvedBehavior?: ResolvedStepBehavior;
42
+ }
43
+
44
+ export interface ChildLaunchPlan {
45
+ stepCwd: string;
46
+ instructionCwd: string;
47
+ readExistenceCwd: string;
48
+ behavior: ResolvedStepBehavior;
49
+ inheritedRelativeParallelOutput: boolean;
50
+ namespaceOutputPath: boolean;
51
+ outputPath?: string;
52
+ skillNames: string[];
53
+ }
54
+
55
+ export function normalizeOutputOverride(output: unknown): string | false | undefined {
56
+ if (output === false || output === "false") return false;
57
+ if (output === true || output === "true") return undefined;
58
+ return typeof output === "string" && output.length > 0 ? output : undefined;
59
+ }
60
+
61
+ export function resolveStepBehavior(
62
+ agentConfig: AgentConfig,
63
+ stepOverrides: StepOverrides,
64
+ chainSkills?: string[],
65
+ ): ResolvedStepBehavior {
66
+ const stepOutput = normalizeOutputOverride(stepOverrides.output);
67
+ const output = stepOutput !== undefined
68
+ ? stepOutput
69
+ : normalizeOutputOverride(agentConfig.output) ?? false;
70
+
71
+ const reads = stepOverrides.reads !== undefined
72
+ ? stepOverrides.reads
73
+ : agentConfig.defaultReads ?? false;
74
+
75
+ const progress = stepOverrides.progress !== undefined
76
+ ? stepOverrides.progress
77
+ : agentConfig.defaultProgress ?? false;
78
+
79
+ let skills: string[] | false;
80
+ if (stepOverrides.skills === false) {
81
+ skills = false;
82
+ } else if (stepOverrides.skills !== undefined) {
83
+ skills = [...stepOverrides.skills];
84
+ if (chainSkills && chainSkills.length > 0) {
85
+ skills = [...new Set([...skills, ...chainSkills])];
86
+ }
87
+ } else {
88
+ skills = agentConfig.skills ? [...agentConfig.skills] : [];
89
+ if (chainSkills && chainSkills.length > 0) {
90
+ skills = [...new Set([...skills, ...chainSkills])];
91
+ }
92
+ }
93
+
94
+ const outputMode = stepOverrides.outputMode ?? agentConfig.outputMode ?? "inline";
95
+ const model = stepOverrides.model ?? agentConfig.model;
96
+ const fast = stepOverrides.fast ?? agentConfig.fast;
97
+ return { output, outputMode, reads, progress, skills, model, fast };
98
+ }
99
+
100
+ export function resolveTaskTextForFileUpdatePolicy(task: string | undefined, originalTask?: string): string | undefined {
101
+ if (!task) return originalTask;
102
+ return originalTask ? task.replaceAll("{task}", originalTask) : task;
103
+ }
104
+
105
+ export function taskDisallowsFileUpdates(task: string | undefined): boolean {
106
+ if (!task) return false;
107
+ return /\breview[- ]only\b/i.test(task)
108
+ || /\bread[- ]only\s+(?:review|audit|inspection|pass)\b/i.test(task)
109
+ || /\b(?:no|without)\s+(?:file\s+)?edits?\b/i.test(task)
110
+ || /\b(?:do not|don't|must not)\s+(?:edit|modify|write|touch)\b/i.test(task)
111
+ || /\bleave\s+files?\s+unchanged\b/i.test(task);
112
+ }
113
+
114
+ export function suppressProgressForReadOnlyTask(behavior: ResolvedStepBehavior, task: string | undefined, originalTask?: string): ResolvedStepBehavior {
115
+ const policyTask = resolveTaskTextForFileUpdatePolicy(task, originalTask);
116
+ return behavior.progress && taskDisallowsFileUpdates(policyTask) ? { ...behavior, progress: false } : behavior;
117
+ }
118
+
119
+ export function planChildLaunch(input: ChildLaunchPlanInput): ChildLaunchPlan {
120
+ const stepCwd = resolveChildCwd(input.runnerCwd, input.stepCwdInput);
121
+ const instructionCwd = input.behaviorCwd ?? stepCwd;
122
+ const readExistenceCwd = input.behaviorCwd ? stepCwd : instructionCwd;
123
+ let behavior = suppressProgressForReadOnlyTask(
124
+ input.resolvedBehavior ?? resolveStepBehavior(input.agentConfig, input.stepOverrides, input.chainSkills),
125
+ input.task,
126
+ input.originalTask,
127
+ );
128
+
129
+ const inheritedRelativeParallelOutput = Boolean(
130
+ input.parallelOutputNamespace
131
+ && input.stepOverrides.output === undefined
132
+ && typeof behavior.output === "string"
133
+ && !path.isAbsolute(behavior.output),
134
+ );
135
+ if (inheritedRelativeParallelOutput && input.parallelOutputNamespace?.taskIndex !== undefined) {
136
+ behavior = {
137
+ ...behavior,
138
+ output: path.join(
139
+ `parallel-${input.parallelOutputNamespace.stepIndex}`,
140
+ `${input.parallelOutputNamespace.taskIndex}-${input.agentConfig.name}`,
141
+ behavior.output as string,
142
+ ),
143
+ };
144
+ }
145
+
146
+ const namespaceOutputPath = inheritedRelativeParallelOutput && input.parallelOutputNamespace?.taskIndex === undefined;
147
+ const skillNames = behavior.skills === false ? [] : behavior.skills;
148
+ const outputPath = resolveSingleOutputPath(behavior.output, input.runtimeCwd, instructionCwd, input.outputBaseDir);
149
+
150
+ return { stepCwd, instructionCwd, readExistenceCwd, behavior, inheritedRelativeParallelOutput, namespaceOutputPath, outputPath, skillNames };
151
+ }
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Builds the in-process launch for one child: the tool plan, the typed child
3
+ * runtime config the hooks read, and the session launch input. Foreground
4
+ * children are built in the parent process; background children are built in
5
+ * the detached runner from the step it received in its config.
6
+ */
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ import type { ChildWatchdogConfig, ChildWatchdogStatusEvent } from "../../watchdog/child-status.ts";
11
+ import type { ThinkingLevel } from "../../shared/model-info.ts";
12
+ import { intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
13
+ import {
14
+ TEMP_ROOT_DIR,
15
+ resolveChildDepth,
16
+ type LaunchResolvedChildExtensionsV1,
17
+ type ResolvedToolBudget,
18
+ type RunFanoutBudgetDescriptor,
19
+ } from "../../shared/types.ts";
20
+ import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
21
+ import type { NestedPathEntry } from "./nested-path.ts";
22
+ import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
23
+ import type { PermissionRules } from "./permissions.ts";
24
+ import type { StructuredOutputRuntime } from "./structured-output.ts";
25
+ import type { ChildToolDiagnostic } from "./tool-availability.ts";
26
+ import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
27
+ import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
28
+ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
29
+ import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
30
+ import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
31
+ import {
32
+ isSubagentRuntimeExtensionPath,
33
+ projectLaunchResolvedChildExtensions,
34
+ resolvePiLaunchToolPlan,
35
+ supervisorChannelDir,
36
+ type PiLaunchToolPlan,
37
+ } from "./child-tool-plan.ts";
38
+ import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
39
+ import { createChildHooks } from "./child-hooks.ts";
40
+ import type { ChildSessionLaunch, ChildSessionStorage } from "./child-session.ts";
41
+
42
+ /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
43
+ export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
44
+
45
+ const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
46
+ const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
47
+ // Marks an in-process child so child extensions never mutate the host process
48
+ // state (for example a profile-failure exit code) that a separate child process
49
+ // would legitimately own.
50
+ const IN_PROCESS_CHILD_ENV = "PI_SUBAGENT_SANDBOX_IN_PROCESS_CHILD";
51
+
52
+ function hasTrustedProfileProjectCwd(input: Pick<BuildInProcessChildLaunchInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
53
+ if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
54
+ return path.resolve(input.cwd) === path.resolve(input.trustedProjectCwd);
55
+ }
56
+
57
+ /**
58
+ * The parts of the launching executor's own child runtime that a child it
59
+ * launches inherits. Serialized into the background runner config; the
60
+ * foreground path passes the executor's full `ChildRuntimeConfig`.
61
+ */
62
+ export type InheritedChildRuntime = Pick<ChildRuntimeConfig, "depth" | "maxDepth" | "nestedRoute" | "nestedParent" | "capabilityCeiling" | "thinkingCeiling" | "runFanoutBudget">;
63
+
64
+ export function inheritedChildRuntime(config: ChildRuntimeConfig | undefined): InheritedChildRuntime | undefined {
65
+ if (!config) return undefined;
66
+ return {
67
+ depth: config.depth,
68
+ ...(config.maxDepth !== undefined ? { maxDepth: config.maxDepth } : {}),
69
+ ...(config.nestedRoute ? { nestedRoute: config.nestedRoute } : {}),
70
+ ...(config.nestedParent ? { nestedParent: config.nestedParent } : {}),
71
+ ...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),
72
+ ...(config.thinkingCeiling ? { thinkingCeiling: config.thinkingCeiling } : {}),
73
+ ...(config.runFanoutBudget ? { runFanoutBudget: config.runFanoutBudget } : {}),
74
+ };
75
+ }
76
+
77
+ export interface BuildInProcessChildLaunchInput {
78
+ parentSessionId?: string;
79
+ forkCacheKey?: string;
80
+ sessionEnabled: boolean;
81
+ sessionDir?: string;
82
+ sessionFile?: string;
83
+ /** Model reference with the thinking suffix already applied. */
84
+ model?: string;
85
+ systemPromptMode?: "append" | "replace";
86
+ inheritProjectContext: boolean;
87
+ inheritGlobalContext: boolean;
88
+ inheritSkills: boolean;
89
+ requireReadTool?: boolean;
90
+ tools?: string[];
91
+ excludeTools?: string[];
92
+ extensions?: string[];
93
+ subagentOnlyExtensions?: string[];
94
+ systemPrompt?: string | null;
95
+ mcpDirectTools?: string[];
96
+ extensionBindings?: ExtensionBindings;
97
+ cwd: string;
98
+ intercomSessionName?: string;
99
+ sessionName?: string;
100
+ orchestratorIntercomTarget?: string;
101
+ runId?: string;
102
+ childAgentName: string;
103
+ childIndex: number;
104
+ nestedRoute?: { rootRunId: string; eventSink: string; controlInbox: string; capabilityToken: string };
105
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
106
+ structuredOutput?: StructuredOutputRuntime;
107
+ fast?: boolean;
108
+ modelCandidates?: readonly string[];
109
+ toolBudget?: ResolvedToolBudget;
110
+ permissionRules?: PermissionRules;
111
+ permissionAuditPath?: string;
112
+ childWatchdog?: ChildWatchdogConfig;
113
+ watchdogStatus?: (event: ChildWatchdogStatusEvent) => void;
114
+ waitToolEnabled?: boolean;
115
+ waitToolDefaultTimeoutMs?: number;
116
+ allowNestedSubagents?: boolean;
117
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
118
+ thinkingCeiling?: ThinkingLevel;
119
+ maxSubagentDepth?: number;
120
+ runtimeSnapshotHost?: McpRuntimeSnapshotHost;
121
+ /** A validated global pi-sandbox profile selected by the agent definition. */
122
+ sandbox?: string;
123
+ /** Parent-authoritative trust state for profile-aware project config merging. */
124
+ projectTrusted?: boolean;
125
+ /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
126
+ trustedProjectCwd?: string;
127
+ /** The launching executor's own child runtime when it is itself an in-process child. */
128
+ inherited?: InheritedChildRuntime;
129
+ /**
130
+ * Which process hosts the session. The parent never loads ambient extensions
131
+ * or writes child environment values (it shares its process with the parent
132
+ * session); the runner loads ambient extensions when the tool plan allows
133
+ * them and exposes the child environment external extensions read.
134
+ */
135
+ host: "parent" | "runner";
136
+ }
137
+
138
+ export interface InProcessChildCapture {
139
+ structuredOutput(): { called: boolean; value?: unknown; acceptanceReport?: unknown; acceptanceReportProvided: boolean };
140
+ toolDiagnostic(): ChildToolDiagnostic | undefined;
141
+ runtimeAcknowledgedExtensions(): RuntimeAcknowledgedChildExtensionsV1 | undefined;
142
+ }
143
+
144
+ export interface InProcessChildLaunch {
145
+ toolPlan: PiLaunchToolPlan;
146
+ config: ChildRuntimeConfig;
147
+ session: Omit<ChildSessionLaunch, "onExtensionError">;
148
+ capture: InProcessChildCapture;
149
+ launchResolvedExtensions: LaunchResolvedChildExtensionsV1;
150
+ warnings: string[];
151
+ capabilityAudit?: SubagentCapabilityAudit;
152
+ /** Path a blocked child extension writes its startup failure to; see
153
+ * `readSandboxStartupDiagnostic`. Present only for sandbox-profile children. */
154
+ sandboxDiagnosticsPath?: string;
155
+ }
156
+
157
+ /** Escape XML-significant characters in a string for safe attribute interpolation. */
158
+ function escapeXmlAttr(value: string): string {
159
+ return value
160
+ .replace(/&/g, "&amp;")
161
+ .replace(/"/g, "&quot;")
162
+ .replace(/</g, "&lt;")
163
+ .replace(/>/g, "&gt;");
164
+ }
165
+
166
+ function inheritedCapabilityCeiling(inherited: InheritedChildRuntime | undefined): ResolvedSubagentCapabilityCeiling | undefined {
167
+ return inherited?.capabilityCeiling;
168
+ }
169
+
170
+ /** Environment values external child extensions read; only the runner applies them. */
171
+ function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan, sandboxEnv?: Record<string, string | undefined>): Record<string, string | undefined> {
172
+ const env: Record<string, string | undefined> = {};
173
+ env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
174
+ if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
175
+ else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
176
+ env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
177
+ } else env[MCP_DIRECT_TOOLS_ENV] = "__none__";
178
+ return sandboxEnv ? { ...env, ...sandboxEnv } : env;
179
+ }
180
+
181
+ function childStorage(input: BuildInProcessChildLaunchInput): ChildSessionStorage {
182
+ if (input.sessionFile) {
183
+ fs.mkdirSync(path.dirname(input.sessionFile), { recursive: true });
184
+ return { kind: "file", sessionFile: input.sessionFile };
185
+ }
186
+ if (!input.sessionEnabled) return { kind: "memory" };
187
+ if (input.sessionDir) {
188
+ fs.mkdirSync(input.sessionDir, { recursive: true });
189
+ return { kind: "dir", sessionDir: input.sessionDir };
190
+ }
191
+ return { kind: "default" };
192
+ }
193
+
194
+ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput): InProcessChildLaunch {
195
+ const toolPlan = resolvePiLaunchToolPlan({
196
+ tools: input.tools,
197
+ excludeTools: input.excludeTools,
198
+ allowNestedSubagents: input.allowNestedSubagents,
199
+ extensions: input.extensions,
200
+ subagentOnlyExtensions: input.subagentOnlyExtensions,
201
+ mcpDirectTools: input.mcpDirectTools,
202
+ cwd: input.cwd,
203
+ requireReadTool: input.requireReadTool,
204
+ structuredOutput: Boolean(input.structuredOutput),
205
+ fast: input.fast,
206
+ model: input.model,
207
+ modelCandidates: input.modelCandidates,
208
+ capabilityCeiling: input.capabilityCeiling,
209
+ inheritedCapabilityCeiling: inheritedCapabilityCeiling(input.inherited),
210
+ agentName: input.childAgentName,
211
+ permissionRules: input.permissionRules,
212
+ runtimeSnapshotHost: input.runtimeSnapshotHost,
213
+ sandbox: input.sandbox,
214
+ });
215
+
216
+ // A selected profile is validated by resolvePiLaunchToolPlan; the child
217
+ // receives only the profile identity, trust snapshot, and startup ack
218
+ // channel through its environment. Transient keys are restored after the
219
+ // session is created so the host process never keeps them.
220
+ const sandboxAckPath = toolPlan.sandboxExtension && input.sandbox !== undefined
221
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-acks", `${randomUUID()}.json`)
222
+ : undefined;
223
+ const sandboxDiagnosticsPath = sandboxAckPath
224
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-diagnostics", `${randomUUID()}.json`)
225
+ : undefined;
226
+ const sandboxEnv: Record<string, string | undefined> | undefined = sandboxAckPath
227
+ ? {
228
+ [SUBAGENT_SANDBOX_PROFILE_ENV]: input.sandbox,
229
+ [SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: hasTrustedProfileProjectCwd(input) ? "1" : "0",
230
+ [SANDBOX_STARTUP_ACK_PATH_ENV]: sandboxAckPath,
231
+ [SANDBOX_STARTUP_ACK_TOKEN_ENV]: randomUUID(),
232
+ [SANDBOX_DIAGNOSTICS_PATH_ENV]: sandboxDiagnosticsPath,
233
+ ...(input.host === "parent" ? { [IN_PROCESS_CHILD_ENV]: "1" } : {}),
234
+ }
235
+ : undefined;
236
+ if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
237
+
238
+ const inherited = input.inherited;
239
+ const fanout = toolPlan.fanoutAuthorized;
240
+ const inheritedRoute = inherited?.nestedRoute;
241
+ const parentRunId = input.runId ?? inherited?.nestedParent?.parentRunId ?? "";
242
+ const parentChildIndex = input.childIndex;
243
+ const parentDepth = inheritedRoute && inherited?.nestedParent ? inherited.nestedParent.depth + 1 : 1;
244
+ const parentPath: NestedPathEntry[] = [
245
+ ...(inherited?.nestedParent?.path ?? []),
246
+ ...(parentRunId ? [{ runId: parentRunId, stepIndex: parentChildIndex, agent: input.childAgentName }] : []),
247
+ ];
248
+ const nestedRoute = fanout ? (input.nestedRoute ?? inheritedRoute) : undefined;
249
+ const childDepth = resolveChildDepth(input.maxSubagentDepth, inherited);
250
+ const permissions = input.permissionRules && Object.keys(input.permissionRules).length > 0
251
+ ? { rules: input.permissionRules, ...(input.permissionAuditPath ? { auditPath: input.permissionAuditPath } : {}) }
252
+ : undefined;
253
+ let supervisorDir: string | undefined;
254
+ if (input.orchestratorIntercomTarget && input.parentSessionId && input.runId) {
255
+ supervisorDir = supervisorChannelDir(input.runId, input.childAgentName, input.childIndex);
256
+ fs.mkdirSync(path.join(supervisorDir, "requests"), { recursive: true });
257
+ fs.mkdirSync(path.join(supervisorDir, "replies"), { recursive: true });
258
+ }
259
+ const thinkingCeiling = intersectThinkingCeilings(input.thinkingCeiling, inherited?.thinkingCeiling);
260
+
261
+ let structuredValue: unknown;
262
+ let structuredAcceptanceReport: unknown;
263
+ let structuredCalled = false;
264
+ let structuredAcceptanceProvided = false;
265
+ let toolDiagnostic: ChildToolDiagnostic | undefined;
266
+ let acknowledgedIds: string[] | undefined;
267
+
268
+ const config: ChildRuntimeConfig = {
269
+ ...(input.runId ? { runId: input.runId } : {}),
270
+ agent: input.childAgentName,
271
+ childIndex: input.childIndex,
272
+ fanoutChild: fanout,
273
+ ...(input.sessionName?.trim() ? { sessionName: input.sessionName.trim() } : {}),
274
+ ...(input.intercomSessionName ? { intercomSessionName: input.intercomSessionName } : {}),
275
+ ...(input.orchestratorIntercomTarget ? { orchestratorTarget: input.orchestratorIntercomTarget } : {}),
276
+ ...(input.parentSessionId ? { orchestratorSessionId: input.parentSessionId, parentSessionId: input.parentSessionId } : {}),
277
+ ...(supervisorDir ? { supervisorChannelDir: supervisorDir } : {}),
278
+ ...(nestedRoute ? { nestedRoute } : {}),
279
+ ...(fanout && parentRunId ? { nestedParent: { parentRunId, parentChildIndex, depth: parentDepth, path: parentPath } } : {}),
280
+ ...(fanout && (input.runFanoutBudget ?? inherited?.runFanoutBudget) ? { runFanoutBudget: input.runFanoutBudget ?? inherited?.runFanoutBudget } : {}),
281
+ depth: childDepth.depth,
282
+ maxDepth: childDepth.maxDepth,
283
+ ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
284
+ ...(thinkingCeiling ? { thinkingCeiling } : {}),
285
+ inheritProjectContext: input.inheritProjectContext,
286
+ inheritGlobalContext: input.inheritGlobalContext,
287
+ inheritSkills: input.inheritSkills,
288
+ ...(input.forkCacheKey?.trim() ? { forkCacheKey: input.forkCacheKey.trim() } : {}),
289
+ ...(permissions ? { permissions } : {}),
290
+ ...(input.toolBudget ? { toolBudget: input.toolBudget } : {}),
291
+ ...(input.childWatchdog ? { childWatchdog: input.childWatchdog } : {}),
292
+ ...(input.watchdogStatus ? { watchdogStatus: input.watchdogStatus } : {}),
293
+ waitTool: {
294
+ enabled: input.waitToolEnabled ?? true,
295
+ ...(input.waitToolDefaultTimeoutMs !== undefined ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}),
296
+ },
297
+ ...(input.structuredOutput
298
+ ? {
299
+ structuredOutput: {
300
+ schema: input.structuredOutput.schema,
301
+ ...(input.structuredOutput.acceptanceReportPath
302
+ ? { acceptanceReport: input.structuredOutput.acceptanceReportRequired ? "required" as const : "optional" as const }
303
+ : {}),
304
+ capture: (value: unknown, acceptanceReport: unknown) => {
305
+ structuredCalled = true;
306
+ structuredValue = value;
307
+ structuredAcceptanceProvided = acceptanceReport !== undefined;
308
+ structuredAcceptanceReport = acceptanceReport;
309
+ },
310
+ },
311
+ }
312
+ : {}),
313
+ ...(toolPlan.requiredChildTools.length > 0 ? { requiredTools: toolPlan.requiredChildTools } : {}),
314
+ ...(toolPlan.effectiveMcpTools.length > 0 ? { mcpDirectTools: toolPlan.effectiveMcpTools } : {}),
315
+ toolDiagnostic: (diagnostic) => { toolDiagnostic = diagnostic; },
316
+ runtimeAcknowledgements: (ids) => { acknowledgedIds = ids; },
317
+ fast: input.fast === true,
318
+ };
319
+
320
+ const extensionPaths = toolPlan.extensionArgs.filter((extensionPath) => !isSubagentRuntimeExtensionPath(extensionPath));
321
+ const ambientExtensions = input.host === "runner" && !toolPlan.disableAmbientExtensions;
322
+ const launchResolvedExtensions = projectLaunchResolvedChildExtensions({
323
+ runtimeExtensions: toolPlan.runtimeExtensions,
324
+ configuredExtensions: toolPlan.configuredExtensions,
325
+ extensionArgs: toolPlan.extensionArgs,
326
+ disableAmbientExtensions: !ambientExtensions,
327
+ });
328
+ const taggedPrompt = input.systemPrompt !== undefined && input.systemPrompt !== null
329
+ ? `<active_agent name="${escapeXmlAttr(input.childAgentName)}"/>\n\n${input.systemPrompt}`
330
+ : undefined;
331
+ const session: Omit<ChildSessionLaunch, "onExtensionError"> = {
332
+ cwd: input.cwd,
333
+ storage: childStorage(input),
334
+ ...(input.model ? { model: input.model } : {}),
335
+ ...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
336
+ ...(!toolPlan.explicitToolAllowlist && toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
337
+ extensionPaths,
338
+ ambientExtensions,
339
+ hooks: createChildHooks(config),
340
+ ...(input.host === "runner" || sandboxEnv ? { processEnv: childProcessEnv(input, toolPlan, sandboxEnv) } : {}),
341
+ ...(sandboxEnv ? { transientProcessEnv: Object.keys(sandboxEnv) } : {}),
342
+ runtime: config,
343
+ noSkills: !input.inheritSkills,
344
+ noContextFiles: !input.inheritProjectContext,
345
+ ...(taggedPrompt !== undefined
346
+ ? input.systemPromptMode === "replace" ? { systemPrompt: taggedPrompt } : { appendSystemPrompt: taggedPrompt }
347
+ : {}),
348
+ };
349
+
350
+ return {
351
+ toolPlan,
352
+ config,
353
+ session,
354
+ capture: {
355
+ structuredOutput: () => ({ called: structuredCalled, value: structuredValue, acceptanceReport: structuredAcceptanceReport, acceptanceReportProvided: structuredAcceptanceProvided }),
356
+ toolDiagnostic: () => toolDiagnostic,
357
+ runtimeAcknowledgedExtensions: () => (acknowledgedIds ? projectRuntimeAcknowledgedExtensions(acknowledgedIds) : undefined),
358
+ },
359
+ launchResolvedExtensions,
360
+ warnings: toolPlan.warnings,
361
+ ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
362
+ ...(sandboxDiagnosticsPath ? { sandboxDiagnosticsPath } : {}),
363
+ };
364
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Child lifecycle projection: when the observed child session events mean
3
+ * the run is settling and the observer may start (or must cancel) its final
4
+ * drain window.
5
+ */
6
+ export type ChildLifecycleAction = "start-drain" | "cancel-drain" | "none";
7
+
8
+ export interface ChildLifecycleState {
9
+ compactionRetryActive: boolean;
10
+ }
11
+
12
+ export function projectChildLifecycle(event: { type?: string; willRetry?: unknown }, terminalAssistantStop = false, state?: ChildLifecycleState): ChildLifecycleAction {
13
+ if (event.type === "compaction_end") {
14
+ if (state) state.compactionRetryActive = event.willRetry === true;
15
+ return event.willRetry === true ? "cancel-drain" : "none";
16
+ }
17
+ if (event.type === "agent_start" || event.type === "auto_retry_start") {
18
+ if (state) state.compactionRetryActive = false;
19
+ }
20
+ if (event.type === "agent_end" && event.willRetry === true) return "cancel-drain";
21
+ if (event.type === "agent_end" && state) state.compactionRetryActive = false;
22
+ if (event.type === "agent_settled") return state?.compactionRetryActive ? "none" : "start-drain";
23
+ if (terminalAssistantStop) return "start-drain";
24
+ return "none";
25
+ }