pi-agent-swarm 0.3.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/README.md +24 -3
- package/dist/chunks/{menu-RH6GY6U4.ts → menu-NLK5I2DA.ts} +15 -2
- package/dist/chunks/menu-NLK5I2DA.ts.map +7 -0
- package/dist/index.ts +1112 -119
- package/dist/index.ts.map +4 -4
- package/package.json +4 -4
- package/src/context-recycling.ts +507 -0
- package/src/launch-envelope.ts +51 -0
- package/src/menu.ts +16 -2
- package/src/pi-agent-swarm.ts +34 -2
- package/src/protocol.ts +14 -3
- package/src/reload-handoff.ts +3 -0
- package/src/swarm-controller.ts +548 -6
- package/src/tools.ts +101 -3
- package/src/transport.ts +17 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +0 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-agent-swarm",
|
|
3
|
-
"version": "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
|
|
47
|
-
"@earendil-works/pi-coding-agent": "1.0
|
|
48
|
-
"@earendil-works/pi-tui": "1.0
|
|
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,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
|
+
}
|
package/src/launch-envelope.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type ContextRecyclingLaunch, normalizeContextRecyclingPolicy } from "./context-recycling.js";
|
|
2
|
+
|
|
1
3
|
type SwarmThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
2
4
|
|
|
3
5
|
export const SWARM_LAUNCH_ENV_KEYS = [
|
|
@@ -11,6 +13,7 @@ export const SWARM_LAUNCH_ENV_KEYS = [
|
|
|
11
13
|
"PI_SWARM_MODEL_PROVIDER",
|
|
12
14
|
"PI_SWARM_MODEL_ID",
|
|
13
15
|
"PI_SWARM_THINKING",
|
|
16
|
+
"PI_SWARM_CONTEXT_RECYCLING",
|
|
14
17
|
] as const;
|
|
15
18
|
|
|
16
19
|
export interface SwarmLaunchEnvelope {
|
|
@@ -21,6 +24,7 @@ export interface SwarmLaunchEnvelope {
|
|
|
21
24
|
childName?: string;
|
|
22
25
|
childColor?: string;
|
|
23
26
|
acceptsRequests: boolean;
|
|
27
|
+
contextRecycling?: ContextRecyclingLaunch;
|
|
24
28
|
model?: { provider: string; id: string; thinkingLevel?: SwarmThinkingLevel };
|
|
25
29
|
}
|
|
26
30
|
|
|
@@ -43,6 +47,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
|
|
|
43
47
|
const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
|
|
44
48
|
const childColor = optionalHexColor(values.PI_SWARM_COLOR);
|
|
45
49
|
const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
|
|
50
|
+
const contextRecycling = parseContextRecycling(values.PI_SWARM_CONTEXT_RECYCLING);
|
|
46
51
|
const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
|
|
47
52
|
const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
|
|
48
53
|
if ((provider === undefined) !== (id === undefined)) {
|
|
@@ -63,6 +68,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
|
|
|
63
68
|
...(childName ? { childName } : {}),
|
|
64
69
|
...(childColor ? { childColor } : {}),
|
|
65
70
|
acceptsRequests,
|
|
71
|
+
...(contextRecycling ? { contextRecycling } : {}),
|
|
66
72
|
...(provider && id
|
|
67
73
|
? {
|
|
68
74
|
model: {
|
|
@@ -82,6 +88,7 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
|
|
|
82
88
|
PI_SWARM_LAUNCH_ID: envelope.launchId,
|
|
83
89
|
PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
|
|
84
90
|
PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
|
|
91
|
+
...(envelope.contextRecycling ? { PI_SWARM_CONTEXT_RECYCLING: JSON.stringify(envelope.contextRecycling) } : {}),
|
|
85
92
|
...(envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {}),
|
|
86
93
|
...(envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {}),
|
|
87
94
|
...(envelope.model
|
|
@@ -94,6 +101,50 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
|
|
|
94
101
|
};
|
|
95
102
|
}
|
|
96
103
|
|
|
104
|
+
function parseContextRecycling(value: string | undefined): ContextRecyclingLaunch | undefined {
|
|
105
|
+
if (value === undefined) return undefined;
|
|
106
|
+
const boundedValue = bounded(value, "context recycling policy", 4096);
|
|
107
|
+
let parsed: unknown;
|
|
108
|
+
try {
|
|
109
|
+
parsed = JSON.parse(boundedValue);
|
|
110
|
+
} catch {
|
|
111
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
112
|
+
}
|
|
113
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
114
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
115
|
+
}
|
|
116
|
+
const candidate = parsed as Record<string, unknown>;
|
|
117
|
+
const allowed = ["lineageId", "generation", "replacementCount", "policy", "handoffPath"];
|
|
118
|
+
if (Object.keys(candidate).some((key) => !allowed.includes(key))) {
|
|
119
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
120
|
+
}
|
|
121
|
+
const lineageId = safeId(candidate.lineageId as string | undefined, "lineage id");
|
|
122
|
+
if (!Number.isInteger(candidate.generation) || (candidate.generation as number) < 1) {
|
|
123
|
+
throw new Error("Pi Agent Swarm launch context recycling generation is invalid");
|
|
124
|
+
}
|
|
125
|
+
if (!Number.isInteger(candidate.replacementCount) || (candidate.replacementCount as number) < 0) {
|
|
126
|
+
throw new Error("Pi Agent Swarm launch context recycling replacement count is invalid");
|
|
127
|
+
}
|
|
128
|
+
const handoffPath = optionalBounded(candidate.handoffPath as string | undefined, "context handoff path", 4096);
|
|
129
|
+
if ((candidate.generation === 1) !== (handoffPath === undefined)) {
|
|
130
|
+
throw new Error("Pi Agent Swarm launch context handoff path is inconsistent");
|
|
131
|
+
}
|
|
132
|
+
const policy = normalizeContextRecyclingPolicy(candidate.policy);
|
|
133
|
+
if (
|
|
134
|
+
candidate.generation !== (candidate.replacementCount as number) + 1 ||
|
|
135
|
+
(candidate.replacementCount as number) > policy.maxReplacements
|
|
136
|
+
) {
|
|
137
|
+
throw new Error("Pi Agent Swarm launch context recycling generation is inconsistent");
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
lineageId,
|
|
141
|
+
generation: candidate.generation as number,
|
|
142
|
+
replacementCount: candidate.replacementCount as number,
|
|
143
|
+
policy,
|
|
144
|
+
...(handoffPath ? { handoffPath } : {}),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
97
148
|
function parseBoolean(value: string | undefined): boolean {
|
|
98
149
|
if (value === undefined || value === "0") return false;
|
|
99
150
|
if (value === "1") return true;
|
package/src/menu.ts
CHANGED
|
@@ -12,23 +12,25 @@ export interface SwarmMenuSource {
|
|
|
12
12
|
rename(ctx: ExtensionCommandContext, name: string, signal?: AbortSignal): Promise<void>;
|
|
13
13
|
setColor(ctx: ExtensionCommandContext, color: string, signal?: AbortSignal): Promise<void>;
|
|
14
14
|
setPalette(ctx: ExtensionCommandContext, palette: SwarmColorPaletteName, signal?: AbortSignal): Promise<void>;
|
|
15
|
+
setRequests(ctx: ExtensionCommandContext, value: boolean): Promise<void>;
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
type Screen = "main";
|
|
18
|
-
type Action = "spawn" | "rename" | "setColor" | "setTheme";
|
|
19
|
+
type Action = "spawn" | "rename" | "setColor" | "setTheme" | "setRequests";
|
|
19
20
|
|
|
20
21
|
const DIRECTION_OPTIONS = ["Right", "Down", "Left", "Up"] as const;
|
|
21
22
|
const PALETTE_OPTIONS = [
|
|
22
23
|
{ label: "muted (default, low-saturation GitHub colors)", value: "muted" },
|
|
23
24
|
{ label: "bright (vivid GitHub colors)", value: "bright" },
|
|
24
25
|
] as const satisfies readonly { label: string; value: SwarmColorPaletteName }[];
|
|
26
|
+
const REQUEST_OPTIONS = ["Block (default)", "Allow paid turns from trusted peers"] as const;
|
|
25
27
|
|
|
26
28
|
export function createSwarmMenu(source: SwarmMenuSource) {
|
|
27
29
|
const getState = ({ signal }: { signal?: AbortSignal } = {}) => source.snapshot(signal);
|
|
28
30
|
const menu: MenuDefinition<SwarmMenuState, Screen, Action> = {
|
|
29
31
|
start: "main",
|
|
30
32
|
screens: {
|
|
31
|
-
main: () => ({
|
|
33
|
+
main: ({ state }) => ({
|
|
32
34
|
kind: "actions",
|
|
33
35
|
title: "Pi Agent Swarm",
|
|
34
36
|
lines: ["Spawn workers and manage this session's badge."],
|
|
@@ -53,6 +55,11 @@ export function createSwarmMenu(source: SwarmMenuSource) {
|
|
|
53
55
|
label: "Set theme",
|
|
54
56
|
action: "setTheme",
|
|
55
57
|
},
|
|
58
|
+
{
|
|
59
|
+
id: "requests",
|
|
60
|
+
label: `Follow-up requests: ${state.acceptsRequests ? "allowed" : "blocked"}`,
|
|
61
|
+
action: "setRequests",
|
|
62
|
+
},
|
|
56
63
|
],
|
|
57
64
|
hint: "close",
|
|
58
65
|
}),
|
|
@@ -63,6 +70,8 @@ export function createSwarmMenu(source: SwarmMenuSource) {
|
|
|
63
70
|
signal,
|
|
64
71
|
});
|
|
65
72
|
if (!directionChoice || signal.aborted) return { kind: "stay" };
|
|
73
|
+
const requestChoice = await ctx.ui.select("Follow-up agent requests", [...REQUEST_OPTIONS], { signal });
|
|
74
|
+
if (!requestChoice || signal.aborted) return { kind: "stay" };
|
|
66
75
|
const task = await ctx.ui.input("Optional first task", "Submit an empty value for an idle child session", {
|
|
67
76
|
signal,
|
|
68
77
|
});
|
|
@@ -71,6 +80,7 @@ export function createSwarmMenu(source: SwarmMenuSource) {
|
|
|
71
80
|
ctx,
|
|
72
81
|
{
|
|
73
82
|
direction: directionChoice.toLowerCase() as SpawnSessionInput["direction"],
|
|
83
|
+
allowRequests: requestChoice === "Allow paid turns from trusted peers",
|
|
74
84
|
...(task ? { task } : {}),
|
|
75
85
|
},
|
|
76
86
|
signal,
|
|
@@ -93,6 +103,10 @@ export function createSwarmMenu(source: SwarmMenuSource) {
|
|
|
93
103
|
await source.setColor(ctx, choice, signal);
|
|
94
104
|
return { kind: "stay" };
|
|
95
105
|
},
|
|
106
|
+
setRequests: async ({ ctx, state }) => {
|
|
107
|
+
await source.setRequests(ctx, !state.acceptsRequests);
|
|
108
|
+
return { kind: "stay" };
|
|
109
|
+
},
|
|
96
110
|
setTheme: async ({ ctx, signal }) => {
|
|
97
111
|
const choice = await ctx.ui.select(
|
|
98
112
|
"Roster theme (badge palette)",
|