pi-agent-swarm 0.4.0 → 0.5.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/README.md +21 -4
- package/dist/index.ts +7047 -1209
- package/dist/index.ts.map +4 -4
- package/package.json +1 -1
- package/src/auto-name.ts +137 -28
- package/src/budget.ts +268 -0
- package/src/context-recycling.ts +257 -52
- package/src/external-runtime.ts +374 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +64 -0
- package/src/lead-mcp-bridge.ts +516 -0
- package/src/leader-handoff-bridge.ts +155 -0
- package/src/leader-recycling.ts +752 -0
- package/src/leader-runtime.ts +1098 -0
- package/src/leader-session-runtime.ts +71 -0
- package/src/ledger.ts +351 -0
- package/src/model-catalog.ts +213 -0
- package/src/org.ts +242 -0
- package/src/pi-agent-swarm.ts +28 -7
- package/src/profile-probe.ts +143 -0
- package/src/profiles.ts +621 -0
- package/src/resource-lease.ts +250 -0
- package/src/reviewer.ts +191 -0
- package/src/settings.ts +335 -10
- package/src/swarm-controller.ts +1671 -95
- package/src/tools.ts +144 -5
- package/src/worktree.ts +86 -0
package/src/context-recycling.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import type { WorkerRole } from "./profiles.js";
|
|
4
5
|
|
|
5
6
|
export const WORKER_RECYCLING_DIRECTORY = join(".pi", "agent-swarm");
|
|
6
7
|
export const DEFAULT_MAX_CONTEXT_PERCENT = 50;
|
|
7
8
|
export const DEFAULT_MAX_REPLACEMENTS = 3;
|
|
8
9
|
export const MAX_REPLACEMENTS = 10;
|
|
9
10
|
|
|
10
|
-
const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
11
|
+
export const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
11
12
|
const TASK_PROFILES = new Set(["short", "long", "auto"]);
|
|
12
13
|
const LINEAGE_STATES = new Set([
|
|
13
14
|
"working",
|
|
@@ -18,7 +19,7 @@ const LINEAGE_STATES = new Set([
|
|
|
18
19
|
"completed",
|
|
19
20
|
"failed",
|
|
20
21
|
]);
|
|
21
|
-
const SECRET_PATTERNS = [
|
|
22
|
+
export const SECRET_PATTERNS = [
|
|
22
23
|
/piagentswarm:v1:/iu,
|
|
23
24
|
/PI_SWARM_INVITE/iu,
|
|
24
25
|
/PI_SWARM_KICKOFF_CAPABILITY/iu,
|
|
@@ -63,6 +64,9 @@ export interface WorkerLaunchSpecification {
|
|
|
63
64
|
color?: string;
|
|
64
65
|
model?: string;
|
|
65
66
|
allowRequests: boolean;
|
|
67
|
+
role?: WorkerRole;
|
|
68
|
+
profile?: string;
|
|
69
|
+
readableDirs?: string[];
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
export interface WorkerContextMetric {
|
|
@@ -72,6 +76,30 @@ export interface WorkerContextMetric {
|
|
|
72
76
|
updatedAt: string;
|
|
73
77
|
}
|
|
74
78
|
|
|
79
|
+
export interface HandoffEvidenceRef {
|
|
80
|
+
type: "file" | "artifact" | "log" | "diff" | "command";
|
|
81
|
+
ref: string;
|
|
82
|
+
/** Optional `sha256:<hex>` integrity digest verified against the file on disk. */
|
|
83
|
+
hash?: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* S3 machine-verifiable handoff header (optional; missing header falls back cleanly to
|
|
88
|
+
* the legacy 10-section Markdown validation).
|
|
89
|
+
* Minimal required fields (`task_id`, `status`, `nextAction`, `evidence`) prevent models
|
|
90
|
+
* from fabricating filler content.
|
|
91
|
+
*/
|
|
92
|
+
export interface StructuredHandoffHeader {
|
|
93
|
+
task_id: string;
|
|
94
|
+
status: "working" | "completed" | "blocked" | "handoff";
|
|
95
|
+
nextAction: string;
|
|
96
|
+
evidence: HandoffEvidenceRef[];
|
|
97
|
+
generation?: number;
|
|
98
|
+
facts?: Record<string, unknown>;
|
|
99
|
+
uncertainties?: string[];
|
|
100
|
+
requested_next_action?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
75
103
|
export interface WorkerHandoffContent {
|
|
76
104
|
originalObjective: string;
|
|
77
105
|
currentState: string;
|
|
@@ -83,8 +111,31 @@ export interface WorkerHandoffContent {
|
|
|
83
111
|
blocker: string;
|
|
84
112
|
nextAction: string;
|
|
85
113
|
artifacts: string[];
|
|
114
|
+
/** Optional S3 structured header embedded ahead of the 10-section Markdown body. */
|
|
115
|
+
structuredHeader?: StructuredHandoffHeader;
|
|
86
116
|
}
|
|
87
117
|
|
|
118
|
+
const HANDOFF_HEADER_OPEN = "<!-- pi-swarm-handoff-header:v1\n";
|
|
119
|
+
const HANDOFF_HEADER_CLOSE = "\n-->";
|
|
120
|
+
const SHA256_PREFIX = "sha256:";
|
|
121
|
+
const VALID_EVIDENCE_TYPES = new Set(["file", "artifact", "log", "diff", "command"]);
|
|
122
|
+
const VALID_HEADER_STATUSES = new Set(["working", "completed", "blocked", "handoff"]);
|
|
123
|
+
|
|
124
|
+
const HANDOFF_SECTIONS = [
|
|
125
|
+
["Original objective and constraints", "originalObjective"],
|
|
126
|
+
["Current state", "currentState"],
|
|
127
|
+
["Completed work", "completedWork"],
|
|
128
|
+
["Remaining work", "remainingWork"],
|
|
129
|
+
["Modified files and Git state", "modifiedFiles"],
|
|
130
|
+
["Verification performed and its results", "verification"],
|
|
131
|
+
["Key decisions and their rationale", "decisions"],
|
|
132
|
+
["Current problem or blocker", "blocker"],
|
|
133
|
+
["Exact next action", "nextAction"],
|
|
134
|
+
["Required project files and artifact paths", "artifacts"],
|
|
135
|
+
] as const satisfies readonly (readonly [string, keyof WorkerHandoffContent])[];
|
|
136
|
+
|
|
137
|
+
export const HANDOFF_SECTION_TITLES: readonly string[] = HANDOFF_SECTIONS.map(([title]) => title);
|
|
138
|
+
|
|
88
139
|
export type WorkerLineage = {
|
|
89
140
|
schemaVersion: 1;
|
|
90
141
|
lineageId: string;
|
|
@@ -170,6 +221,17 @@ export function workerLineagePaths(projectRoot: string, lineageId: string, gener
|
|
|
170
221
|
};
|
|
171
222
|
}
|
|
172
223
|
|
|
224
|
+
/** Whether a recorded handoff path belongs to the lineage's current generation document. */
|
|
225
|
+
export function isCurrentGenerationHandoffPath(
|
|
226
|
+
projectRoot: string,
|
|
227
|
+
lineageId: string,
|
|
228
|
+
generation: number,
|
|
229
|
+
handoffPath: string | undefined,
|
|
230
|
+
): boolean {
|
|
231
|
+
if (!handoffPath) return false;
|
|
232
|
+
return resolve(handoffPath) === workerLineagePaths(projectRoot, lineageId, generation).handoffPath;
|
|
233
|
+
}
|
|
234
|
+
|
|
173
235
|
export async function verifyWorkerHandoffReadable(projectRoot: string, launch: ContextRecyclingLaunch): Promise<void> {
|
|
174
236
|
if (launch.generation === 1) return;
|
|
175
237
|
const expected = workerLineagePaths(projectRoot, launch.lineageId, launch.generation - 1).handoffPath;
|
|
@@ -177,21 +239,120 @@ export async function verifyWorkerHandoffReadable(projectRoot: string, launch: C
|
|
|
177
239
|
throw new Error("Pi Agent Swarm successor handoff path does not match its predecessor generation");
|
|
178
240
|
}
|
|
179
241
|
const markdown = await readFile(expected, "utf8");
|
|
180
|
-
|
|
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}`))) {
|
|
242
|
+
if (!hasRequiredHandoffSections(markdown)) {
|
|
193
243
|
throw new Error("Pi Agent Swarm successor handoff is incomplete");
|
|
194
244
|
}
|
|
245
|
+
const header = parseStructuredHandoffHeader(markdown);
|
|
246
|
+
if (header) {
|
|
247
|
+
await verifyHandoffEvidence(projectRoot, header.evidence);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function computeFileSha256(filePath: string): Promise<string> {
|
|
252
|
+
const buf = await readFile(filePath);
|
|
253
|
+
return `${SHA256_PREFIX}${createHash("sha256").update(buf).digest("hex")}`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function validateStructuredHandoffHeader(raw: unknown): StructuredHandoffHeader {
|
|
257
|
+
const obj = record(raw, "handoff structured header");
|
|
258
|
+
if (typeof obj.task_id !== "string" || obj.task_id.trim().length === 0) {
|
|
259
|
+
throw new Error("Pi Agent Swarm handoff header requires a non-empty task_id");
|
|
260
|
+
}
|
|
261
|
+
if (typeof obj.status !== "string" || !VALID_HEADER_STATUSES.has(obj.status)) {
|
|
262
|
+
throw new Error(`Pi Agent Swarm handoff header status is invalid: "${String(obj.status)}"`);
|
|
263
|
+
}
|
|
264
|
+
if (typeof obj.nextAction !== "string" || obj.nextAction.trim().length === 0) {
|
|
265
|
+
throw new Error("Pi Agent Swarm handoff header requires a non-empty nextAction");
|
|
266
|
+
}
|
|
267
|
+
if (!Array.isArray(obj.evidence)) {
|
|
268
|
+
throw new Error("Pi Agent Swarm handoff header evidence must be an array");
|
|
269
|
+
}
|
|
270
|
+
const evidence: HandoffEvidenceRef[] = obj.evidence.map((entry) => {
|
|
271
|
+
const item = record(entry, "handoff evidence");
|
|
272
|
+
if (typeof item.type !== "string" || !VALID_EVIDENCE_TYPES.has(item.type)) {
|
|
273
|
+
throw new Error(`Pi Agent Swarm handoff evidence type is invalid: "${String(item.type)}"`);
|
|
274
|
+
}
|
|
275
|
+
if (typeof item.ref !== "string" || item.ref.trim().length === 0 || item.ref.includes("\0")) {
|
|
276
|
+
throw new Error("Pi Agent Swarm handoff evidence ref must be a non-empty string without NUL bytes");
|
|
277
|
+
}
|
|
278
|
+
if (item.hash !== undefined) {
|
|
279
|
+
if (typeof item.hash !== "string" || !/^sha256:[a-f0-9]{64}$/iu.test(item.hash)) {
|
|
280
|
+
throw new Error(`Pi Agent Swarm handoff evidence hash is invalid: "${String(item.hash)}"`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
type: item.type as HandoffEvidenceRef["type"],
|
|
285
|
+
ref: item.ref.trim(),
|
|
286
|
+
...(typeof item.hash === "string" ? { hash: item.hash.toLowerCase() } : {}),
|
|
287
|
+
};
|
|
288
|
+
});
|
|
289
|
+
return {
|
|
290
|
+
task_id: obj.task_id.trim(),
|
|
291
|
+
status: obj.status as StructuredHandoffHeader["status"],
|
|
292
|
+
nextAction: obj.nextAction.trim(),
|
|
293
|
+
evidence,
|
|
294
|
+
...(typeof obj.generation === "number" && Number.isInteger(obj.generation) && obj.generation >= 1
|
|
295
|
+
? { generation: obj.generation }
|
|
296
|
+
: {}),
|
|
297
|
+
...(obj.facts && typeof obj.facts === "object" && !Array.isArray(obj.facts)
|
|
298
|
+
? { facts: obj.facts as Record<string, unknown> }
|
|
299
|
+
: {}),
|
|
300
|
+
...(Array.isArray(obj.uncertainties) && obj.uncertainties.every((u) => typeof u === "string")
|
|
301
|
+
? { uncertainties: obj.uncertainties as string[] }
|
|
302
|
+
: {}),
|
|
303
|
+
...(typeof obj.requested_next_action === "string" ? { requested_next_action: obj.requested_next_action } : {}),
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function parseStructuredHandoffHeader(markdown: string): StructuredHandoffHeader | undefined {
|
|
308
|
+
if (!markdown.startsWith(HANDOFF_HEADER_OPEN)) return undefined;
|
|
309
|
+
const closeIdx = markdown.indexOf(HANDOFF_HEADER_CLOSE, HANDOFF_HEADER_OPEN.length);
|
|
310
|
+
if (closeIdx < 0) {
|
|
311
|
+
throw new Error("Pi Agent Swarm handoff structured header is malformed (missing closing marker)");
|
|
312
|
+
}
|
|
313
|
+
const rawJson = markdown.slice(HANDOFF_HEADER_OPEN.length, closeIdx).trim();
|
|
314
|
+
let parsed: unknown;
|
|
315
|
+
try {
|
|
316
|
+
parsed = JSON.parse(rawJson);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
throw new Error(
|
|
319
|
+
`Pi Agent Swarm handoff structured header JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
return validateStructuredHandoffHeader(parsed);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export async function verifyHandoffEvidence(
|
|
326
|
+
projectRoot: string,
|
|
327
|
+
evidence: readonly HandoffEvidenceRef[],
|
|
328
|
+
extraAllowedDirs: readonly string[] = [],
|
|
329
|
+
): Promise<void> {
|
|
330
|
+
const root = resolve(projectRoot);
|
|
331
|
+
const allowedRoots = [root, ...extraAllowedDirs.map((d) => resolve(d))];
|
|
332
|
+
for (const item of evidence) {
|
|
333
|
+
if (item.type === "command") continue;
|
|
334
|
+
const candidate = resolve(root, item.ref);
|
|
335
|
+
if (!allowedRoots.some((allowed) => isWithin(allowed, candidate))) {
|
|
336
|
+
throw new Error(`Pi Agent Swarm handoff evidence ref "${item.ref}" escapes allowed project roots`);
|
|
337
|
+
}
|
|
338
|
+
let info: Awaited<ReturnType<typeof stat>>;
|
|
339
|
+
try {
|
|
340
|
+
info = await stat(candidate);
|
|
341
|
+
} catch {
|
|
342
|
+
throw new Error(`Pi Agent Swarm handoff evidence ref does not exist on disk: "${item.ref}"`);
|
|
343
|
+
}
|
|
344
|
+
if (!info.isFile()) {
|
|
345
|
+
throw new Error(`Pi Agent Swarm handoff evidence ref is not a regular file: "${item.ref}"`);
|
|
346
|
+
}
|
|
347
|
+
if (item.hash) {
|
|
348
|
+
const actual = await computeFileSha256(candidate);
|
|
349
|
+
if (actual !== item.hash.toLowerCase()) {
|
|
350
|
+
throw new Error(
|
|
351
|
+
`Pi Agent Swarm handoff evidence hash mismatch for "${item.ref}": expected ${item.hash}, got ${actual}`,
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
195
356
|
}
|
|
196
357
|
|
|
197
358
|
export async function initializeWorkerLineage(options: {
|
|
@@ -210,7 +371,9 @@ export async function initializeWorkerLineage(options: {
|
|
|
210
371
|
schemaVersion: 1,
|
|
211
372
|
lineageId: options.launch.lineageId,
|
|
212
373
|
projectRoot: resolve(options.projectRoot),
|
|
213
|
-
|
|
374
|
+
// A committed successor may have rebound this lineage already; reloads of the worker still
|
|
375
|
+
// carry the previous parent session id, so the on-disk leader always wins.
|
|
376
|
+
leaderSessionId: existing?.leaderSessionId ?? options.leaderSessionId,
|
|
214
377
|
workerSessionId: options.workerSessionId,
|
|
215
378
|
originalObjective: existing?.originalObjective ?? "",
|
|
216
379
|
taskProfile: options.launch.policy.taskProfile,
|
|
@@ -270,7 +433,7 @@ export async function publishWorkerHandoff(options: {
|
|
|
270
433
|
launch: WorkerLaunchSpecification;
|
|
271
434
|
content: WorkerHandoffContent;
|
|
272
435
|
nextAction: string;
|
|
273
|
-
}): Promise<
|
|
436
|
+
}): Promise<{ handoffPath: string; leaderSessionId: string }> {
|
|
274
437
|
return withLineageLock(options.projectRoot, options.lineageId, async () => {
|
|
275
438
|
validateHandoff(options.content);
|
|
276
439
|
const root = resolve(options.projectRoot);
|
|
@@ -279,6 +442,10 @@ export async function publishWorkerHandoff(options: {
|
|
|
279
442
|
throw new Error("Pi Agent Swarm handoff artifact is outside the project root");
|
|
280
443
|
}
|
|
281
444
|
}
|
|
445
|
+
if (options.content.structuredHeader) {
|
|
446
|
+
const validHeader = validateStructuredHandoffHeader(options.content.structuredHeader);
|
|
447
|
+
await verifyHandoffEvidence(root, validHeader.evidence, options.launch.readableDirs ?? []);
|
|
448
|
+
}
|
|
282
449
|
const paths = workerLineagePaths(options.projectRoot, options.lineageId, options.generation);
|
|
283
450
|
const existing = await readWorkerLineageOptional(options.projectRoot, options.lineageId);
|
|
284
451
|
if (
|
|
@@ -299,7 +466,9 @@ export async function publishWorkerHandoff(options: {
|
|
|
299
466
|
schemaVersion: 1,
|
|
300
467
|
lineageId: options.lineageId,
|
|
301
468
|
projectRoot: root,
|
|
302
|
-
|
|
469
|
+
// The lineage file is the authority for the current leader: a concurrent rebind must win
|
|
470
|
+
// over the id this worker still holds in memory.
|
|
471
|
+
leaderSessionId: existing?.leaderSessionId ?? options.leaderSessionId,
|
|
303
472
|
originalObjective: options.content.originalObjective,
|
|
304
473
|
taskProfile: options.policy.taskProfile,
|
|
305
474
|
policy: options.policy,
|
|
@@ -316,29 +485,38 @@ export async function publishWorkerHandoff(options: {
|
|
|
316
485
|
options.lineageId,
|
|
317
486
|
);
|
|
318
487
|
await atomicJson(paths.lineagePath, lineage);
|
|
319
|
-
return paths;
|
|
488
|
+
return { handoffPath: paths.handoffPath, leaderSessionId: lineage.leaderSessionId };
|
|
320
489
|
});
|
|
321
490
|
}
|
|
322
491
|
|
|
323
492
|
export function renderWorkerHandoff(content: WorkerHandoffContent): string {
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
493
|
+
return renderHandoffDocument("Worker handoff", content, "worker");
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Shared renderer keeps worker and leader handoff contracts byte-for-byte aligned apart from the title. */
|
|
497
|
+
export function renderHandoffDocument(
|
|
498
|
+
title: string,
|
|
499
|
+
content: WorkerHandoffContent,
|
|
500
|
+
owner: "worker" | "leader",
|
|
501
|
+
): string {
|
|
502
|
+
validateHandoff(content, owner);
|
|
503
|
+
const headerBlock = content.structuredHeader
|
|
504
|
+
? `${HANDOFF_HEADER_OPEN}${JSON.stringify(validateStructuredHandoffHeader(content.structuredHeader), null, 2)}${HANDOFF_HEADER_CLOSE}\n\n`
|
|
505
|
+
: "";
|
|
506
|
+
const sections = HANDOFF_SECTIONS.map(([section, key]) => {
|
|
507
|
+
const value = content[key];
|
|
508
|
+
const body = Array.isArray(value) ? value.join("\n") : value;
|
|
509
|
+
return `## ${section}\n\n${body.trim() || "None"}`;
|
|
510
|
+
});
|
|
511
|
+
return `${headerBlock}# ${title}\n\n${sections.join("\n\n")}\n`;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export function hasRequiredHandoffSections(markdown: string): boolean {
|
|
515
|
+
return HANDOFF_SECTION_TITLES.every((section) => markdown.includes(`## ${section}`));
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function validateHandoff(content: WorkerHandoffContent, owner: "worker" | "leader" = "worker"): void {
|
|
519
|
+
const value = record(content, `${owner} handoff`);
|
|
342
520
|
for (const key of [
|
|
343
521
|
"originalObjective",
|
|
344
522
|
"currentState",
|
|
@@ -351,7 +529,7 @@ function validateHandoff(content: WorkerHandoffContent): void {
|
|
|
351
529
|
"nextAction",
|
|
352
530
|
]) {
|
|
353
531
|
if (typeof value[key] !== "string" || Buffer.byteLength(value[key], "utf8") > 8192) {
|
|
354
|
-
throw new Error(`Pi Agent Swarm
|
|
532
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff ${key} is invalid`);
|
|
355
533
|
}
|
|
356
534
|
}
|
|
357
535
|
if (
|
|
@@ -359,12 +537,13 @@ function validateHandoff(content: WorkerHandoffContent): void {
|
|
|
359
537
|
value.artifacts.length > 32 ||
|
|
360
538
|
value.artifacts.some((item) => typeof item !== "string")
|
|
361
539
|
) {
|
|
362
|
-
throw new Error(
|
|
540
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff artifacts are invalid`);
|
|
363
541
|
}
|
|
364
542
|
const serialized = JSON.stringify(value);
|
|
365
|
-
if (Buffer.byteLength(serialized, "utf8") > 40 * 1024)
|
|
543
|
+
if (Buffer.byteLength(serialized, "utf8") > 40 * 1024)
|
|
544
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff is too large`);
|
|
366
545
|
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
367
|
-
throw new Error(
|
|
546
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff must not contain secret material`);
|
|
368
547
|
}
|
|
369
548
|
}
|
|
370
549
|
|
|
@@ -377,11 +556,11 @@ async function readWorkerLineageOptional(projectRoot: string, lineageId: string)
|
|
|
377
556
|
}
|
|
378
557
|
}
|
|
379
558
|
|
|
380
|
-
function isWithin(root: string, candidate: string): boolean {
|
|
559
|
+
export function isWithin(root: string, candidate: string): boolean {
|
|
381
560
|
return candidate === root || candidate.startsWith(`${root}${sep}`);
|
|
382
561
|
}
|
|
383
562
|
|
|
384
|
-
async function ensureStorageRoot(paths:
|
|
563
|
+
export async function ensureStorageRoot(paths: { root: string }): Promise<void> {
|
|
385
564
|
await mkdir(paths.root, { recursive: true, mode: 0o700 });
|
|
386
565
|
try {
|
|
387
566
|
await writeFile(join(paths.root, ".gitignore"), "*\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
@@ -390,8 +569,14 @@ async function ensureStorageRoot(paths: WorkerLineagePaths): Promise<void> {
|
|
|
390
569
|
}
|
|
391
570
|
}
|
|
392
571
|
|
|
393
|
-
async function withLineageLock<T>(
|
|
394
|
-
|
|
572
|
+
export async function withLineageLock<T>(
|
|
573
|
+
projectRoot: string,
|
|
574
|
+
lineageId: string,
|
|
575
|
+
callback: () => Promise<T>,
|
|
576
|
+
paths: Pick<WorkerLineagePaths, "lineagePath"> = workerLineagePaths(projectRoot, lineageId, 1),
|
|
577
|
+
): Promise<T> {
|
|
578
|
+
// The caller supplies leader paths explicitly; the worker default preserves the existing isolated lock location.
|
|
579
|
+
const lockPath = `${paths.lineagePath}.lock`;
|
|
395
580
|
await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
396
581
|
let handle: Awaited<ReturnType<typeof open>> | undefined;
|
|
397
582
|
for (let attempt = 0; attempt < 200 && !handle; attempt += 1) {
|
|
@@ -404,7 +589,7 @@ async function withLineageLock<T>(projectRoot: string, lineageId: string, callba
|
|
|
404
589
|
await new Promise((resolveDelay) => setTimeout(resolveDelay, 5));
|
|
405
590
|
}
|
|
406
591
|
}
|
|
407
|
-
if (!handle) throw new Error("Pi Agent Swarm
|
|
592
|
+
if (!handle) throw new Error("Pi Agent Swarm lineage is busy with another update");
|
|
408
593
|
try {
|
|
409
594
|
return await callback();
|
|
410
595
|
} finally {
|
|
@@ -438,7 +623,11 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
|
|
|
438
623
|
throw new Error("Pi Agent Swarm worker lineage replacement budget is invalid");
|
|
439
624
|
}
|
|
440
625
|
const launch = record(lineage.launch, "worker lineage launch");
|
|
441
|
-
assertKeys(
|
|
626
|
+
assertKeys(
|
|
627
|
+
launch,
|
|
628
|
+
["cwd", "name", "color", "model", "allowRequests", "role", "profile", "readableDirs"],
|
|
629
|
+
"worker lineage launch",
|
|
630
|
+
);
|
|
442
631
|
if (
|
|
443
632
|
typeof launch.cwd !== "string" ||
|
|
444
633
|
resolve(launch.cwd) !== resolve(projectRoot) ||
|
|
@@ -446,7 +635,7 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
|
|
|
446
635
|
) {
|
|
447
636
|
throw new Error("Pi Agent Swarm worker lineage launch is invalid");
|
|
448
637
|
}
|
|
449
|
-
for (const key of ["name", "color", "model"] as const) {
|
|
638
|
+
for (const key of ["name", "color", "model", "profile"] as const) {
|
|
450
639
|
if (
|
|
451
640
|
launch[key] !== undefined &&
|
|
452
641
|
(typeof launch[key] !== "string" || Buffer.byteLength(launch[key], "utf8") > 4_096)
|
|
@@ -454,6 +643,22 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
|
|
|
454
643
|
throw new Error(`Pi Agent Swarm worker lineage launch ${key} is invalid`);
|
|
455
644
|
}
|
|
456
645
|
}
|
|
646
|
+
if (
|
|
647
|
+
launch.role !== undefined &&
|
|
648
|
+
launch.role !== "implementer" &&
|
|
649
|
+
launch.role !== "researcher" &&
|
|
650
|
+
launch.role !== "reviewer"
|
|
651
|
+
) {
|
|
652
|
+
throw new Error("Pi Agent Swarm worker lineage launch role is invalid");
|
|
653
|
+
}
|
|
654
|
+
if (
|
|
655
|
+
launch.readableDirs !== undefined &&
|
|
656
|
+
(!Array.isArray(launch.readableDirs) ||
|
|
657
|
+
launch.readableDirs.length > 32 ||
|
|
658
|
+
launch.readableDirs.some((item) => typeof item !== "string" || item.length === 0 || item.includes("\0")))
|
|
659
|
+
) {
|
|
660
|
+
throw new Error("Pi Agent Swarm worker lineage launch readableDirs is invalid");
|
|
661
|
+
}
|
|
457
662
|
if (lineage.currentHandoffPath !== undefined) {
|
|
458
663
|
const handoffPath = resolve(String(lineage.currentHandoffPath));
|
|
459
664
|
const generations = join(workerLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
|
|
@@ -474,15 +679,15 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
|
|
|
474
679
|
return { ...lineage, policy, launch } as unknown as WorkerLineage;
|
|
475
680
|
}
|
|
476
681
|
|
|
477
|
-
async function atomicJson(path: string, value: unknown): Promise<void> {
|
|
682
|
+
export async function atomicJson(path: string, value: unknown, label = "worker lineage"): Promise<void> {
|
|
478
683
|
const serialized = JSON.stringify(value, null, 2);
|
|
479
684
|
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
480
|
-
throw new Error(
|
|
685
|
+
throw new Error(`Pi Agent Swarm ${label} must not contain secret material`);
|
|
481
686
|
}
|
|
482
687
|
await atomicText(path, `${serialized}\n`);
|
|
483
688
|
}
|
|
484
689
|
|
|
485
|
-
async function atomicText(path: string, content: string): Promise<void> {
|
|
690
|
+
export async function atomicText(path: string, content: string): Promise<void> {
|
|
486
691
|
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
487
692
|
const temporary = `${path}.tmp-${process.pid}-${randomBytes(8).toString("hex")}`;
|
|
488
693
|
await writeFile(temporary, content, { encoding: "utf8", mode: 0o600, flag: "wx" });
|