pi-agent-swarm 0.4.0 → 0.6.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.
package/src/fanout.ts ADDED
@@ -0,0 +1,219 @@
1
+ import { resolve } from "node:path";
2
+ import type { ResolvedWorkerProfile, WorkerRole } from "./profiles.js";
3
+ import type { SwarmIsolationMode } from "./worktree.js";
4
+
5
+ export interface FanoutBranchSpec {
6
+ id: string;
7
+ role: WorkerRole;
8
+ profile: ResolvedWorkerProfile;
9
+ cwd: string;
10
+ model?: string;
11
+ task: string;
12
+ name?: string;
13
+ color?: string;
14
+ contextFiles?: string[];
15
+ readableDirs?: string[];
16
+ allowRequests?: boolean;
17
+ }
18
+
19
+ export interface FanoutPrecheckOptions {
20
+ maxChildren: number;
21
+ isolation: SwarmIsolationMode;
22
+ }
23
+
24
+ export class FanoutConcurrencyError extends Error {
25
+ constructor(
26
+ public readonly code:
27
+ | "empty_branches"
28
+ | "max_children_exceeded"
29
+ | "macro_opaque_forbidden"
30
+ | "resource_lock_conflict"
31
+ | "shared_workspace_write_conflict",
32
+ message: string,
33
+ ) {
34
+ super(message);
35
+ this.name = "FanoutConcurrencyError";
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Deterministic pre-flight concurrency law for `session_fanout`:
41
+ * 1. Total branches <= maxChildren;
42
+ * 2. No branch with `orchestration === "macro-opaque"` (e.g. `game`) may be fanned out;
43
+ * 3. Total demand for any profile resource cannot exceed its `concurrency` (e.g. two `pcb` writers wanting `gui:lceda`);
44
+ * 4. Multiple writable branches (`role === "implementer"`) cannot target the same cwd unless `isolation === "worktree"`.
45
+ *
46
+ * Every violation rejects the entire batch BEFORE opening any terminal window or spending any tokens.
47
+ */
48
+ export function precheckFanoutBatch(branches: readonly FanoutBranchSpec[], options: FanoutPrecheckOptions): void {
49
+ if (branches.length === 0) {
50
+ throw new FanoutConcurrencyError("empty_branches", "session_fanout requires at least one branch");
51
+ }
52
+ if (branches.length > options.maxChildren) {
53
+ throw new FanoutConcurrencyError(
54
+ "max_children_exceeded",
55
+ `session_fanout requested ${branches.length} branches, exceeding maxChildren=${options.maxChildren}`,
56
+ );
57
+ }
58
+
59
+ const resourceDemand = new Map<string, { concurrency: number; claimants: string[] }>();
60
+ const writableByCwd = new Map<string, string[]>();
61
+
62
+ for (const branch of branches) {
63
+ if (branch.profile.orchestration === "macro-opaque") {
64
+ throw new FanoutConcurrencyError(
65
+ "macro_opaque_forbidden",
66
+ `session_fanout refuses branch "${branch.id}" with macro-opaque profile "${branch.profile.id}" (nested multi-agent replication is prohibited).`,
67
+ );
68
+ }
69
+
70
+ for (const res of branch.profile.resources) {
71
+ const existing = resourceDemand.get(res.id);
72
+ if (existing) {
73
+ existing.concurrency = Math.min(existing.concurrency, res.concurrency);
74
+ existing.claimants.push(branch.id);
75
+ } else {
76
+ resourceDemand.set(res.id, { concurrency: res.concurrency, claimants: [branch.id] });
77
+ }
78
+ }
79
+
80
+ if (branch.profile.writable) {
81
+ const normalizedCwd = resolve(branch.cwd);
82
+ const list = writableByCwd.get(normalizedCwd) ?? [];
83
+ list.push(branch.id);
84
+ writableByCwd.set(normalizedCwd, list);
85
+ }
86
+ }
87
+
88
+ for (const [resourceId, demand] of resourceDemand) {
89
+ if (demand.claimants.length > demand.concurrency) {
90
+ throw new FanoutConcurrencyError(
91
+ "resource_lock_conflict",
92
+ `session_fanout rejected before launch: branches [${demand.claimants.join(", ")}] contend for singleton/bounded resource "${resourceId}" (concurrency=${demand.concurrency}). Run them sequentially or use read-only reviewer branches.`,
93
+ );
94
+ }
95
+ }
96
+
97
+ if (options.isolation !== "worktree") {
98
+ for (const [cwd, claimants] of writableByCwd) {
99
+ if (claimants.length > 1) {
100
+ throw new FanoutConcurrencyError(
101
+ "shared_workspace_write_conflict",
102
+ `session_fanout rejected before launch: writable branches [${claimants.join(", ")}] share cwd "${cwd}" without worktree isolation. Enable isolation="worktree", give distinct cwds, or use read-only researcher/reviewer roles.`,
103
+ );
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ export interface FanoutBranchResult<T = unknown> {
110
+ branchId: string;
111
+ status: "completed" | "failed" | "timed_out";
112
+ sessionId?: string;
113
+ value?: T;
114
+ error?: string;
115
+ }
116
+
117
+ export interface FanoutJoinSummary<T = unknown> {
118
+ expected: number;
119
+ received: number;
120
+ timedOut: number;
121
+ failed: number;
122
+ allowPartial: boolean;
123
+ results: FanoutBranchResult<T>[];
124
+ }
125
+
126
+ /**
127
+ * Join helper for parallel fan-out executions with bounded deadline and optional partial acceptance.
128
+ */
129
+ export async function joinFanoutBranches<T>(
130
+ branches: readonly { branchId: string; run: (signal: AbortSignal) => Promise<{ sessionId?: string; value: T }> }[],
131
+ options: { deadlineMs?: number; allowPartial?: boolean; signal?: AbortSignal } = {},
132
+ ): Promise<FanoutJoinSummary<T>> {
133
+ const allowPartial = options.allowPartial ?? true;
134
+ const deadlineMs = options.deadlineMs ?? 120_000;
135
+ const deadlineController = new AbortController();
136
+
137
+ const onOuterAbort = () => deadlineController.abort(options.signal?.reason);
138
+ if (options.signal) {
139
+ if (options.signal.aborted) {
140
+ deadlineController.abort(options.signal.reason);
141
+ } else {
142
+ options.signal.addEventListener("abort", onOuterAbort, { once: true });
143
+ }
144
+ }
145
+
146
+ let timedOutFlag = false;
147
+ const timer =
148
+ deadlineMs > 0
149
+ ? setTimeout(() => {
150
+ timedOutFlag = true;
151
+ deadlineController.abort(new Error(`Fan-out join deadline (${deadlineMs}ms) reached`));
152
+ }, deadlineMs)
153
+ : undefined;
154
+
155
+ try {
156
+ const settled = await Promise.all(
157
+ branches.map(async (branch): Promise<FanoutBranchResult<T>> => {
158
+ try {
159
+ const outcome = await raceWithAbort(branch.run(deadlineController.signal), deadlineController.signal);
160
+ return {
161
+ branchId: branch.branchId,
162
+ status: "completed",
163
+ ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),
164
+ value: outcome.value,
165
+ };
166
+ } catch (error) {
167
+ const isTimeout = timedOutFlag && deadlineController.signal.aborted;
168
+ return {
169
+ branchId: branch.branchId,
170
+ status: isTimeout ? "timed_out" : "failed",
171
+ error: error instanceof Error ? error.message : String(error),
172
+ };
173
+ }
174
+ }),
175
+ );
176
+
177
+ const received = settled.filter((r) => r.status === "completed").length;
178
+ const timedOut = settled.filter((r) => r.status === "timed_out").length;
179
+ const failed = settled.filter((r) => r.status === "failed").length;
180
+
181
+ if (!allowPartial && received < branches.length) {
182
+ throw new Error(
183
+ `Fan-out join failed with allowPartial=false: ${received}/${branches.length} completed (${timedOut} timed out, ${failed} failed)`,
184
+ );
185
+ }
186
+
187
+ return {
188
+ expected: branches.length,
189
+ received,
190
+ timedOut,
191
+ failed,
192
+ allowPartial,
193
+ results: settled,
194
+ };
195
+ } finally {
196
+ if (timer) clearTimeout(timer);
197
+ options.signal?.removeEventListener("abort", onOuterAbort);
198
+ }
199
+ }
200
+
201
+ function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
202
+ if (signal.aborted) {
203
+ return Promise.reject(signal.reason ?? new Error("Aborted"));
204
+ }
205
+ return new Promise<T>((resolvePromise, rejectPromise) => {
206
+ const onAbort = () => rejectPromise(signal.reason ?? new Error("Aborted"));
207
+ signal.addEventListener("abort", onAbort, { once: true });
208
+ promise.then(
209
+ (value) => {
210
+ signal.removeEventListener("abort", onAbort);
211
+ resolvePromise(value);
212
+ },
213
+ (error) => {
214
+ signal.removeEventListener("abort", onAbort);
215
+ rejectPromise(error);
216
+ },
217
+ );
218
+ });
219
+ }
@@ -1,4 +1,5 @@
1
1
  import { type ContextRecyclingLaunch, normalizeContextRecyclingPolicy } from "./context-recycling.js";
2
+ import type { WorkerRole } from "./profiles.js";
2
3
 
3
4
  type SwarmThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
4
5
 
@@ -14,6 +15,11 @@ export const SWARM_LAUNCH_ENV_KEYS = [
14
15
  "PI_SWARM_MODEL_ID",
15
16
  "PI_SWARM_THINKING",
16
17
  "PI_SWARM_CONTEXT_RECYCLING",
18
+ "PI_SWARM_ROLE",
19
+ "PI_SWARM_PROFILE",
20
+ "PI_SWARM_RUNTIME",
21
+ "PI_SWARM_RUNTIME_MODEL",
22
+ "PI_SWARM_READABLE_DIRS",
17
23
  ] as const;
18
24
 
19
25
  export interface SwarmLaunchEnvelope {
@@ -26,9 +32,16 @@ export interface SwarmLaunchEnvelope {
26
32
  acceptsRequests: boolean;
27
33
  contextRecycling?: ContextRecyclingLaunch;
28
34
  model?: { provider: string; id: string; thinkingLevel?: SwarmThinkingLevel };
35
+ role?: WorkerRole;
36
+ profile?: string;
37
+ runtime?: "pi" | "agy";
38
+ runtimeModel?: string;
39
+ readableDirs?: string[];
29
40
  }
30
41
 
31
42
  const THINKING_LEVELS = new Set<SwarmThinkingLevel>(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
43
+ const VALID_ROLES = new Set<WorkerRole>(["implementer", "researcher", "reviewer"]);
44
+ const VALID_RUNTIMES = new Set<"pi" | "agy">(["pi", "agy"]);
32
45
  const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
33
46
 
34
47
  export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.env): SwarmLaunchEnvelope | undefined {
@@ -60,6 +73,14 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
60
73
  if (thinking !== undefined && !THINKING_LEVELS.has(thinking as SwarmThinkingLevel)) {
61
74
  throw new Error("Pi Agent Swarm launch thinking level is invalid");
62
75
  }
76
+ const role = parseRole(values.PI_SWARM_ROLE);
77
+ const profile = optionalBounded(values.PI_SWARM_PROFILE, "profile", 64);
78
+ const runtime = parseRuntime(values.PI_SWARM_RUNTIME);
79
+ const runtimeModel = optionalBounded(values.PI_SWARM_RUNTIME_MODEL, "runtime model", 200);
80
+ if (runtime === "agy" && !runtimeModel) {
81
+ throw new Error("Pi Agent Swarm launch runtime model is required for agy runtime");
82
+ }
83
+ const readableDirs = parseReadableDirs(values.PI_SWARM_READABLE_DIRS);
63
84
  return {
64
85
  invite,
65
86
  parentSessionId,
@@ -78,6 +99,11 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
78
99
  },
79
100
  }
80
101
  : {}),
102
+ ...(role ? { role } : {}),
103
+ ...(profile ? { profile } : {}),
104
+ ...(runtime ? { runtime } : {}),
105
+ ...(runtimeModel ? { runtimeModel } : {}),
106
+ ...(readableDirs ? { readableDirs } : {}),
81
107
  };
82
108
  }
83
109
 
@@ -98,6 +124,11 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
98
124
  ...(envelope.model.thinkingLevel ? { PI_SWARM_THINKING: envelope.model.thinkingLevel } : {}),
99
125
  }
100
126
  : {}),
127
+ ...(envelope.role ? { PI_SWARM_ROLE: envelope.role } : {}),
128
+ ...(envelope.profile ? { PI_SWARM_PROFILE: envelope.profile } : {}),
129
+ ...(envelope.runtime ? { PI_SWARM_RUNTIME: envelope.runtime } : {}),
130
+ ...(envelope.runtimeModel ? { PI_SWARM_RUNTIME_MODEL: envelope.runtimeModel } : {}),
131
+ ...(envelope.readableDirs?.length ? { PI_SWARM_READABLE_DIRS: JSON.stringify(envelope.readableDirs) } : {}),
101
132
  };
102
133
  }
103
134
 
@@ -167,6 +198,39 @@ function optionalBounded(value: string | undefined, label: string, maxBytes: num
167
198
  return value === undefined ? undefined : bounded(value, label, maxBytes);
168
199
  }
169
200
 
201
+ function parseRole(value: string | undefined): WorkerRole | undefined {
202
+ if (value === undefined) return undefined;
203
+ if (!VALID_ROLES.has(value as WorkerRole)) throw new Error("Pi Agent Swarm launch role is invalid");
204
+ return value as WorkerRole;
205
+ }
206
+
207
+ function parseRuntime(value: string | undefined): "pi" | "agy" | undefined {
208
+ if (value === undefined) return undefined;
209
+ if (!VALID_RUNTIMES.has(value as "pi" | "agy")) throw new Error("Pi Agent Swarm launch runtime is invalid");
210
+ return value as "pi" | "agy";
211
+ }
212
+
213
+ function parseReadableDirs(value: string | undefined): string[] | undefined {
214
+ if (value === undefined) return undefined;
215
+ const boundedValue = bounded(value, "readable dirs", 16_384);
216
+ let parsed: unknown;
217
+ try {
218
+ parsed = JSON.parse(boundedValue);
219
+ } catch {
220
+ throw new Error("Pi Agent Swarm launch readable dirs is invalid");
221
+ }
222
+ if (
223
+ !Array.isArray(parsed) ||
224
+ parsed.length > 32 ||
225
+ parsed.some(
226
+ (item) => typeof item !== "string" || item.length === 0 || item.includes("\0") || Buffer.byteLength(item) > 4_096,
227
+ )
228
+ ) {
229
+ throw new Error("Pi Agent Swarm launch readable dirs is invalid");
230
+ }
231
+ return parsed as string[];
232
+ }
233
+
170
234
  function optionalHexColor(value: string | undefined): string | undefined {
171
235
  if (value === undefined) return undefined;
172
236
  const lower = value.toLowerCase();