pi-agent-swarm 0.2.0 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agent-swarm",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Window-manager-native agent swarm for the Pi Coding Agent — every agent runs as a real terminal window under a tiling window manager.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,9 +43,9 @@
43
43
  "typebox": "*"
44
44
  },
45
45
  "devDependencies": {
46
- "@earendil-works/pi-ai": "1.0.2",
47
- "@earendil-works/pi-coding-agent": "1.0.2",
48
- "@earendil-works/pi-tui": "1.0.2",
46
+ "@earendil-works/pi-ai": "1.4.0",
47
+ "@earendil-works/pi-coding-agent": "1.4.0",
48
+ "@earendil-works/pi-tui": "1.4.0",
49
49
  "@types/node": "26.6.4",
50
50
  "esbuild": "0.28.2",
51
51
  "typebox": "1.3.34",
@@ -0,0 +1,169 @@
1
+ import { type Api, type AssistantMessage, contentText, type Model } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { safeTerminalLine } from "./text.js";
4
+
5
+ /** Prefix applied to auto-generated session names, replacing the MANAGER-<id> default. */
6
+ export const AUTO_NAME_PREFIX = "MAN-";
7
+ /** Auto-naming runs once, after this many completed turns. */
8
+ export const AUTO_NAME_TURN_THRESHOLD = 3;
9
+ /** Maximum length of the generated title (the part after `MAN-`), in Unicode code points. */
10
+ export const AUTO_NAME_MAX_TITLE_CHARS = 24;
11
+ /** Per-message and total caps on the conversation excerpt sent to the title model. */
12
+ export const AUTO_NAME_MAX_MESSAGE_CHARS = 500;
13
+ export const AUTO_NAME_MAX_CONTEXT_CHARS = 2_000;
14
+ /** Wall-clock budget for the one-shot title completion. */
15
+ export const AUTO_NAME_TIMEOUT_MS = 120_000;
16
+
17
+ /** Maximum title-completion attempts per session before auto-naming gives up. */
18
+ export const AUTO_NAME_MAX_ATTEMPTS = 3;
19
+
20
+ // Matches exactly what sessionStart generates: `MANAGER-` plus the first 8
21
+ // characters of the session id. Session ids are not guaranteed to be hex (UUIDs
22
+ // can put a hyphen inside the first 8 characters), so accept any non-space run.
23
+ const DEFAULT_MANAGER_NAME_PATTERN = /^MANAGER-\S{8}$/u;
24
+ const AUTO_NAME_MODEL_PATTERN = /^[^\s/]+\/[^\s/]+$/u;
25
+
26
+ /** The default name assigned to human-started sessions before auto-naming kicks in. */
27
+ export function isDefaultManagerName(name: string | undefined): boolean {
28
+ return name !== undefined && DEFAULT_MANAGER_NAME_PATTERN.test(name);
29
+ }
30
+
31
+ /** Validate the `provider/id` shape accepted by the `autoNameModel` setting. */
32
+ export function isAutoNameModel(value: string): boolean {
33
+ return AUTO_NAME_MODEL_PATTERN.test(value);
34
+ }
35
+
36
+ /**
37
+ * Turn raw model output into a `MAN-<title>` session name. Strips terminal
38
+ * controls, quotes, and markdown noise, keeps the first line, truncates to
39
+ * AUTO_NAME_MAX_TITLE_CHARS code points, and returns undefined when nothing
40
+ * usable remains. 24 CJK characters stay well under the 200-byte name budget.
41
+ */
42
+ export function toAutoName(raw: string | undefined): string | undefined {
43
+ if (!raw) return undefined;
44
+ const line = safeTerminalLine(raw)
45
+ .replace(/^[\s"'`“”‘’#>*_~-]+/u, "")
46
+ .replace(/[\s"'`“”‘’.,;:!?。,;:!?…·#>*_~-]+$/u, "")
47
+ .trim();
48
+ if (!line) return undefined;
49
+ const title = [...line].slice(0, AUTO_NAME_MAX_TITLE_CHARS).join("");
50
+ return `${AUTO_NAME_PREFIX}${title}`;
51
+ }
52
+
53
+ /**
54
+ * Collect the first AUTO_NAME_TURN_THRESHOLD user messages from the current
55
+ * branch, each clipped to AUTO_NAME_MAX_MESSAGE_CHARS and capped in total.
56
+ */
57
+ export function collectAutoNameMessages(ctx: ExtensionContext): string[] {
58
+ const messages: string[] = [];
59
+ let total = 0;
60
+ for (const entry of ctx.sessionManager.getBranch()) {
61
+ if (messages.length >= AUTO_NAME_TURN_THRESHOLD || total >= AUTO_NAME_MAX_CONTEXT_CHARS) break;
62
+ if (entry.type !== "message") continue;
63
+ const message = (entry as { message?: unknown }).message;
64
+ if (!isRecord(message) || message.role !== "user") continue;
65
+ const content = (message as { content?: unknown }).content;
66
+ if (typeof content !== "string" && !Array.isArray(content)) continue;
67
+ const text = safeTerminalLine(contentText(content as Parameters<typeof contentText>[0]));
68
+ if (!text) continue;
69
+ const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
70
+ messages.push(clipped);
71
+ total += clipped.length;
72
+ }
73
+ return messages;
74
+ }
75
+
76
+ /** Prompt asking the model for a bare, short session title in the user's language. */
77
+ export function buildAutoNamePrompt(messages: readonly string[]): string {
78
+ return [
79
+ "Summarize the user's goal in this conversation as a short session title.",
80
+ "",
81
+ "Rules:",
82
+ "- Reply with only the title: no quotes, no prefix, no trailing punctuation.",
83
+ "- Use the same language as the user messages.",
84
+ `- Keep it under ${AUTO_NAME_MAX_TITLE_CHARS} characters.`,
85
+ '- Name the task or topic, for example "修复登录页样式" or "Add payments API retry".',
86
+ "",
87
+ "User messages:",
88
+ ...messages.map((message, index) => `${index + 1}. ${message}`),
89
+ ].join("\n");
90
+ }
91
+
92
+ /**
93
+ * Resolve the model used for the title completion: the configured
94
+ * `provider/id` override when set, otherwise the session's current model.
95
+ * Returns undefined when the override cannot be resolved.
96
+ */
97
+ export function resolveAutoNameModel(ctx: ExtensionContext, configured: string | undefined): Model<Api> | undefined {
98
+ if (!configured) return ctx.model;
99
+ const slash = configured.indexOf("/");
100
+ return ctx.modelRegistry.find(configured.slice(0, slash), configured.slice(slash + 1));
101
+ }
102
+
103
+ /** Default one-shot title completion through the session's model registry. */
104
+ export async function completeSessionTitle(
105
+ ctx: ExtensionContext,
106
+ model: Model<Api>,
107
+ prompt: string,
108
+ signal?: AbortSignal,
109
+ ): Promise<string> {
110
+ const message: AssistantMessage = await ctx.modelRegistry.complete(
111
+ model,
112
+ { messages: [{ role: "user", content: prompt, timestamp: Date.now() }] },
113
+ { signal },
114
+ );
115
+ return contentText(message.content);
116
+ }
117
+
118
+ /**
119
+ * Per-session state machine for auto-name attempts. The controller feeds
120
+ * completed turns and external name changes in; the namer fires on the
121
+ * AUTO_NAME_TURN_THRESHOLD-th turn while the session still carries its
122
+ * default manager name and the user has not taken over naming. A failed
123
+ * attempt is retried on later turns, up to AUTO_NAME_MAX_ATTEMPTS attempts,
124
+ * because local single-threaded models can queue or drop one request.
125
+ */
126
+ export class AutoNamer {
127
+ private turnsSeen = 0;
128
+ private attempts = 0;
129
+ private userNamed = false;
130
+
131
+ reset(): void {
132
+ this.turnsSeen = 0;
133
+ this.attempts = 0;
134
+ this.userNamed = false;
135
+ }
136
+
137
+ /**
138
+ * Record a name change produced outside the auto-namer. A default manager
139
+ * name is the extension's own bootstrap and ignored; anything else means the
140
+ * user (or a handoff) owns the name and auto-naming stays out of the way.
141
+ */
142
+ noteExternalName(name: string | undefined): void {
143
+ if (isDefaultManagerName(name)) return;
144
+ this.userNamed = true;
145
+ }
146
+
147
+ /**
148
+ * Count one completed turn and report whether an auto-name attempt should
149
+ * start now. Each returned true consumes one attempt; after a successful
150
+ * naming the session no longer carries the default name, so later turns
151
+ * permanently settle via the userNamed path.
152
+ */
153
+ noteTurn(currentName: string | undefined, enabled: boolean): boolean {
154
+ if (this.userNamed) return false;
155
+ this.turnsSeen += 1;
156
+ if (this.turnsSeen < AUTO_NAME_TURN_THRESHOLD) return false;
157
+ if (currentName !== undefined && !isDefaultManagerName(currentName)) {
158
+ this.userNamed = true;
159
+ return false;
160
+ }
161
+ if (!enabled || this.attempts >= AUTO_NAME_MAX_ATTEMPTS) return false;
162
+ this.attempts += 1;
163
+ return true;
164
+ }
165
+ }
166
+
167
+ function isRecord(value: unknown): value is Record<string, unknown> {
168
+ return typeof value === "object" && value !== null && !Array.isArray(value);
169
+ }
@@ -0,0 +1,507 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join, resolve, sep } from "node:path";
4
+
5
+ export const WORKER_RECYCLING_DIRECTORY = join(".pi", "agent-swarm");
6
+ export const DEFAULT_MAX_CONTEXT_PERCENT = 50;
7
+ export const DEFAULT_MAX_REPLACEMENTS = 3;
8
+ export const MAX_REPLACEMENTS = 10;
9
+
10
+ const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
11
+ const TASK_PROFILES = new Set(["short", "long", "auto"]);
12
+ const LINEAGE_STATES = new Set([
13
+ "working",
14
+ "handoff_pending",
15
+ "handoff_ready",
16
+ "replacing",
17
+ "retired",
18
+ "completed",
19
+ "failed",
20
+ ]);
21
+ const SECRET_PATTERNS = [
22
+ /piagentswarm:v1:/iu,
23
+ /PI_SWARM_INVITE/iu,
24
+ /PI_SWARM_KICKOFF_CAPABILITY/iu,
25
+ /PI_SWARM_GROUP_SECRET/iu,
26
+ ];
27
+
28
+ export type WorkerTaskProfile = "short" | "long" | "auto";
29
+ export type WorkerTaskStatus = "working" | "completed";
30
+ export type WorkerLineageState =
31
+ | "working"
32
+ | "handoff_pending"
33
+ | "handoff_ready"
34
+ | "replacing"
35
+ | "retired"
36
+ | "completed"
37
+ | "failed";
38
+
39
+ export interface ContextRecyclingPolicyInput {
40
+ taskProfile: WorkerTaskProfile;
41
+ maxContextPercent?: number;
42
+ maxReplacements?: number;
43
+ }
44
+
45
+ export interface ContextRecyclingPolicy {
46
+ taskProfile: WorkerTaskProfile;
47
+ maxContextPercent: number;
48
+ maxReplacements: number;
49
+ }
50
+
51
+ export interface ContextRecyclingLaunch {
52
+ lineageId: string;
53
+ generation: number;
54
+ replacementCount: number;
55
+ policy: ContextRecyclingPolicy;
56
+ /** Successors must prove this predecessor handoff is readable during session_start. */
57
+ handoffPath?: string;
58
+ }
59
+
60
+ export interface WorkerLaunchSpecification {
61
+ cwd: string;
62
+ name?: string;
63
+ color?: string;
64
+ model?: string;
65
+ allowRequests: boolean;
66
+ }
67
+
68
+ export interface WorkerContextMetric {
69
+ tokens: number | null;
70
+ contextWindow: number;
71
+ percent: number | null;
72
+ updatedAt: string;
73
+ }
74
+
75
+ export interface WorkerHandoffContent {
76
+ originalObjective: string;
77
+ currentState: string;
78
+ completedWork: string;
79
+ remainingWork: string;
80
+ modifiedFiles: string;
81
+ verification: string;
82
+ decisions: string;
83
+ blocker: string;
84
+ nextAction: string;
85
+ artifacts: string[];
86
+ }
87
+
88
+ export type WorkerLineage = {
89
+ schemaVersion: 1;
90
+ lineageId: string;
91
+ projectRoot: string;
92
+ leaderSessionId: string;
93
+ workerSessionId?: string;
94
+ successorSessionId?: string;
95
+ originalObjective: string;
96
+ taskProfile: WorkerTaskProfile;
97
+ policy: ContextRecyclingPolicy;
98
+ launch: WorkerLaunchSpecification;
99
+ currentGeneration: number;
100
+ replacementCount: number;
101
+ state: WorkerLineageState;
102
+ currentHandoffPath?: string;
103
+ nextAction?: string;
104
+ contextUsage?: WorkerContextMetric;
105
+ updatedAt: string;
106
+ } & Record<string, unknown>;
107
+
108
+ export interface WorkerLineagePaths {
109
+ root: string;
110
+ lineageDirectory: string;
111
+ lineagePath: string;
112
+ handoffPath: string;
113
+ artifactsDirectory: string;
114
+ }
115
+
116
+ export function normalizeContextRecyclingPolicy(input: unknown): ContextRecyclingPolicy {
117
+ const value = record(input, "context recycling policy");
118
+ assertKeys(value, ["taskProfile", "maxContextPercent", "maxReplacements"], "context recycling policy");
119
+ if (typeof value.taskProfile !== "string" || !TASK_PROFILES.has(value.taskProfile)) {
120
+ throw new Error("Pi Agent Swarm context recycling task profile is invalid");
121
+ }
122
+ const maxContextPercent = value.maxContextPercent ?? DEFAULT_MAX_CONTEXT_PERCENT;
123
+ if (
124
+ typeof maxContextPercent !== "number" ||
125
+ !Number.isFinite(maxContextPercent) ||
126
+ maxContextPercent <= 0 ||
127
+ maxContextPercent > 100
128
+ ) {
129
+ throw new Error("Pi Agent Swarm context recycling percent must be greater than 0 and at most 100");
130
+ }
131
+ const maxReplacements = value.maxReplacements ?? DEFAULT_MAX_REPLACEMENTS;
132
+ if (
133
+ !Number.isInteger(maxReplacements) ||
134
+ (maxReplacements as number) < 0 ||
135
+ (maxReplacements as number) > MAX_REPLACEMENTS
136
+ ) {
137
+ throw new Error(`Pi Agent Swarm context recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
138
+ }
139
+ return {
140
+ taskProfile: value.taskProfile as WorkerTaskProfile,
141
+ maxContextPercent,
142
+ maxReplacements: maxReplacements as number,
143
+ };
144
+ }
145
+
146
+ export function contextHandoffDecision(
147
+ percent: number | null | undefined,
148
+ taskStatus: WorkerTaskStatus | undefined,
149
+ threshold = DEFAULT_MAX_CONTEXT_PERCENT,
150
+ ): "continue" | "complete" | "handoff" {
151
+ if (percent === null || percent === undefined || percent < threshold) return "continue";
152
+ return taskStatus === "completed" ? "complete" : "handoff";
153
+ }
154
+
155
+ export function workerLineagePaths(projectRoot: string, lineageId: string, generation: number): WorkerLineagePaths {
156
+ if (!SAFE_LINEAGE_ID.test(lineageId)) throw new Error("Pi Agent Swarm lineage id is invalid");
157
+ if (!Number.isInteger(generation) || generation < 1) throw new Error("Pi Agent Swarm lineage generation is invalid");
158
+ const root = resolve(projectRoot);
159
+ const storageRoot = resolve(root, WORKER_RECYCLING_DIRECTORY);
160
+ if (storageRoot !== root && !storageRoot.startsWith(`${root}${sep}`)) {
161
+ throw new Error("Pi Agent Swarm lineage storage escapes the project root");
162
+ }
163
+ const lineageDirectory = join(storageRoot, "lineages", lineageId);
164
+ return {
165
+ root: storageRoot,
166
+ lineageDirectory,
167
+ lineagePath: join(lineageDirectory, "lineage.json"),
168
+ handoffPath: join(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`),
169
+ artifactsDirectory: join(storageRoot, "artifacts", lineageId, String(generation).padStart(4, "0")),
170
+ };
171
+ }
172
+
173
+ export async function verifyWorkerHandoffReadable(projectRoot: string, launch: ContextRecyclingLaunch): Promise<void> {
174
+ if (launch.generation === 1) return;
175
+ const expected = workerLineagePaths(projectRoot, launch.lineageId, launch.generation - 1).handoffPath;
176
+ if (!launch.handoffPath || resolve(launch.handoffPath) !== expected) {
177
+ throw new Error("Pi Agent Swarm successor handoff path does not match its predecessor generation");
178
+ }
179
+ const markdown = await readFile(expected, "utf8");
180
+ const requiredSections = [
181
+ "Original objective and constraints",
182
+ "Current state",
183
+ "Completed work",
184
+ "Remaining work",
185
+ "Modified files and Git state",
186
+ "Verification performed and its results",
187
+ "Key decisions and their rationale",
188
+ "Current problem or blocker",
189
+ "Exact next action",
190
+ "Required project files and artifact paths",
191
+ ];
192
+ if (requiredSections.some((section) => !markdown.includes(`## ${section}`))) {
193
+ throw new Error("Pi Agent Swarm successor handoff is incomplete");
194
+ }
195
+ }
196
+
197
+ export async function initializeWorkerLineage(options: {
198
+ projectRoot: string;
199
+ launch: ContextRecyclingLaunch;
200
+ leaderSessionId: string;
201
+ workerSessionId: string;
202
+ specification: WorkerLaunchSpecification;
203
+ }): Promise<WorkerLineage> {
204
+ return withLineageLock(options.projectRoot, options.launch.lineageId, async () => {
205
+ const existing = await readWorkerLineageOptional(options.projectRoot, options.launch.lineageId);
206
+ if (existing && existing.currentGeneration > options.launch.generation) return existing;
207
+ const now = new Date().toISOString();
208
+ const lineage: WorkerLineage = {
209
+ ...(existing ?? {}),
210
+ schemaVersion: 1,
211
+ lineageId: options.launch.lineageId,
212
+ projectRoot: resolve(options.projectRoot),
213
+ leaderSessionId: options.leaderSessionId,
214
+ workerSessionId: options.workerSessionId,
215
+ originalObjective: existing?.originalObjective ?? "",
216
+ taskProfile: options.launch.policy.taskProfile,
217
+ policy: options.launch.policy,
218
+ launch: options.specification,
219
+ currentGeneration: options.launch.generation,
220
+ replacementCount: options.launch.replacementCount,
221
+ state: existing?.currentGeneration === options.launch.generation ? existing.state : "working",
222
+ currentHandoffPath: options.launch.handoffPath ?? existing?.currentHandoffPath,
223
+ nextAction: existing?.nextAction,
224
+ updatedAt: now,
225
+ };
226
+ const paths = workerLineagePaths(options.projectRoot, options.launch.lineageId, options.launch.generation);
227
+ await ensureStorageRoot(paths);
228
+ await mkdir(paths.artifactsDirectory, { recursive: true, mode: 0o700 });
229
+ await atomicJson(paths.lineagePath, lineage);
230
+ return lineage;
231
+ });
232
+ }
233
+
234
+ export async function readWorkerLineage(projectRoot: string, lineageId: string): Promise<WorkerLineage> {
235
+ const paths = workerLineagePaths(projectRoot, lineageId, 1);
236
+ const value = JSON.parse(await readFile(paths.lineagePath, "utf8")) as unknown;
237
+ return validateWorkerLineage(value, projectRoot, lineageId);
238
+ }
239
+
240
+ export async function updateWorkerLineage(
241
+ projectRoot: string,
242
+ lineageId: string,
243
+ patch: Record<string, unknown>,
244
+ expected: { generation?: number; state?: WorkerLineageState } = {},
245
+ ): Promise<WorkerLineage> {
246
+ return withLineageLock(projectRoot, lineageId, async () => {
247
+ const existing = await readWorkerLineage(projectRoot, lineageId);
248
+ if (expected.generation !== undefined && existing.currentGeneration !== expected.generation) {
249
+ throw new Error("Pi Agent Swarm worker lineage generation was superseded");
250
+ }
251
+ if (expected.state !== undefined && existing.state !== expected.state) {
252
+ throw new Error("Pi Agent Swarm worker lineage state changed before its update");
253
+ }
254
+ const updated = validateWorkerLineage(
255
+ { ...existing, ...patch, lineageId, projectRoot: resolve(projectRoot), updatedAt: new Date().toISOString() },
256
+ projectRoot,
257
+ lineageId,
258
+ );
259
+ await atomicJson(workerLineagePaths(projectRoot, lineageId, existing.currentGeneration).lineagePath, updated);
260
+ return updated;
261
+ });
262
+ }
263
+
264
+ export async function publishWorkerHandoff(options: {
265
+ projectRoot: string;
266
+ lineageId: string;
267
+ generation: number;
268
+ leaderSessionId: string;
269
+ policy: ContextRecyclingPolicy;
270
+ launch: WorkerLaunchSpecification;
271
+ content: WorkerHandoffContent;
272
+ nextAction: string;
273
+ }): Promise<WorkerLineagePaths> {
274
+ return withLineageLock(options.projectRoot, options.lineageId, async () => {
275
+ validateHandoff(options.content);
276
+ const root = resolve(options.projectRoot);
277
+ for (const artifact of options.content.artifacts) {
278
+ if (!isWithin(root, resolve(root, artifact))) {
279
+ throw new Error("Pi Agent Swarm handoff artifact is outside the project root");
280
+ }
281
+ }
282
+ const paths = workerLineagePaths(options.projectRoot, options.lineageId, options.generation);
283
+ const existing = await readWorkerLineageOptional(options.projectRoot, options.lineageId);
284
+ if (
285
+ existing &&
286
+ (existing.currentGeneration > options.generation ||
287
+ existing.state === "replacing" ||
288
+ (existing.state === "working" && existing.currentHandoffPath !== paths.handoffPath))
289
+ ) {
290
+ throw new Error("Pi Agent Swarm handoff was superseded by a newer generation");
291
+ }
292
+ await ensureStorageRoot(paths);
293
+ await mkdir(dirname(paths.handoffPath), { recursive: true, mode: 0o700 });
294
+ await mkdir(paths.artifactsDirectory, { recursive: true, mode: 0o700 });
295
+ await atomicText(paths.handoffPath, renderWorkerHandoff(options.content));
296
+ const lineage = validateWorkerLineage(
297
+ {
298
+ ...(existing ?? {}),
299
+ schemaVersion: 1,
300
+ lineageId: options.lineageId,
301
+ projectRoot: root,
302
+ leaderSessionId: options.leaderSessionId,
303
+ originalObjective: options.content.originalObjective,
304
+ taskProfile: options.policy.taskProfile,
305
+ policy: options.policy,
306
+ launch: options.launch,
307
+ currentGeneration: options.generation,
308
+ replacementCount: existing?.replacementCount ?? Math.max(0, options.generation - 1),
309
+ state: "handoff_ready",
310
+ currentHandoffPath: paths.handoffPath,
311
+ nextAction: options.nextAction,
312
+ remainingWork: options.content.remainingWork,
313
+ updatedAt: new Date().toISOString(),
314
+ },
315
+ options.projectRoot,
316
+ options.lineageId,
317
+ );
318
+ await atomicJson(paths.lineagePath, lineage);
319
+ return paths;
320
+ });
321
+ }
322
+
323
+ export function renderWorkerHandoff(content: WorkerHandoffContent): string {
324
+ validateHandoff(content);
325
+ const sections: [string, string][] = [
326
+ ["Original objective and constraints", content.originalObjective],
327
+ ["Current state", content.currentState],
328
+ ["Completed work", content.completedWork],
329
+ ["Remaining work", content.remainingWork],
330
+ ["Modified files and Git state", content.modifiedFiles],
331
+ ["Verification performed and its results", content.verification],
332
+ ["Key decisions and their rationale", content.decisions],
333
+ ["Current problem or blocker", content.blocker],
334
+ ["Exact next action", content.nextAction],
335
+ ["Required project files and artifact paths", content.artifacts.length > 0 ? content.artifacts.join("\n") : "None"],
336
+ ];
337
+ return `# Worker handoff\n\n${sections.map(([title, body]) => `## ${title}\n\n${body.trim() || "None"}`).join("\n\n")}\n`;
338
+ }
339
+
340
+ function validateHandoff(content: WorkerHandoffContent): void {
341
+ const value = record(content, "worker handoff");
342
+ for (const key of [
343
+ "originalObjective",
344
+ "currentState",
345
+ "completedWork",
346
+ "remainingWork",
347
+ "modifiedFiles",
348
+ "verification",
349
+ "decisions",
350
+ "blocker",
351
+ "nextAction",
352
+ ]) {
353
+ if (typeof value[key] !== "string" || Buffer.byteLength(value[key], "utf8") > 8192) {
354
+ throw new Error(`Pi Agent Swarm worker handoff ${key} is invalid`);
355
+ }
356
+ }
357
+ if (
358
+ !Array.isArray(value.artifacts) ||
359
+ value.artifacts.length > 32 ||
360
+ value.artifacts.some((item) => typeof item !== "string")
361
+ ) {
362
+ throw new Error("Pi Agent Swarm worker handoff artifacts are invalid");
363
+ }
364
+ const serialized = JSON.stringify(value);
365
+ if (Buffer.byteLength(serialized, "utf8") > 40 * 1024) throw new Error("Pi Agent Swarm worker handoff is too large");
366
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
367
+ throw new Error("Pi Agent Swarm worker handoff must not contain secret material");
368
+ }
369
+ }
370
+
371
+ async function readWorkerLineageOptional(projectRoot: string, lineageId: string): Promise<WorkerLineage | undefined> {
372
+ try {
373
+ return await readWorkerLineage(projectRoot, lineageId);
374
+ } catch (error) {
375
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
376
+ throw error;
377
+ }
378
+ }
379
+
380
+ function isWithin(root: string, candidate: string): boolean {
381
+ return candidate === root || candidate.startsWith(`${root}${sep}`);
382
+ }
383
+
384
+ async function ensureStorageRoot(paths: WorkerLineagePaths): Promise<void> {
385
+ await mkdir(paths.root, { recursive: true, mode: 0o700 });
386
+ try {
387
+ await writeFile(join(paths.root, ".gitignore"), "*\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
388
+ } catch (error) {
389
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
390
+ }
391
+ }
392
+
393
+ async function withLineageLock<T>(projectRoot: string, lineageId: string, callback: () => Promise<T>): Promise<T> {
394
+ const lockPath = `${workerLineagePaths(projectRoot, lineageId, 1).lineagePath}.lock`;
395
+ await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
396
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
397
+ for (let attempt = 0; attempt < 200 && !handle; attempt += 1) {
398
+ try {
399
+ handle = await open(lockPath, "wx", 0o600);
400
+ } catch (error) {
401
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
402
+ const lockStat = await stat(lockPath).catch(() => undefined);
403
+ if (lockStat && Date.now() - lockStat.mtimeMs > 30_000) await rm(lockPath, { force: true });
404
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 5));
405
+ }
406
+ }
407
+ if (!handle) throw new Error("Pi Agent Swarm worker lineage is busy with another update");
408
+ try {
409
+ return await callback();
410
+ } finally {
411
+ await handle.close();
412
+ await rm(lockPath, { force: true });
413
+ }
414
+ }
415
+
416
+ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: string): WorkerLineage {
417
+ const lineage = record(value, "worker lineage");
418
+ if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve(projectRoot)) {
419
+ throw new Error("Pi Agent Swarm worker lineage identity is invalid");
420
+ }
421
+ if (typeof lineage.leaderSessionId !== "string" || typeof lineage.originalObjective !== "string") {
422
+ throw new Error("Pi Agent Swarm worker lineage ownership is invalid");
423
+ }
424
+ if (!Number.isInteger(lineage.currentGeneration) || (lineage.currentGeneration as number) < 1) {
425
+ throw new Error("Pi Agent Swarm worker lineage generation is invalid");
426
+ }
427
+ if (!Number.isInteger(lineage.replacementCount) || (lineage.replacementCount as number) < 0) {
428
+ throw new Error("Pi Agent Swarm worker lineage replacement count is invalid");
429
+ }
430
+ if (typeof lineage.state !== "string" || !LINEAGE_STATES.has(lineage.state)) {
431
+ throw new Error("Pi Agent Swarm worker lineage state is invalid");
432
+ }
433
+ const policy = normalizeContextRecyclingPolicy(lineage.policy);
434
+ if (
435
+ (lineage.replacementCount as number) !== (lineage.currentGeneration as number) - 1 ||
436
+ (lineage.replacementCount as number) > policy.maxReplacements
437
+ ) {
438
+ throw new Error("Pi Agent Swarm worker lineage replacement budget is invalid");
439
+ }
440
+ const launch = record(lineage.launch, "worker lineage launch");
441
+ assertKeys(launch, ["cwd", "name", "color", "model", "allowRequests"], "worker lineage launch");
442
+ if (
443
+ typeof launch.cwd !== "string" ||
444
+ resolve(launch.cwd) !== resolve(projectRoot) ||
445
+ typeof launch.allowRequests !== "boolean"
446
+ ) {
447
+ throw new Error("Pi Agent Swarm worker lineage launch is invalid");
448
+ }
449
+ for (const key of ["name", "color", "model"] as const) {
450
+ if (
451
+ launch[key] !== undefined &&
452
+ (typeof launch[key] !== "string" || Buffer.byteLength(launch[key], "utf8") > 4_096)
453
+ ) {
454
+ throw new Error(`Pi Agent Swarm worker lineage launch ${key} is invalid`);
455
+ }
456
+ }
457
+ if (lineage.currentHandoffPath !== undefined) {
458
+ const handoffPath = resolve(String(lineage.currentHandoffPath));
459
+ const generations = join(workerLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
460
+ if (
461
+ !isWithin(generations, handoffPath) ||
462
+ !/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))
463
+ ) {
464
+ throw new Error("Pi Agent Swarm worker lineage handoff path is invalid");
465
+ }
466
+ }
467
+ for (const key of ["workerSessionId", "successorSessionId", "leaderSessionId"] as const) {
468
+ if (typeof lineage[key] !== "string" || Buffer.byteLength(lineage[key], "utf8") > 256) {
469
+ if (key !== "leaderSessionId" && lineage[key] === undefined) continue;
470
+ throw new Error(`Pi Agent Swarm worker lineage ${key} is invalid`);
471
+ }
472
+ }
473
+ if (typeof lineage.updatedAt !== "string") throw new Error("Pi Agent Swarm worker lineage update time is invalid");
474
+ return { ...lineage, policy, launch } as unknown as WorkerLineage;
475
+ }
476
+
477
+ async function atomicJson(path: string, value: unknown): Promise<void> {
478
+ const serialized = JSON.stringify(value, null, 2);
479
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
480
+ throw new Error("Pi Agent Swarm worker lineage must not contain secret material");
481
+ }
482
+ await atomicText(path, `${serialized}\n`);
483
+ }
484
+
485
+ async function atomicText(path: string, content: string): Promise<void> {
486
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
487
+ const temporary = `${path}.tmp-${process.pid}-${randomBytes(8).toString("hex")}`;
488
+ await writeFile(temporary, content, { encoding: "utf8", mode: 0o600, flag: "wx" });
489
+ try {
490
+ await rename(temporary, path);
491
+ } catch (error) {
492
+ const { rm } = await import("node:fs/promises");
493
+ await rm(temporary, { force: true }).catch(() => undefined);
494
+ throw error;
495
+ }
496
+ }
497
+
498
+ function record(value: unknown, label: string): Record<string, unknown> {
499
+ if (!value || typeof value !== "object" || Array.isArray(value))
500
+ throw new Error(`Pi Agent Swarm ${label} must be an object`);
501
+ return value as Record<string, unknown>;
502
+ }
503
+
504
+ function assertKeys(value: Record<string, unknown>, allowed: string[], label: string): void {
505
+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));
506
+ if (unknown) throw new Error(`Pi Agent Swarm ${label} has unknown field ${unknown}`);
507
+ }