@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,52 @@
1
+ import * as path from "node:path";
2
+
3
+ const MAX_NESTED_ID_LENGTH = 128;
4
+ export const MAX_NESTED_PATH_ENTRIES = 4;
5
+
6
+ export type NestedPathEntry = { runId: string; stepIndex?: number; agent?: string };
7
+
8
+ export function isSafeNestedPathId(value: unknown): value is string {
9
+ return typeof value === "string"
10
+ && value.length > 0
11
+ && value.length <= MAX_NESTED_ID_LENGTH
12
+ && !path.isAbsolute(value)
13
+ && !value.includes("/")
14
+ && !value.includes("\\")
15
+ && !value.includes("..");
16
+ }
17
+
18
+ function finiteNumber(value: unknown): number | undefined {
19
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
20
+ }
21
+
22
+ function nonEmptyString(value: unknown, max: number): string | undefined {
23
+ return typeof value === "string" && value.length > 0 ? value.slice(0, max) : undefined;
24
+ }
25
+
26
+ export function sanitizeNestedPath(value: unknown): NestedPathEntry[] {
27
+ if (!Array.isArray(value)) return [];
28
+ return value.map((part) => {
29
+ if (!part || typeof part !== "object") return undefined;
30
+ const record = part as Record<string, unknown>;
31
+ if (!isSafeNestedPathId(record.runId)) return undefined;
32
+ return {
33
+ runId: record.runId,
34
+ ...(finiteNumber(record.stepIndex) !== undefined ? { stepIndex: finiteNumber(record.stepIndex) } : {}),
35
+ ...(nonEmptyString(record.agent, 128) ? { agent: nonEmptyString(record.agent, 128) } : {}),
36
+ };
37
+ }).filter((part): part is NestedPathEntry => Boolean(part)).slice(0, MAX_NESTED_PATH_ENTRIES);
38
+ }
39
+
40
+ export function parseNestedPathEnv(value: string | undefined): NestedPathEntry[] {
41
+ if (!value) return [];
42
+ try {
43
+ return sanitizeNestedPath(JSON.parse(value) as unknown);
44
+ } catch {
45
+ return [];
46
+ }
47
+ }
48
+
49
+ export function encodeNestedPathEnv(value: NestedPathEntry[]): string {
50
+ const sanitized = sanitizeNestedPath(value);
51
+ return sanitized.length ? JSON.stringify(sanitized) : "";
52
+ }
@@ -0,0 +1,123 @@
1
+ import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
2
+ import { formatActivityLabel } from "../../shared/status-format.ts";
3
+ import type { ActivityState, NestedRunSummary, NestedStepSummary } from "../../shared/types.ts";
4
+
5
+ export interface NestedRunCounts {
6
+ total: number;
7
+ running: number;
8
+ paused: number;
9
+ complete: number;
10
+ failed: number;
11
+ rejected: number;
12
+ stopped: number;
13
+ queued: number;
14
+ }
15
+
16
+ export function countNestedRuns(children: NestedRunSummary[] | undefined): NestedRunCounts {
17
+ const counts: NestedRunCounts = { total: 0, running: 0, paused: 0, complete: 0, failed: 0, rejected: 0, stopped: 0, queued: 0 };
18
+ for (const child of children ?? []) {
19
+ counts.total++;
20
+ counts[child.state]++;
21
+ const nested = countNestedRuns([...(child.children ?? []), ...(child.steps?.flatMap((step) => step.children ?? []) ?? [])]);
22
+ counts.total += nested.total;
23
+ counts.running += nested.running;
24
+ counts.paused += nested.paused;
25
+ counts.complete += nested.complete;
26
+ counts.failed += nested.failed;
27
+ counts.rejected += nested.rejected;
28
+ counts.stopped += nested.stopped;
29
+ counts.queued += nested.queued;
30
+ }
31
+ return counts;
32
+ }
33
+
34
+ export function formatNestedAggregate(children: NestedRunSummary[] | undefined): string | undefined {
35
+ const counts = countNestedRuns(children);
36
+ if (counts.total === 0) return undefined;
37
+ const parts = [
38
+ counts.running > 0 ? `${counts.running} running` : "",
39
+ counts.paused > 0 ? `${counts.paused} paused` : "",
40
+ counts.failed > 0 ? `${counts.failed} failed` : "",
41
+ counts.rejected > 0 ? `${counts.rejected} rejected` : "",
42
+ counts.stopped > 0 ? `${counts.stopped} stopped` : "",
43
+ counts.complete > 0 ? `${counts.complete} complete` : "",
44
+ counts.queued > 0 ? `${counts.queued} queued` : "",
45
+ ].filter(Boolean);
46
+ return `+${counts.total} nested run${counts.total === 1 ? "" : "s"}${parts.length ? ` (${parts.join(", ")})` : ""}`;
47
+ }
48
+
49
+ function nestedRunLabel(run: NestedRunSummary): string {
50
+ if (run.agent) return run.agent;
51
+ if (run.agents?.length) return run.agents.length === 1 ? run.agents[0]! : `${run.agents.slice(0, 2).join(", ")}${run.agents.length > 2 ? ` +${run.agents.length - 2}` : ""}`;
52
+ return run.id;
53
+ }
54
+
55
+ function formatNestedActivity(input: {
56
+ activityState?: ActivityState;
57
+ lastActivityAt?: number;
58
+ currentTool?: string;
59
+ currentToolStartedAt?: number;
60
+ currentPath?: string;
61
+ turnCount?: number;
62
+ toolCount?: number;
63
+ totalTokens?: NestedRunSummary["totalTokens"];
64
+ }): string | undefined {
65
+ const facts: string[] = [];
66
+ if (input.currentTool && input.currentToolStartedAt !== undefined) facts.push(`tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`);
67
+ else if (input.currentTool) facts.push(`tool ${input.currentTool}`);
68
+ if (input.currentPath) facts.push(shortenPath(input.currentPath));
69
+ if (input.turnCount !== undefined) facts.push(`${input.turnCount} turns`);
70
+ if (input.toolCount !== undefined) facts.push(`${input.toolCount} tools`);
71
+ if (input.totalTokens) facts.push(`${formatTokens(input.totalTokens.total)} tok`);
72
+ const activity = formatActivityLabel(input.lastActivityAt, input.activityState as ActivityState | undefined);
73
+ return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : undefined;
74
+ }
75
+
76
+ function formatNestedRunLines(children: NestedRunSummary[] | undefined, options: { indent: string; maxDepth: number; maxLines: number; commandHints?: boolean }): string[] {
77
+ const lines: string[] = [];
78
+ const append = (items: NestedRunSummary[] | undefined, depth: number, indent: string): void => {
79
+ if (!items?.length || lines.length >= options.maxLines) return;
80
+ if (depth > options.maxDepth) {
81
+ const aggregate = formatNestedAggregate(items);
82
+ if (aggregate && lines.length < options.maxLines) lines.push(`${indent}↳ ${aggregate}`);
83
+ return;
84
+ }
85
+ for (let index = 0; index < items.length; index++) {
86
+ const child = items[index]!;
87
+ if (lines.length >= options.maxLines) {
88
+ const aggregate = formatNestedAggregate(items.slice(index));
89
+ if (aggregate) lines[lines.length - 1] = `${indent}↳ ${aggregate}`;
90
+ return;
91
+ }
92
+ const activity = child.state === "running" ? formatNestedActivity(child) : undefined;
93
+ const error = child.error ? ` | error: ${child.error}` : "";
94
+ const modelThinking = formatModelThinking(child.model, child.thinking);
95
+ lines.push(`${indent}↳ ${nestedRunLabel(child)} [${child.id}] ${child.state}${modelThinking ? ` | ${modelThinking}` : ""}${activity ? ` | ${activity}` : ""}${error}`);
96
+ if (options.commandHints && lines.length < options.maxLines) lines.push(`${indent} Status: subagent({ action: "status", id: "${child.id}" })`);
97
+ if (depth === options.maxDepth) {
98
+ const aggregate = formatNestedAggregate([...(child.steps?.flatMap((step) => step.children ?? []) ?? []), ...(child.children ?? [])]);
99
+ if (aggregate && lines.length < options.maxLines) lines.push(`${indent} ↳ ${aggregate}`);
100
+ continue;
101
+ }
102
+ for (const [stepIndex, step] of (child.steps ?? []).entries()) {
103
+ if (lines.length >= options.maxLines) return;
104
+ const stepActivity = step.status === "running" ? formatNestedActivity(step) : undefined;
105
+ const stepModelThinking = formatModelThinking(step.model, step.thinking);
106
+ lines.push(`${indent} ${stepIndex + 1}. ${step.agent} ${step.status}${stepModelThinking ? ` | ${stepModelThinking}` : ""}${stepActivity ? ` | ${stepActivity}` : ""}${step.error ? ` | error: ${step.error}` : ""}`);
107
+ append(step.children, depth + 1, `${indent} `);
108
+ }
109
+ append(child.children, depth + 1, `${indent} `);
110
+ }
111
+ };
112
+ append(children, 0, options.indent);
113
+ return lines;
114
+ }
115
+
116
+ export function formatNestedRunStatusLines(children: NestedRunSummary[] | undefined, options: { indent?: string; maxDepth?: number; maxLines?: number; commandHints?: boolean } = {}): string[] {
117
+ return formatNestedRunLines(children, {
118
+ indent: options.indent ?? " ",
119
+ maxDepth: options.maxDepth ?? 2,
120
+ maxLines: options.maxLines ?? 40,
121
+ commandHints: options.commandHints ?? false,
122
+ });
123
+ }
@@ -0,0 +1,238 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
4
+ import type {
5
+ ParallelHandoffGroup,
6
+ ParallelHandoffManifest,
7
+ ParallelHandoffReference,
8
+ SubagentResultStatus,
9
+ } from "../../shared/types.ts";
10
+ import type {
11
+ WorktreeCleanupReport,
12
+ WorktreeDiff,
13
+ WorktreeSetup,
14
+ WorktreeCleanupIntent,
15
+ } from "./worktree.ts";
16
+ import { cleanupWorktrees } from "./worktree.ts";
17
+
18
+ export interface ParallelHandoffResult {
19
+ agent: string;
20
+ status: SubagentResultStatus;
21
+ summary: string;
22
+ outputPath?: string;
23
+ structuredOutput?: unknown;
24
+ structuredOutputPath?: string;
25
+ sessionPath?: string;
26
+ }
27
+
28
+ function readManifest(manifestPath: string): ParallelHandoffManifest | undefined {
29
+ if (!fs.existsSync(manifestPath)) return undefined;
30
+ const parsed = JSON.parse(fs.readFileSync(manifestPath, "utf-8")) as ParallelHandoffManifest;
31
+ if (parsed.version !== 1 || !Array.isArray(parsed.groups)) {
32
+ throw new Error(`Invalid parallel handoff manifest: ${manifestPath}`);
33
+ }
34
+ return parsed;
35
+ }
36
+
37
+ function referenceFor(manifestPath: string, manifest: ParallelHandoffManifest): ParallelHandoffReference {
38
+ const children = manifest.groups.flatMap((group) => group.children);
39
+ return {
40
+ version: 1,
41
+ path: manifestPath,
42
+ groupCount: manifest.groups.length,
43
+ childCount: children.length,
44
+ changedPatches: children.filter((child) => child.patch.changed).length,
45
+ cleanupState: manifest.groups.every((group) => group.cleanup.state === "complete") ? "complete" : "partial",
46
+ };
47
+ }
48
+
49
+ function safeHandoffAgentName(agent: string): string {
50
+ return agent.replace(/[^\w.-]/g, "_");
51
+ }
52
+
53
+ function missingDiff(input: { manifestPath: string; stepIndex: number; taskIndex: number; agent: string; branch?: string }): WorktreeDiff {
54
+ const patchPath = path.join(path.dirname(input.manifestPath), `missing-diff-step-${input.stepIndex}-task-${input.taskIndex}-${safeHandoffAgentName(input.agent)}.patch`);
55
+ try {
56
+ fs.mkdirSync(path.dirname(patchPath), { recursive: true });
57
+ fs.writeFileSync(patchPath, "", "utf-8");
58
+ } catch {
59
+ // Handoff records the artifact failure below; patch creation remains best-effort.
60
+ }
61
+ return {
62
+ index: input.taskIndex,
63
+ agent: input.agent,
64
+ branch: input.branch ?? "",
65
+ diffStat: "",
66
+ filesChanged: 0,
67
+ insertions: 0,
68
+ deletions: 0,
69
+ patchPath,
70
+ error: "diff artifact unavailable; no patch was captured",
71
+ };
72
+ }
73
+
74
+ export function writeParallelHandoffGroup(input: {
75
+ manifestPath: string;
76
+ runId: string;
77
+ mode: "parallel" | "chain";
78
+ source: "foreground" | "async";
79
+ cwd: string;
80
+ stepIndex: number;
81
+ flatStartIndex: number;
82
+ setup: WorktreeSetup;
83
+ diffs: WorktreeDiff[];
84
+ cleanup?: WorktreeCleanupReport;
85
+ results: ParallelHandoffResult[];
86
+ now?: number;
87
+ }): ParallelHandoffReference {
88
+ const now = input.now ?? Date.now();
89
+ const existing = readManifest(input.manifestPath);
90
+ if (existing && (existing.runId !== input.runId || existing.mode !== input.mode || existing.source !== input.source)) {
91
+ throw new Error(`Parallel handoff manifest belongs to a different run: ${input.manifestPath}`);
92
+ }
93
+ const group: ParallelHandoffGroup = {
94
+ stepIndex: input.stepIndex,
95
+ baseCommit: input.setup.baseCommit,
96
+ repoRoot: input.setup.cwd,
97
+ children: input.results.map((result, taskIndex) => {
98
+ const diff = input.diffs[taskIndex] ?? missingDiff({
99
+ manifestPath: input.manifestPath,
100
+ stepIndex: input.stepIndex,
101
+ taskIndex,
102
+ agent: result.agent,
103
+ branch: input.setup.worktrees[taskIndex]?.branch,
104
+ });
105
+ return {
106
+ index: input.flatStartIndex + taskIndex,
107
+ taskIndex,
108
+ agent: result.agent,
109
+ status: result.status,
110
+ summary: result.summary,
111
+ ...(result.outputPath ? { outputPath: result.outputPath } : {}),
112
+ ...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),
113
+ ...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),
114
+ ...(result.sessionPath ? { sessionPath: result.sessionPath } : {}),
115
+ patch: {
116
+ path: diff.patchPath,
117
+ branch: diff.branch,
118
+ changed: diff.filesChanged > 0 || diff.insertions > 0 || diff.deletions > 0 || diff.diffStat.trim().length > 0,
119
+ diffStat: diff.diffStat,
120
+ filesChanged: diff.filesChanged,
121
+ insertions: diff.insertions,
122
+ deletions: diff.deletions,
123
+ ...(diff.error ? { error: diff.error } : {}),
124
+ },
125
+ };
126
+ }),
127
+ cleanup: input.cleanup ?? {
128
+ state: "partial",
129
+ pruned: false,
130
+ tasks: input.setup.worktrees.map((worktree) => ({
131
+ index: worktree.index,
132
+ path: worktree.path,
133
+ branch: worktree.branch,
134
+ worktreeRemoved: false,
135
+ branchRemoved: false,
136
+ preserved: true,
137
+ reason: "cleanup pending durable handoff capture",
138
+ })),
139
+ },
140
+ };
141
+ const groups = existing?.groups.filter((candidate) => candidate.stepIndex !== input.stepIndex) ?? [];
142
+ groups.push(group);
143
+ groups.sort((left, right) => left.stepIndex - right.stepIndex);
144
+ const manifest: ParallelHandoffManifest = {
145
+ version: 1,
146
+ runId: input.runId,
147
+ mode: input.mode,
148
+ source: input.source,
149
+ cwd: input.cwd,
150
+ createdAt: existing?.createdAt ?? now,
151
+ updatedAt: now,
152
+ groups,
153
+ };
154
+ writeAtomicJson(input.manifestPath, manifest);
155
+ return referenceFor(input.manifestPath, manifest);
156
+ }
157
+
158
+ export function parallelHandoffPath(baseDir: string, runId?: string): string {
159
+ return runId ? path.join(baseDir, "handoffs", `${runId}.json`) : path.join(baseDir, "handoff.json");
160
+ }
161
+
162
+ export function writePendingParallelHandoff(input: {
163
+ manifestPath: string;
164
+ runId: string;
165
+ mode: "parallel" | "chain";
166
+ source: "foreground" | "async";
167
+ cwd: string;
168
+ stepIndex: number;
169
+ flatStartIndex: number;
170
+ setup: WorktreeSetup;
171
+ }): ParallelHandoffReference {
172
+ return writeParallelHandoffGroup({ ...input, diffs: [], results: [] });
173
+ }
174
+
175
+ export function formatParallelHandoffReference(reference: ParallelHandoffReference): string {
176
+ return `Parallel handoff: ${reference.path} (${reference.childCount} children, ${reference.changedPatches} changed patches, cleanup ${reference.cleanupState})`;
177
+ }
178
+
179
+ export function formatParallelHandoffError(error: unknown): string {
180
+ return `Parallel handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
181
+ }
182
+
183
+ export function discardPreservedWorktrees(
184
+ manifestPath: string,
185
+ authorization: Extract<WorktreeCleanupIntent, { kind: "discard" }>["authorization"],
186
+ ): { manifest: ParallelHandoffManifest; text: string } {
187
+ const resolvedPath = path.resolve(manifestPath);
188
+ const manifest = readManifest(resolvedPath);
189
+ if (!manifest) throw new Error(`Parallel handoff manifest not found: ${resolvedPath}`);
190
+ let attempted = 0;
191
+ for (const group of manifest.groups) {
192
+ const pending = group.cleanup.tasks.filter((task) => task.preserved && (!task.worktreeRemoved || !task.branchRemoved));
193
+ if (pending.length === 0) continue;
194
+ attempted += pending.length;
195
+ const report = cleanupWorktrees({
196
+ cwd: group.repoRoot,
197
+ baseCommit: group.baseCommit,
198
+ worktrees: pending.map((task) => ({
199
+ path: task.path,
200
+ agentCwd: task.path,
201
+ branch: task.branch,
202
+ index: task.index,
203
+ nodeModulesLinked: false,
204
+ syntheticPaths: [],
205
+ })),
206
+ }, { kind: "discard", authorization });
207
+ const updates = new Map(report.tasks.map((task) => [task.index, task.worktreeRemoved && task.branchRemoved
208
+ ? task
209
+ : { ...task, preserved: true, reason: task.reason ?? "discard cleanup remains incomplete" }]));
210
+ group.cleanup = {
211
+ state: group.cleanup.tasks.every((task) => {
212
+ const next = updates.get(task.index) ?? task;
213
+ return next.worktreeRemoved && next.branchRemoved;
214
+ }) && report.pruned ? "complete" : "partial",
215
+ tasks: group.cleanup.tasks.map((task) => updates.get(task.index) ?? task),
216
+ pruned: report.pruned,
217
+ ...(report.errors ? { errors: report.errors } : {}),
218
+ };
219
+ }
220
+ manifest.updatedAt = Date.now();
221
+ writeAtomicJson(resolvedPath, manifest);
222
+ const remaining = manifest.groups.flatMap((group) => group.cleanup.tasks.map((task) => ({ group, task })))
223
+ .filter(({ task }) => task.preserved && (!task.worktreeRemoved || !task.branchRemoved));
224
+ const lines = attempted === 0
225
+ ? [`No preserved worktrees remain in ${resolvedPath}.`]
226
+ : [`Discard processed ${attempted} preserved worktree${attempted === 1 ? "" : "s"}.`, `Manifest: ${resolvedPath}`];
227
+ if (remaining.length > 0) {
228
+ lines.push("", "Some worktrees remain. Inspect and remove them manually if appropriate:");
229
+ for (const { group, task } of remaining) {
230
+ lines.push(
231
+ ` git -C ${JSON.stringify(group.repoRoot)} status --short`,
232
+ ` git -C ${JSON.stringify(group.repoRoot)} worktree remove --force ${JSON.stringify(task.path)}`,
233
+ ` git -C ${JSON.stringify(group.repoRoot)} branch -D ${JSON.stringify(task.branch)}`,
234
+ );
235
+ }
236
+ }
237
+ return { manifest, text: lines.join("\n") };
238
+ }
@@ -0,0 +1,256 @@
1
+ export type ResolvedRunnerConfig = import("../../shared/types.ts").AgentRunnerConfig;
2
+
3
+ export interface RunnerSubagentStep {
4
+ /** Session id of the direct parent session for permission-system ask forwarding. */
5
+ parentSessionId?: string;
6
+ /** Resolved opt-in rules for native Pi child tool calls. */
7
+ permissionRules?: import("./permissions.ts").PermissionRules;
8
+ agent: string;
9
+ task: string;
10
+ runner?: ResolvedRunnerConfig;
11
+ /** Resolved launch context for this child. */
12
+ context?: "fresh" | "fork";
13
+ importAsyncRoot?: {
14
+ runId: string;
15
+ asyncDir: string;
16
+ resultPath: string;
17
+ index: number;
18
+ };
19
+ phase?: string;
20
+ label?: string;
21
+ outputName?: string;
22
+ structured?: boolean;
23
+ cwd?: string;
24
+ model?: string;
25
+ thinking?: string;
26
+ modelCandidates?: string[];
27
+ tools?: string[];
28
+ extensions?: string[];
29
+ subagentOnlyExtensions?: string[];
30
+ mcpDirectTools?: string[];
31
+ completionGuard?: boolean;
32
+ systemPrompt?: string | null;
33
+ systemPromptMode?: "append" | "replace";
34
+ inheritProjectContext: boolean;
35
+ inheritSkills: boolean;
36
+ skills?: string[];
37
+ outputPath?: string;
38
+ /** Defer the authoritative output instruction until a dynamic fanout item is materialized. */
39
+ namespaceOutputPath?: boolean;
40
+ outputMode?: "inline" | "file-only";
41
+ sessionFile?: string;
42
+ maxSubagentDepth?: number;
43
+ waitToolEnabled?: boolean;
44
+ structuredOutput?: {
45
+ schema: import("../../shared/types.ts").JsonSchemaObject;
46
+ schemaPath: string;
47
+ outputPath: string;
48
+ };
49
+ structuredOutputSchema?: import("../../shared/types.ts").JsonSchemaObject;
50
+ agentContract?: import("../../shared/types.ts").AgentContract;
51
+ definitionDigest?: string;
52
+ launchBindingTask?: string;
53
+ launchContractDigest?: string;
54
+ launchResolvedExtensions?: import("../../shared/types.ts").LaunchResolvedChildExtensionsV1;
55
+ runtimeAcknowledgedExtensions?: import("../../shared/types.ts").RuntimeAcknowledgedChildExtensionsV1;
56
+ effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
57
+ acceptanceInput?: import("../../shared/types.ts").AcceptanceInput;
58
+ acceptanceRole?: import("../../shared/types.ts").AcceptanceRole;
59
+ gateOn?: import("../../shared/types.ts").ChainGateLayer;
60
+ toolBudget?: import("../../shared/types.ts").ResolvedToolBudget;
61
+ capabilityCeiling?: import("./capability-ceiling.ts").ResolvedSubagentCapabilityCeiling;
62
+ capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
63
+ }
64
+
65
+ export interface RunnerCheckpointStep {
66
+ checkpoint: string;
67
+ message?: string;
68
+ phase?: string;
69
+ label?: string;
70
+ }
71
+
72
+ export interface ParallelStepGroup {
73
+ parallel: RunnerSubagentStep[];
74
+ concurrency?: number;
75
+ failFast?: boolean;
76
+ worktree?: boolean;
77
+ }
78
+
79
+ export interface DynamicRunnerGroup {
80
+ expand: import("../../shared/settings.ts").DynamicExpandSpec;
81
+ parallel: RunnerSubagentStep;
82
+ collect: import("../../shared/settings.ts").DynamicCollectSpec;
83
+ concurrency?: number;
84
+ failFast?: boolean;
85
+ phase?: string;
86
+ label?: string;
87
+ sessionFiles?: (string | undefined)[];
88
+ thinkingOverrides?: (string | undefined)[];
89
+ effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
90
+ acceptanceInput?: import("../../shared/types.ts").AcceptanceInput;
91
+ acceptanceRole?: import("../../shared/types.ts").AcceptanceRole;
92
+ agentContract?: import("../../shared/types.ts").AgentContract;
93
+ gateOn?: import("../../shared/types.ts").ChainGateLayer;
94
+ capabilityCeiling?: import("./capability-ceiling.ts").ResolvedSubagentCapabilityCeiling;
95
+ capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
96
+ }
97
+
98
+ export type RunnerStep = RunnerSubagentStep | ParallelStepGroup | DynamicRunnerGroup | RunnerCheckpointStep;
99
+
100
+ export function isCheckpointRunnerStep(step: RunnerStep): step is RunnerCheckpointStep {
101
+ return "checkpoint" in step;
102
+ }
103
+
104
+ export function isParallelGroup(step: RunnerStep): step is ParallelStepGroup {
105
+ return "parallel" in step && Array.isArray(step.parallel);
106
+ }
107
+
108
+ export function isDynamicRunnerGroup(step: RunnerStep): step is DynamicRunnerGroup {
109
+ return "expand" in step && "collect" in step && "parallel" in step && !Array.isArray((step as { parallel?: unknown }).parallel);
110
+ }
111
+
112
+ export function flattenSteps(steps: RunnerStep[]): RunnerSubagentStep[] {
113
+ const flat: RunnerSubagentStep[] = [];
114
+ for (const step of steps) {
115
+ if (isCheckpointRunnerStep(step)) {
116
+ continue;
117
+ } else if (isParallelGroup(step)) {
118
+ for (const task of step.parallel) flat.push(task);
119
+ } else if (isDynamicRunnerGroup(step)) {
120
+ continue;
121
+ } else {
122
+ flat.push(step);
123
+ }
124
+ }
125
+ return flat;
126
+ }
127
+
128
+ export const DEFAULT_GLOBAL_CONCURRENCY_LIMIT = 20;
129
+
130
+ /**
131
+ * A promise-based semaphore for limiting concurrent access across multiple
132
+ * mapConcurrent calls within a single run. Enforces a global cap on the total
133
+ * number of subagent tasks executing simultaneously, regardless of each step's
134
+ * per-step concurrency limit.
135
+ */
136
+ export class Semaphore {
137
+ private available: number;
138
+ private readonly queue: Array<() => void> = [];
139
+
140
+ constructor(limit: number) {
141
+ this.available = Math.max(1, Math.floor(limit) || 1);
142
+ }
143
+
144
+ acquire(): Promise<void> {
145
+ if (this.available > 0) {
146
+ this.available--;
147
+ return Promise.resolve();
148
+ }
149
+ return new Promise<void>((resolve) => {
150
+ this.queue.push(resolve);
151
+ });
152
+ }
153
+
154
+ release(): void {
155
+ const next = this.queue.shift();
156
+ if (next) {
157
+ next();
158
+ } else {
159
+ this.available++;
160
+ }
161
+ }
162
+ }
163
+
164
+ export async function mapConcurrent<T, R>(
165
+ items: T[],
166
+ limit: number,
167
+ fn: (item: T, i: number) => Promise<R>,
168
+ globalSemaphore?: Semaphore,
169
+ /** Invoked after every worker has stopped, including workers outliving an early rejection. */
170
+ onSchedulingSettled?: () => void,
171
+ ): Promise<R[]> {
172
+ const safeLimit = Math.max(1, Math.floor(limit) || 1);
173
+ const results: R[] = new Array(items.length);
174
+ let next = 0;
175
+ let liveWorkers = Math.min(safeLimit, items.length);
176
+ const notifySchedulingSettled = () => {
177
+ try {
178
+ onSchedulingSettled?.();
179
+ } catch {
180
+ // Scheduling lifecycle cleanup must not replace the worker result.
181
+ }
182
+ };
183
+
184
+ async function worker(_workerIndex: number): Promise<void> {
185
+ try {
186
+ while (next < items.length) {
187
+ const i = next++;
188
+ if (!(i in items)) throw new Error(`Missing parallel item at index ${i}`);
189
+ const item = items[i] as T;
190
+ if (globalSemaphore) {
191
+ await globalSemaphore.acquire();
192
+ try {
193
+ results[i] = await fn(item, i);
194
+ } finally {
195
+ globalSemaphore.release();
196
+ }
197
+ } else {
198
+ results[i] = await fn(item, i);
199
+ }
200
+ }
201
+ } finally {
202
+ liveWorkers--;
203
+ if (liveWorkers === 0) notifySchedulingSettled();
204
+ }
205
+ }
206
+
207
+ if (liveWorkers === 0) notifySchedulingSettled();
208
+ await Promise.all(
209
+ Array.from({ length: liveWorkers }, (_, wi) => worker(wi)),
210
+ );
211
+ return results;
212
+ }
213
+
214
+ export interface ParallelTaskResult {
215
+ agent: string;
216
+ taskIndex?: number;
217
+ output: string;
218
+ exitCode: number | null;
219
+ error?: string;
220
+ timedOut?: boolean;
221
+ model?: string;
222
+ attemptedModels?: string[];
223
+ outputTargetPath?: string;
224
+ outputTargetExists?: boolean;
225
+ }
226
+
227
+ export function aggregateParallelOutputs(
228
+ results: ParallelTaskResult[],
229
+ headerFormat: (index: number, agent: string) => string = (i, agent) =>
230
+ `=== Parallel Task ${i + 1} (${agent}) ===`,
231
+ ): string {
232
+ return results
233
+ .map((r, i) => {
234
+ const header = headerFormat(r.taskIndex ?? i, r.agent);
235
+ const hasOutput = Boolean(r.output?.trim());
236
+ const status =
237
+ r.timedOut
238
+ ? `TIMED OUT${r.error ? `: ${r.error}` : ""}`
239
+ : r.exitCode === -1
240
+ ? "SKIPPED"
241
+ : r.exitCode !== 0 && r.exitCode !== null
242
+ ? `FAILED (exit code ${r.exitCode})${r.error ? `: ${r.error}` : ""}`
243
+ : r.error
244
+ ? `WARNING: ${r.error}`
245
+ : !hasOutput && r.outputTargetPath && r.outputTargetExists === false
246
+ ? `EMPTY OUTPUT (expected output file missing: ${r.outputTargetPath})`
247
+ : !hasOutput && !r.outputTargetPath
248
+ ? "EMPTY OUTPUT (no textual response returned)"
249
+ : "";
250
+ const body = status ? (hasOutput ? `${status}\n${r.output}` : status) : r.output;
251
+ return `${header}\n${body}`;
252
+ })
253
+ .join("\n\n");
254
+ }
255
+
256
+ export const MAX_PARALLEL_CONCURRENCY = 4;