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/dist/index.ts
CHANGED
|
@@ -32,6 +32,7 @@ var ENDPOINT_ID = /^[a-f0-9]{24}$/u;
|
|
|
32
32
|
var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/u;
|
|
33
33
|
var BASE64URL_MAC = /^[A-Za-z0-9_-]{43}$/u;
|
|
34
34
|
var ACK_CODES = /* @__PURE__ */ new Set([
|
|
35
|
+
"context_handoff",
|
|
35
36
|
"delivery_failed",
|
|
36
37
|
"kickoff_consumed",
|
|
37
38
|
"launch_mismatch",
|
|
@@ -169,9 +170,12 @@ function validateMessage(value) {
|
|
|
169
170
|
}
|
|
170
171
|
const replyTo = optionalId(value.replyTo, "reply message id");
|
|
171
172
|
const launchId = optionalId(value.launchId, "launch id");
|
|
172
|
-
if (value.kind !== void 0 && value.kind !== "lead" && value.kind !== "steer" && value.kind !== "shutdown") {
|
|
173
|
+
if (value.kind !== void 0 && value.kind !== "lead" && value.kind !== "steer" && value.kind !== "shutdown" && value.kind !== "handoff") {
|
|
173
174
|
throw new Error("Pi Agent Swarm message kind is invalid");
|
|
174
175
|
}
|
|
176
|
+
if (value.kind === "handoff" && mode !== "notify") {
|
|
177
|
+
throw new Error("Pi Agent Swarm handoff must be a notify control message");
|
|
178
|
+
}
|
|
175
179
|
if (mode === "reply" && !replyTo) throw new Error("Pi Agent Swarm reply requires a reply message id");
|
|
176
180
|
if (mode === "kickoff" && !launchId) throw new Error("Pi Agent Swarm kickoff requires a launch id");
|
|
177
181
|
return {
|
|
@@ -1046,14 +1050,365 @@ function formatError(error) {
|
|
|
1046
1050
|
}
|
|
1047
1051
|
|
|
1048
1052
|
// src/swarm-controller.ts
|
|
1049
|
-
import { randomBytes as
|
|
1050
|
-
import { readFile, realpath as realpath2, rename as
|
|
1051
|
-
import { join as
|
|
1053
|
+
import { randomBytes as randomBytes6 } from "node:crypto";
|
|
1054
|
+
import { readdir, readFile as readFile2, realpath as realpath2, rename as rename4, rm as rm6, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1055
|
+
import { basename as basename5, dirname as dirname6, join as join8, resolve as resolve6, sep as sep3 } from "node:path";
|
|
1056
|
+
|
|
1057
|
+
// src/context-recycling.ts
|
|
1058
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1059
|
+
import { mkdir as mkdir2, open as open2, readFile, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
|
|
1060
|
+
import { dirname as dirname2, join as join2, resolve, sep } from "node:path";
|
|
1061
|
+
var WORKER_RECYCLING_DIRECTORY = join2(".pi", "agent-swarm");
|
|
1062
|
+
var DEFAULT_MAX_CONTEXT_PERCENT = 50;
|
|
1063
|
+
var DEFAULT_MAX_REPLACEMENTS = 3;
|
|
1064
|
+
var MAX_REPLACEMENTS = 10;
|
|
1065
|
+
var SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
1066
|
+
var TASK_PROFILES = /* @__PURE__ */ new Set(["short", "long", "auto"]);
|
|
1067
|
+
var LINEAGE_STATES = /* @__PURE__ */ new Set([
|
|
1068
|
+
"working",
|
|
1069
|
+
"handoff_pending",
|
|
1070
|
+
"handoff_ready",
|
|
1071
|
+
"replacing",
|
|
1072
|
+
"retired",
|
|
1073
|
+
"completed",
|
|
1074
|
+
"failed"
|
|
1075
|
+
]);
|
|
1076
|
+
var SECRET_PATTERNS = [
|
|
1077
|
+
/piagentswarm:v1:/iu,
|
|
1078
|
+
/PI_SWARM_INVITE/iu,
|
|
1079
|
+
/PI_SWARM_KICKOFF_CAPABILITY/iu,
|
|
1080
|
+
/PI_SWARM_GROUP_SECRET/iu
|
|
1081
|
+
];
|
|
1082
|
+
function normalizeContextRecyclingPolicy(input) {
|
|
1083
|
+
const value = record(input, "context recycling policy");
|
|
1084
|
+
assertKeys(value, ["taskProfile", "maxContextPercent", "maxReplacements"], "context recycling policy");
|
|
1085
|
+
if (typeof value.taskProfile !== "string" || !TASK_PROFILES.has(value.taskProfile)) {
|
|
1086
|
+
throw new Error("Pi Agent Swarm context recycling task profile is invalid");
|
|
1087
|
+
}
|
|
1088
|
+
const maxContextPercent = value.maxContextPercent ?? DEFAULT_MAX_CONTEXT_PERCENT;
|
|
1089
|
+
if (typeof maxContextPercent !== "number" || !Number.isFinite(maxContextPercent) || maxContextPercent <= 0 || maxContextPercent > 100) {
|
|
1090
|
+
throw new Error("Pi Agent Swarm context recycling percent must be greater than 0 and at most 100");
|
|
1091
|
+
}
|
|
1092
|
+
const maxReplacements = value.maxReplacements ?? DEFAULT_MAX_REPLACEMENTS;
|
|
1093
|
+
if (!Number.isInteger(maxReplacements) || maxReplacements < 0 || maxReplacements > MAX_REPLACEMENTS) {
|
|
1094
|
+
throw new Error(`Pi Agent Swarm context recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
|
|
1095
|
+
}
|
|
1096
|
+
return {
|
|
1097
|
+
taskProfile: value.taskProfile,
|
|
1098
|
+
maxContextPercent,
|
|
1099
|
+
maxReplacements
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
function contextHandoffDecision(percent, taskStatus, threshold = DEFAULT_MAX_CONTEXT_PERCENT) {
|
|
1103
|
+
if (percent === null || percent === void 0 || percent < threshold) return "continue";
|
|
1104
|
+
return taskStatus === "completed" ? "complete" : "handoff";
|
|
1105
|
+
}
|
|
1106
|
+
function workerLineagePaths(projectRoot, lineageId, generation) {
|
|
1107
|
+
if (!SAFE_LINEAGE_ID.test(lineageId)) throw new Error("Pi Agent Swarm lineage id is invalid");
|
|
1108
|
+
if (!Number.isInteger(generation) || generation < 1) throw new Error("Pi Agent Swarm lineage generation is invalid");
|
|
1109
|
+
const root = resolve(projectRoot);
|
|
1110
|
+
const storageRoot = resolve(root, WORKER_RECYCLING_DIRECTORY);
|
|
1111
|
+
if (storageRoot !== root && !storageRoot.startsWith(`${root}${sep}`)) {
|
|
1112
|
+
throw new Error("Pi Agent Swarm lineage storage escapes the project root");
|
|
1113
|
+
}
|
|
1114
|
+
const lineageDirectory = join2(storageRoot, "lineages", lineageId);
|
|
1115
|
+
return {
|
|
1116
|
+
root: storageRoot,
|
|
1117
|
+
lineageDirectory,
|
|
1118
|
+
lineagePath: join2(lineageDirectory, "lineage.json"),
|
|
1119
|
+
handoffPath: join2(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`),
|
|
1120
|
+
artifactsDirectory: join2(storageRoot, "artifacts", lineageId, String(generation).padStart(4, "0"))
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
async function verifyWorkerHandoffReadable(projectRoot, launch) {
|
|
1124
|
+
if (launch.generation === 1) return;
|
|
1125
|
+
const expected = workerLineagePaths(projectRoot, launch.lineageId, launch.generation - 1).handoffPath;
|
|
1126
|
+
if (!launch.handoffPath || resolve(launch.handoffPath) !== expected) {
|
|
1127
|
+
throw new Error("Pi Agent Swarm successor handoff path does not match its predecessor generation");
|
|
1128
|
+
}
|
|
1129
|
+
const markdown = await readFile(expected, "utf8");
|
|
1130
|
+
const requiredSections = [
|
|
1131
|
+
"Original objective and constraints",
|
|
1132
|
+
"Current state",
|
|
1133
|
+
"Completed work",
|
|
1134
|
+
"Remaining work",
|
|
1135
|
+
"Modified files and Git state",
|
|
1136
|
+
"Verification performed and its results",
|
|
1137
|
+
"Key decisions and their rationale",
|
|
1138
|
+
"Current problem or blocker",
|
|
1139
|
+
"Exact next action",
|
|
1140
|
+
"Required project files and artifact paths"
|
|
1141
|
+
];
|
|
1142
|
+
if (requiredSections.some((section) => !markdown.includes(`## ${section}`))) {
|
|
1143
|
+
throw new Error("Pi Agent Swarm successor handoff is incomplete");
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
async function initializeWorkerLineage(options) {
|
|
1147
|
+
return withLineageLock(options.projectRoot, options.launch.lineageId, async () => {
|
|
1148
|
+
const existing = await readWorkerLineageOptional(options.projectRoot, options.launch.lineageId);
|
|
1149
|
+
if (existing && existing.currentGeneration > options.launch.generation) return existing;
|
|
1150
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1151
|
+
const lineage = {
|
|
1152
|
+
...existing ?? {},
|
|
1153
|
+
schemaVersion: 1,
|
|
1154
|
+
lineageId: options.launch.lineageId,
|
|
1155
|
+
projectRoot: resolve(options.projectRoot),
|
|
1156
|
+
leaderSessionId: options.leaderSessionId,
|
|
1157
|
+
workerSessionId: options.workerSessionId,
|
|
1158
|
+
originalObjective: existing?.originalObjective ?? "",
|
|
1159
|
+
taskProfile: options.launch.policy.taskProfile,
|
|
1160
|
+
policy: options.launch.policy,
|
|
1161
|
+
launch: options.specification,
|
|
1162
|
+
currentGeneration: options.launch.generation,
|
|
1163
|
+
replacementCount: options.launch.replacementCount,
|
|
1164
|
+
state: existing?.currentGeneration === options.launch.generation ? existing.state : "working",
|
|
1165
|
+
currentHandoffPath: options.launch.handoffPath ?? existing?.currentHandoffPath,
|
|
1166
|
+
nextAction: existing?.nextAction,
|
|
1167
|
+
updatedAt: now
|
|
1168
|
+
};
|
|
1169
|
+
const paths = workerLineagePaths(options.projectRoot, options.launch.lineageId, options.launch.generation);
|
|
1170
|
+
await ensureStorageRoot(paths);
|
|
1171
|
+
await mkdir2(paths.artifactsDirectory, { recursive: true, mode: 448 });
|
|
1172
|
+
await atomicJson(paths.lineagePath, lineage);
|
|
1173
|
+
return lineage;
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
async function readWorkerLineage(projectRoot, lineageId) {
|
|
1177
|
+
const paths = workerLineagePaths(projectRoot, lineageId, 1);
|
|
1178
|
+
const value = JSON.parse(await readFile(paths.lineagePath, "utf8"));
|
|
1179
|
+
return validateWorkerLineage(value, projectRoot, lineageId);
|
|
1180
|
+
}
|
|
1181
|
+
async function updateWorkerLineage(projectRoot, lineageId, patch, expected = {}) {
|
|
1182
|
+
return withLineageLock(projectRoot, lineageId, async () => {
|
|
1183
|
+
const existing = await readWorkerLineage(projectRoot, lineageId);
|
|
1184
|
+
if (expected.generation !== void 0 && existing.currentGeneration !== expected.generation) {
|
|
1185
|
+
throw new Error("Pi Agent Swarm worker lineage generation was superseded");
|
|
1186
|
+
}
|
|
1187
|
+
if (expected.state !== void 0 && existing.state !== expected.state) {
|
|
1188
|
+
throw new Error("Pi Agent Swarm worker lineage state changed before its update");
|
|
1189
|
+
}
|
|
1190
|
+
const updated = validateWorkerLineage(
|
|
1191
|
+
{ ...existing, ...patch, lineageId, projectRoot: resolve(projectRoot), updatedAt: (/* @__PURE__ */ new Date()).toISOString() },
|
|
1192
|
+
projectRoot,
|
|
1193
|
+
lineageId
|
|
1194
|
+
);
|
|
1195
|
+
await atomicJson(workerLineagePaths(projectRoot, lineageId, existing.currentGeneration).lineagePath, updated);
|
|
1196
|
+
return updated;
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
async function publishWorkerHandoff(options) {
|
|
1200
|
+
return withLineageLock(options.projectRoot, options.lineageId, async () => {
|
|
1201
|
+
validateHandoff(options.content);
|
|
1202
|
+
const root = resolve(options.projectRoot);
|
|
1203
|
+
for (const artifact of options.content.artifacts) {
|
|
1204
|
+
if (!isWithin(root, resolve(root, artifact))) {
|
|
1205
|
+
throw new Error("Pi Agent Swarm handoff artifact is outside the project root");
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
const paths = workerLineagePaths(options.projectRoot, options.lineageId, options.generation);
|
|
1209
|
+
const existing = await readWorkerLineageOptional(options.projectRoot, options.lineageId);
|
|
1210
|
+
if (existing && (existing.currentGeneration > options.generation || existing.state === "replacing" || existing.state === "working" && existing.currentHandoffPath !== paths.handoffPath)) {
|
|
1211
|
+
throw new Error("Pi Agent Swarm handoff was superseded by a newer generation");
|
|
1212
|
+
}
|
|
1213
|
+
await ensureStorageRoot(paths);
|
|
1214
|
+
await mkdir2(dirname2(paths.handoffPath), { recursive: true, mode: 448 });
|
|
1215
|
+
await mkdir2(paths.artifactsDirectory, { recursive: true, mode: 448 });
|
|
1216
|
+
await atomicText(paths.handoffPath, renderWorkerHandoff(options.content));
|
|
1217
|
+
const lineage = validateWorkerLineage(
|
|
1218
|
+
{
|
|
1219
|
+
...existing ?? {},
|
|
1220
|
+
schemaVersion: 1,
|
|
1221
|
+
lineageId: options.lineageId,
|
|
1222
|
+
projectRoot: root,
|
|
1223
|
+
leaderSessionId: options.leaderSessionId,
|
|
1224
|
+
originalObjective: options.content.originalObjective,
|
|
1225
|
+
taskProfile: options.policy.taskProfile,
|
|
1226
|
+
policy: options.policy,
|
|
1227
|
+
launch: options.launch,
|
|
1228
|
+
currentGeneration: options.generation,
|
|
1229
|
+
replacementCount: existing?.replacementCount ?? Math.max(0, options.generation - 1),
|
|
1230
|
+
state: "handoff_ready",
|
|
1231
|
+
currentHandoffPath: paths.handoffPath,
|
|
1232
|
+
nextAction: options.nextAction,
|
|
1233
|
+
remainingWork: options.content.remainingWork,
|
|
1234
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1235
|
+
},
|
|
1236
|
+
options.projectRoot,
|
|
1237
|
+
options.lineageId
|
|
1238
|
+
);
|
|
1239
|
+
await atomicJson(paths.lineagePath, lineage);
|
|
1240
|
+
return paths;
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
function renderWorkerHandoff(content) {
|
|
1244
|
+
validateHandoff(content);
|
|
1245
|
+
const sections = [
|
|
1246
|
+
["Original objective and constraints", content.originalObjective],
|
|
1247
|
+
["Current state", content.currentState],
|
|
1248
|
+
["Completed work", content.completedWork],
|
|
1249
|
+
["Remaining work", content.remainingWork],
|
|
1250
|
+
["Modified files and Git state", content.modifiedFiles],
|
|
1251
|
+
["Verification performed and its results", content.verification],
|
|
1252
|
+
["Key decisions and their rationale", content.decisions],
|
|
1253
|
+
["Current problem or blocker", content.blocker],
|
|
1254
|
+
["Exact next action", content.nextAction],
|
|
1255
|
+
["Required project files and artifact paths", content.artifacts.length > 0 ? content.artifacts.join("\n") : "None"]
|
|
1256
|
+
];
|
|
1257
|
+
return `# Worker handoff
|
|
1258
|
+
|
|
1259
|
+
${sections.map(([title, body]) => `## ${title}
|
|
1260
|
+
|
|
1261
|
+
${body.trim() || "None"}`).join("\n\n")}
|
|
1262
|
+
`;
|
|
1263
|
+
}
|
|
1264
|
+
function validateHandoff(content) {
|
|
1265
|
+
const value = record(content, "worker handoff");
|
|
1266
|
+
for (const key of [
|
|
1267
|
+
"originalObjective",
|
|
1268
|
+
"currentState",
|
|
1269
|
+
"completedWork",
|
|
1270
|
+
"remainingWork",
|
|
1271
|
+
"modifiedFiles",
|
|
1272
|
+
"verification",
|
|
1273
|
+
"decisions",
|
|
1274
|
+
"blocker",
|
|
1275
|
+
"nextAction"
|
|
1276
|
+
]) {
|
|
1277
|
+
if (typeof value[key] !== "string" || Buffer.byteLength(value[key], "utf8") > 8192) {
|
|
1278
|
+
throw new Error(`Pi Agent Swarm worker handoff ${key} is invalid`);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
if (!Array.isArray(value.artifacts) || value.artifacts.length > 32 || value.artifacts.some((item) => typeof item !== "string")) {
|
|
1282
|
+
throw new Error("Pi Agent Swarm worker handoff artifacts are invalid");
|
|
1283
|
+
}
|
|
1284
|
+
const serialized = JSON.stringify(value);
|
|
1285
|
+
if (Buffer.byteLength(serialized, "utf8") > 40 * 1024) throw new Error("Pi Agent Swarm worker handoff is too large");
|
|
1286
|
+
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
1287
|
+
throw new Error("Pi Agent Swarm worker handoff must not contain secret material");
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
async function readWorkerLineageOptional(projectRoot, lineageId) {
|
|
1291
|
+
try {
|
|
1292
|
+
return await readWorkerLineage(projectRoot, lineageId);
|
|
1293
|
+
} catch (error) {
|
|
1294
|
+
if (error.code === "ENOENT") return void 0;
|
|
1295
|
+
throw error;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function isWithin(root, candidate) {
|
|
1299
|
+
return candidate === root || candidate.startsWith(`${root}${sep}`);
|
|
1300
|
+
}
|
|
1301
|
+
async function ensureStorageRoot(paths) {
|
|
1302
|
+
await mkdir2(paths.root, { recursive: true, mode: 448 });
|
|
1303
|
+
try {
|
|
1304
|
+
await writeFile2(join2(paths.root, ".gitignore"), "*\n", { encoding: "utf8", mode: 384, flag: "wx" });
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
if (error.code !== "EEXIST") throw error;
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
async function withLineageLock(projectRoot, lineageId, callback) {
|
|
1310
|
+
const lockPath = `${workerLineagePaths(projectRoot, lineageId, 1).lineagePath}.lock`;
|
|
1311
|
+
await mkdir2(dirname2(lockPath), { recursive: true, mode: 448 });
|
|
1312
|
+
let handle;
|
|
1313
|
+
for (let attempt = 0; attempt < 200 && !handle; attempt += 1) {
|
|
1314
|
+
try {
|
|
1315
|
+
handle = await open2(lockPath, "wx", 384);
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
if (error.code !== "EEXIST") throw error;
|
|
1318
|
+
const lockStat = await stat(lockPath).catch(() => void 0);
|
|
1319
|
+
if (lockStat && Date.now() - lockStat.mtimeMs > 3e4) await rm2(lockPath, { force: true });
|
|
1320
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 5));
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
if (!handle) throw new Error("Pi Agent Swarm worker lineage is busy with another update");
|
|
1324
|
+
try {
|
|
1325
|
+
return await callback();
|
|
1326
|
+
} finally {
|
|
1327
|
+
await handle.close();
|
|
1328
|
+
await rm2(lockPath, { force: true });
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
function validateWorkerLineage(value, projectRoot, lineageId) {
|
|
1332
|
+
const lineage = record(value, "worker lineage");
|
|
1333
|
+
if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve(projectRoot)) {
|
|
1334
|
+
throw new Error("Pi Agent Swarm worker lineage identity is invalid");
|
|
1335
|
+
}
|
|
1336
|
+
if (typeof lineage.leaderSessionId !== "string" || typeof lineage.originalObjective !== "string") {
|
|
1337
|
+
throw new Error("Pi Agent Swarm worker lineage ownership is invalid");
|
|
1338
|
+
}
|
|
1339
|
+
if (!Number.isInteger(lineage.currentGeneration) || lineage.currentGeneration < 1) {
|
|
1340
|
+
throw new Error("Pi Agent Swarm worker lineage generation is invalid");
|
|
1341
|
+
}
|
|
1342
|
+
if (!Number.isInteger(lineage.replacementCount) || lineage.replacementCount < 0) {
|
|
1343
|
+
throw new Error("Pi Agent Swarm worker lineage replacement count is invalid");
|
|
1344
|
+
}
|
|
1345
|
+
if (typeof lineage.state !== "string" || !LINEAGE_STATES.has(lineage.state)) {
|
|
1346
|
+
throw new Error("Pi Agent Swarm worker lineage state is invalid");
|
|
1347
|
+
}
|
|
1348
|
+
const policy = normalizeContextRecyclingPolicy(lineage.policy);
|
|
1349
|
+
if (lineage.replacementCount !== lineage.currentGeneration - 1 || lineage.replacementCount > policy.maxReplacements) {
|
|
1350
|
+
throw new Error("Pi Agent Swarm worker lineage replacement budget is invalid");
|
|
1351
|
+
}
|
|
1352
|
+
const launch = record(lineage.launch, "worker lineage launch");
|
|
1353
|
+
assertKeys(launch, ["cwd", "name", "color", "model", "allowRequests"], "worker lineage launch");
|
|
1354
|
+
if (typeof launch.cwd !== "string" || resolve(launch.cwd) !== resolve(projectRoot) || typeof launch.allowRequests !== "boolean") {
|
|
1355
|
+
throw new Error("Pi Agent Swarm worker lineage launch is invalid");
|
|
1356
|
+
}
|
|
1357
|
+
for (const key of ["name", "color", "model"]) {
|
|
1358
|
+
if (launch[key] !== void 0 && (typeof launch[key] !== "string" || Buffer.byteLength(launch[key], "utf8") > 4096)) {
|
|
1359
|
+
throw new Error(`Pi Agent Swarm worker lineage launch ${key} is invalid`);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
if (lineage.currentHandoffPath !== void 0) {
|
|
1363
|
+
const handoffPath = resolve(String(lineage.currentHandoffPath));
|
|
1364
|
+
const generations = join2(workerLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
|
|
1365
|
+
if (!isWithin(generations, handoffPath) || !/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))) {
|
|
1366
|
+
throw new Error("Pi Agent Swarm worker lineage handoff path is invalid");
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
for (const key of ["workerSessionId", "successorSessionId", "leaderSessionId"]) {
|
|
1370
|
+
if (typeof lineage[key] !== "string" || Buffer.byteLength(lineage[key], "utf8") > 256) {
|
|
1371
|
+
if (key !== "leaderSessionId" && lineage[key] === void 0) continue;
|
|
1372
|
+
throw new Error(`Pi Agent Swarm worker lineage ${key} is invalid`);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
if (typeof lineage.updatedAt !== "string") throw new Error("Pi Agent Swarm worker lineage update time is invalid");
|
|
1376
|
+
return { ...lineage, policy, launch };
|
|
1377
|
+
}
|
|
1378
|
+
async function atomicJson(path2, value) {
|
|
1379
|
+
const serialized = JSON.stringify(value, null, 2);
|
|
1380
|
+
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
1381
|
+
throw new Error("Pi Agent Swarm worker lineage must not contain secret material");
|
|
1382
|
+
}
|
|
1383
|
+
await atomicText(path2, `${serialized}
|
|
1384
|
+
`);
|
|
1385
|
+
}
|
|
1386
|
+
async function atomicText(path2, content) {
|
|
1387
|
+
await mkdir2(dirname2(path2), { recursive: true, mode: 448 });
|
|
1388
|
+
const temporary = `${path2}.tmp-${process.pid}-${randomBytes2(8).toString("hex")}`;
|
|
1389
|
+
await writeFile2(temporary, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
1390
|
+
try {
|
|
1391
|
+
await rename2(temporary, path2);
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
const { rm: rm7 } = await import("node:fs/promises");
|
|
1394
|
+
await rm7(temporary, { force: true }).catch(() => void 0);
|
|
1395
|
+
throw error;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
function record(value, label) {
|
|
1399
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1400
|
+
throw new Error(`Pi Agent Swarm ${label} must be an object`);
|
|
1401
|
+
return value;
|
|
1402
|
+
}
|
|
1403
|
+
function assertKeys(value, allowed, label) {
|
|
1404
|
+
const unknown = Object.keys(value).find((key) => !allowed.includes(key));
|
|
1405
|
+
if (unknown) throw new Error(`Pi Agent Swarm ${label} has unknown field ${unknown}`);
|
|
1406
|
+
}
|
|
1052
1407
|
|
|
1053
1408
|
// src/external.ts
|
|
1054
1409
|
import { spawn } from "node:child_process";
|
|
1055
1410
|
import { existsSync } from "node:fs";
|
|
1056
|
-
import { join as
|
|
1411
|
+
import { join as join3 } from "node:path";
|
|
1057
1412
|
var ExternalLaunchError = class extends Error {
|
|
1058
1413
|
constructor(message, splitCreated = false, terminalId) {
|
|
1059
1414
|
super(message);
|
|
@@ -1156,7 +1511,7 @@ function isOnPath(binary) {
|
|
|
1156
1511
|
if (binary.includes("/")) return existsSync(binary);
|
|
1157
1512
|
const path2 = process.env.PATH ?? "";
|
|
1158
1513
|
for (const dir of path2.split(":")) {
|
|
1159
|
-
if (dir && existsSync(
|
|
1514
|
+
if (dir && existsSync(join3(dir, binary))) return true;
|
|
1160
1515
|
}
|
|
1161
1516
|
return false;
|
|
1162
1517
|
}
|
|
@@ -1204,7 +1559,8 @@ var SWARM_LAUNCH_ENV_KEYS = [
|
|
|
1204
1559
|
"PI_SWARM_ACCEPT_REQUESTS",
|
|
1205
1560
|
"PI_SWARM_MODEL_PROVIDER",
|
|
1206
1561
|
"PI_SWARM_MODEL_ID",
|
|
1207
|
-
"PI_SWARM_THINKING"
|
|
1562
|
+
"PI_SWARM_THINKING",
|
|
1563
|
+
"PI_SWARM_CONTEXT_RECYCLING"
|
|
1208
1564
|
];
|
|
1209
1565
|
var THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
1210
1566
|
var SAFE_ID2 = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
@@ -1224,6 +1580,7 @@ function consumeLaunchEnvelope(environment = process.env) {
|
|
|
1224
1580
|
const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
|
|
1225
1581
|
const childColor = optionalHexColor(values.PI_SWARM_COLOR);
|
|
1226
1582
|
const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
|
|
1583
|
+
const contextRecycling = parseContextRecycling(values.PI_SWARM_CONTEXT_RECYCLING);
|
|
1227
1584
|
const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
|
|
1228
1585
|
const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
|
|
1229
1586
|
if (provider === void 0 !== (id === void 0)) {
|
|
@@ -1244,6 +1601,7 @@ function consumeLaunchEnvelope(environment = process.env) {
|
|
|
1244
1601
|
...childName ? { childName } : {},
|
|
1245
1602
|
...childColor ? { childColor } : {},
|
|
1246
1603
|
acceptsRequests,
|
|
1604
|
+
...contextRecycling ? { contextRecycling } : {},
|
|
1247
1605
|
...provider && id ? {
|
|
1248
1606
|
model: {
|
|
1249
1607
|
provider,
|
|
@@ -1260,6 +1618,7 @@ function launchEnvelopeEnvironment(envelope) {
|
|
|
1260
1618
|
PI_SWARM_LAUNCH_ID: envelope.launchId,
|
|
1261
1619
|
PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
|
|
1262
1620
|
PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
|
|
1621
|
+
...envelope.contextRecycling ? { PI_SWARM_CONTEXT_RECYCLING: JSON.stringify(envelope.contextRecycling) } : {},
|
|
1263
1622
|
...envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {},
|
|
1264
1623
|
...envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {},
|
|
1265
1624
|
...envelope.model ? {
|
|
@@ -1269,6 +1628,46 @@ function launchEnvelopeEnvironment(envelope) {
|
|
|
1269
1628
|
} : {}
|
|
1270
1629
|
};
|
|
1271
1630
|
}
|
|
1631
|
+
function parseContextRecycling(value) {
|
|
1632
|
+
if (value === void 0) return void 0;
|
|
1633
|
+
const boundedValue = bounded(value, "context recycling policy", 4096);
|
|
1634
|
+
let parsed;
|
|
1635
|
+
try {
|
|
1636
|
+
parsed = JSON.parse(boundedValue);
|
|
1637
|
+
} catch {
|
|
1638
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
1639
|
+
}
|
|
1640
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1641
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
1642
|
+
}
|
|
1643
|
+
const candidate = parsed;
|
|
1644
|
+
const allowed = ["lineageId", "generation", "replacementCount", "policy", "handoffPath"];
|
|
1645
|
+
if (Object.keys(candidate).some((key) => !allowed.includes(key))) {
|
|
1646
|
+
throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
|
|
1647
|
+
}
|
|
1648
|
+
const lineageId = safeId(candidate.lineageId, "lineage id");
|
|
1649
|
+
if (!Number.isInteger(candidate.generation) || candidate.generation < 1) {
|
|
1650
|
+
throw new Error("Pi Agent Swarm launch context recycling generation is invalid");
|
|
1651
|
+
}
|
|
1652
|
+
if (!Number.isInteger(candidate.replacementCount) || candidate.replacementCount < 0) {
|
|
1653
|
+
throw new Error("Pi Agent Swarm launch context recycling replacement count is invalid");
|
|
1654
|
+
}
|
|
1655
|
+
const handoffPath = optionalBounded(candidate.handoffPath, "context handoff path", 4096);
|
|
1656
|
+
if (candidate.generation === 1 !== (handoffPath === void 0)) {
|
|
1657
|
+
throw new Error("Pi Agent Swarm launch context handoff path is inconsistent");
|
|
1658
|
+
}
|
|
1659
|
+
const policy = normalizeContextRecyclingPolicy(candidate.policy);
|
|
1660
|
+
if (candidate.generation !== candidate.replacementCount + 1 || candidate.replacementCount > policy.maxReplacements) {
|
|
1661
|
+
throw new Error("Pi Agent Swarm launch context recycling generation is inconsistent");
|
|
1662
|
+
}
|
|
1663
|
+
return {
|
|
1664
|
+
lineageId,
|
|
1665
|
+
generation: candidate.generation,
|
|
1666
|
+
replacementCount: candidate.replacementCount,
|
|
1667
|
+
policy,
|
|
1668
|
+
...handoffPath ? { handoffPath } : {}
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1272
1671
|
function parseBoolean(value) {
|
|
1273
1672
|
if (value === void 0 || value === "0") return false;
|
|
1274
1673
|
if (value === "1") return true;
|
|
@@ -1295,12 +1694,12 @@ function optionalHexColor(value) {
|
|
|
1295
1694
|
}
|
|
1296
1695
|
|
|
1297
1696
|
// src/launcher.ts
|
|
1298
|
-
import { randomBytes as
|
|
1299
|
-
import { lstat as lstat2, open as
|
|
1300
|
-
import { join as
|
|
1697
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
1698
|
+
import { lstat as lstat2, open as open3, rm as rm3 } from "node:fs/promises";
|
|
1699
|
+
import { join as join4, relative, resolve as resolve2 } from "node:path";
|
|
1301
1700
|
async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
1302
1701
|
await assertPrivateDirectory(directory);
|
|
1303
|
-
const launcherPath =
|
|
1702
|
+
const launcherPath = join4(directory, `launch-${randomBytes3(8).toString("hex")}.sh`);
|
|
1304
1703
|
assertInside(directory, launcherPath);
|
|
1305
1704
|
const command = [invocation.command, ...invocation.args];
|
|
1306
1705
|
for (const value of command) {
|
|
@@ -1312,7 +1711,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
|
1312
1711
|
...environment.map(([key, value]) => `export ${key}=${quoteShell(value)}`)
|
|
1313
1712
|
] : [];
|
|
1314
1713
|
const source = ["#!/bin/sh", ...setup, `exec ${command.map(quoteShell).join(" ")}`, ""].join("\n");
|
|
1315
|
-
const handle = await
|
|
1714
|
+
const handle = await open3(launcherPath, "wx", 448);
|
|
1316
1715
|
try {
|
|
1317
1716
|
await handle.writeFile(source, "utf8");
|
|
1318
1717
|
await handle.sync();
|
|
@@ -1320,7 +1719,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
|
1320
1719
|
await handle.close();
|
|
1321
1720
|
} catch (error) {
|
|
1322
1721
|
await handle.close().catch(() => void 0);
|
|
1323
|
-
await
|
|
1722
|
+
await rm3(launcherPath, { force: true }).catch(() => void 0);
|
|
1324
1723
|
throw error;
|
|
1325
1724
|
}
|
|
1326
1725
|
let cleaned = false;
|
|
@@ -1331,7 +1730,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
|
1331
1730
|
if (cleaned) return;
|
|
1332
1731
|
cleaned = true;
|
|
1333
1732
|
assertInside(directory, launcherPath);
|
|
1334
|
-
await
|
|
1733
|
+
await rm3(launcherPath, { force: true });
|
|
1335
1734
|
}
|
|
1336
1735
|
};
|
|
1337
1736
|
}
|
|
@@ -1363,7 +1762,7 @@ async function assertPrivateDirectory(path2) {
|
|
|
1363
1762
|
}
|
|
1364
1763
|
}
|
|
1365
1764
|
function assertInside(parent, candidate) {
|
|
1366
|
-
const rel = relative(
|
|
1765
|
+
const rel = relative(resolve2(parent), resolve2(candidate));
|
|
1367
1766
|
if (!rel || rel === ".." || rel.startsWith("../")) {
|
|
1368
1767
|
throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
|
|
1369
1768
|
}
|
|
@@ -1436,7 +1835,7 @@ function resolveDeclaredBin(packageDirectory, manifest) {
|
|
|
1436
1835
|
throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
|
|
1437
1836
|
}
|
|
1438
1837
|
const candidate = path.resolve(packageDirectory, piBin);
|
|
1439
|
-
if (path.isAbsolute(piBin) || !
|
|
1838
|
+
if (path.isAbsolute(piBin) || !isWithin2(packageDirectory, candidate)) {
|
|
1440
1839
|
throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
|
|
1441
1840
|
}
|
|
1442
1841
|
return candidate;
|
|
@@ -1445,7 +1844,7 @@ function resolveExistingFile(packageDirectory, candidate, reason) {
|
|
|
1445
1844
|
try {
|
|
1446
1845
|
const resolved = fs.realpathSync(candidate);
|
|
1447
1846
|
if (!fs.statSync(resolved).isFile()) throw new Error("not a file");
|
|
1448
|
-
if (!
|
|
1847
|
+
if (!isWithin2(packageDirectory, resolved)) {
|
|
1449
1848
|
throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
|
|
1450
1849
|
}
|
|
1451
1850
|
return resolved;
|
|
@@ -1474,7 +1873,7 @@ function resolveStandaloneExecutable(packageDirectory, runtime) {
|
|
|
1474
1873
|
}
|
|
1475
1874
|
return resolved;
|
|
1476
1875
|
}
|
|
1477
|
-
function
|
|
1876
|
+
function isWithin2(parent, candidate) {
|
|
1478
1877
|
const relative4 = path.relative(parent, candidate);
|
|
1479
1878
|
return relative4 === "" || !relative4.startsWith(`..${path.sep}`) && relative4 !== ".." && !path.isAbsolute(relative4);
|
|
1480
1879
|
}
|
|
@@ -1676,10 +2075,10 @@ function collectAncestors(pid, readPpid) {
|
|
|
1676
2075
|
}
|
|
1677
2076
|
function readProcPpid(pid) {
|
|
1678
2077
|
try {
|
|
1679
|
-
const
|
|
1680
|
-
const close =
|
|
2078
|
+
const stat4 = readFileSync2(`/proc/${pid}/stat`, "utf8");
|
|
2079
|
+
const close = stat4.lastIndexOf(")");
|
|
1681
2080
|
if (close < 0) return void 0;
|
|
1682
|
-
const fields =
|
|
2081
|
+
const fields = stat4.slice(close + 2).split(" ");
|
|
1683
2082
|
const ppid = Number(fields[1]);
|
|
1684
2083
|
return Number.isInteger(ppid) && ppid > 0 ? ppid : void 0;
|
|
1685
2084
|
} catch {
|
|
@@ -1691,12 +2090,12 @@ function quoteI3Value(value) {
|
|
|
1691
2090
|
}
|
|
1692
2091
|
async function abortableSleep(milliseconds, signal) {
|
|
1693
2092
|
throwIfAborted3(signal, "Pi Agent Swarm i3 workspace wait was aborted");
|
|
1694
|
-
await new Promise((
|
|
2093
|
+
await new Promise((resolve7, reject) => {
|
|
1695
2094
|
const finish = (error) => {
|
|
1696
2095
|
clearTimeout(timer);
|
|
1697
2096
|
signal?.removeEventListener("abort", abort);
|
|
1698
2097
|
if (error) reject(error);
|
|
1699
|
-
else
|
|
2098
|
+
else resolve7();
|
|
1700
2099
|
};
|
|
1701
2100
|
const timer = setTimeout(() => finish(), milliseconds);
|
|
1702
2101
|
const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
|
|
@@ -1734,17 +2133,17 @@ function createTerminalLaunchError(message, splitCreated, terminalId) {
|
|
|
1734
2133
|
}
|
|
1735
2134
|
|
|
1736
2135
|
// src/transport.ts
|
|
1737
|
-
import { randomBytes as
|
|
2136
|
+
import { randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
1738
2137
|
import { constants as constants3 } from "node:fs";
|
|
1739
|
-
import { chmod as chmod2, lstat as lstat4, open as
|
|
2138
|
+
import { chmod as chmod2, lstat as lstat4, open as open6, opendir as opendir2, rm as rm5 } from "node:fs/promises";
|
|
1740
2139
|
import { createServer } from "node:net";
|
|
1741
|
-
import { basename as basename4, dirname as
|
|
2140
|
+
import { basename as basename4, dirname as dirname5, join as join7, resolve as resolve5 } from "node:path";
|
|
1742
2141
|
|
|
1743
2142
|
// src/runtime-directory.ts
|
|
1744
|
-
import { randomBytes as
|
|
1745
|
-
import { chmod, lstat as lstat3, mkdir as
|
|
2143
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
2144
|
+
import { chmod, lstat as lstat3, mkdir as mkdir3, open as open4, opendir, realpath, rename as rename3, rm as rm4, stat as stat2 } from "node:fs/promises";
|
|
1746
2145
|
import { tmpdir } from "node:os";
|
|
1747
|
-
import { basename as basename3, dirname as
|
|
2146
|
+
import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative3, resolve as resolve4 } from "node:path";
|
|
1748
2147
|
var MAX_UNIX_SOCKET_PATH_BYTES = 103;
|
|
1749
2148
|
var MAX_MANIFEST_BYTES = 8 * 1024;
|
|
1750
2149
|
var ORPHAN_GRACE_MS = 6e4;
|
|
@@ -1760,21 +2159,21 @@ function defaultRuntimeBaseDirectory() {
|
|
|
1760
2159
|
throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
|
|
1761
2160
|
}
|
|
1762
2161
|
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
1763
|
-
if (process.platform === "darwin") return
|
|
2162
|
+
if (process.platform === "darwin") return join6("/tmp", `pi-swarm-${uid}`);
|
|
1764
2163
|
const runtime = process.env.XDG_RUNTIME_DIR;
|
|
1765
|
-
if (runtime && isAbsolute2(runtime) && Buffer.byteLength(
|
|
1766
|
-
return
|
|
2164
|
+
if (runtime && isAbsolute2(runtime) && Buffer.byteLength(join6(runtime, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
2165
|
+
return join6(runtime, "pi-swarm");
|
|
1767
2166
|
}
|
|
1768
|
-
const systemTmp =
|
|
1769
|
-
const candidate =
|
|
1770
|
-
const socketCandidate =
|
|
1771
|
-
return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate :
|
|
2167
|
+
const systemTmp = resolve4(tmpdir());
|
|
2168
|
+
const candidate = join6(systemTmp, `pi-swarm-${uid}`);
|
|
2169
|
+
const socketCandidate = join6(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
|
|
2170
|
+
return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join6("/tmp", `pi-swarm-${uid}`);
|
|
1772
2171
|
}
|
|
1773
2172
|
async function ensureGroupRuntimeDirectory(groupId, options = {}) {
|
|
1774
2173
|
if (!SAFE_GROUP_ID.test(groupId)) throw new Error("Pi Agent Swarm runtime group id is invalid");
|
|
1775
|
-
const baseDirectory =
|
|
1776
|
-
const directory =
|
|
1777
|
-
const longestSocket =
|
|
2174
|
+
const baseDirectory = resolve4(options.baseDirectory ?? defaultRuntimeBaseDirectory());
|
|
2175
|
+
const directory = join6(baseDirectory, groupId);
|
|
2176
|
+
const longestSocket = join6(directory, `${"x".repeat(24)}.sock`);
|
|
1778
2177
|
if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
1779
2178
|
throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
|
|
1780
2179
|
}
|
|
@@ -1784,7 +2183,7 @@ async function ensureGroupRuntimeDirectory(groupId, options = {}) {
|
|
|
1784
2183
|
}
|
|
1785
2184
|
function createEndpointPaths(directory, endpointId) {
|
|
1786
2185
|
if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
|
|
1787
|
-
const socketPath =
|
|
2186
|
+
const socketPath = join6(directory, `${endpointId}.sock`);
|
|
1788
2187
|
if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
1789
2188
|
throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
|
|
1790
2189
|
}
|
|
@@ -1792,14 +2191,14 @@ function createEndpointPaths(directory, endpointId) {
|
|
|
1792
2191
|
directory,
|
|
1793
2192
|
endpointId,
|
|
1794
2193
|
socketPath,
|
|
1795
|
-
manifestPath:
|
|
2194
|
+
manifestPath: join6(directory, `${endpointId}.json`)
|
|
1796
2195
|
};
|
|
1797
2196
|
}
|
|
1798
2197
|
function randomEndpointId() {
|
|
1799
|
-
return
|
|
2198
|
+
return randomBytes4(12).toString("hex");
|
|
1800
2199
|
}
|
|
1801
2200
|
async function publishManifest(manifestPath, manifest) {
|
|
1802
|
-
const parent =
|
|
2201
|
+
const parent = dirname4(manifestPath);
|
|
1803
2202
|
await assertPrivateDirectory2(parent);
|
|
1804
2203
|
assertOwnedPath(parent, manifestPath, ".json");
|
|
1805
2204
|
const body = `${JSON.stringify(manifest)}
|
|
@@ -1807,19 +2206,19 @@ async function publishManifest(manifestPath, manifest) {
|
|
|
1807
2206
|
if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
|
|
1808
2207
|
throw new Error("Pi Agent Swarm endpoint manifest is too large");
|
|
1809
2208
|
}
|
|
1810
|
-
const temporaryPath =
|
|
2209
|
+
const temporaryPath = join6(parent, `.${basename3(manifestPath)}.${randomBytes4(8).toString("hex")}.tmp`);
|
|
1811
2210
|
let handle;
|
|
1812
2211
|
try {
|
|
1813
|
-
handle = await
|
|
2212
|
+
handle = await open4(temporaryPath, "wx", 384);
|
|
1814
2213
|
await handle.writeFile(body, "utf8");
|
|
1815
2214
|
await handle.sync();
|
|
1816
2215
|
await handle.close();
|
|
1817
2216
|
handle = void 0;
|
|
1818
|
-
await
|
|
2217
|
+
await rename3(temporaryPath, manifestPath);
|
|
1819
2218
|
await chmod(manifestPath, 384);
|
|
1820
2219
|
} finally {
|
|
1821
2220
|
await handle?.close().catch(() => void 0);
|
|
1822
|
-
await
|
|
2221
|
+
await rm4(temporaryPath, { force: true }).catch(() => void 0);
|
|
1823
2222
|
}
|
|
1824
2223
|
}
|
|
1825
2224
|
async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
@@ -1845,7 +2244,7 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
|
1845
2244
|
for (const name of names) {
|
|
1846
2245
|
const socketMatch = SAFE_SOCKET_NAME.exec(name);
|
|
1847
2246
|
if (socketMatch) {
|
|
1848
|
-
const manifestPath =
|
|
2247
|
+
const manifestPath = join6(directory, `${socketMatch[1]}.json`);
|
|
1849
2248
|
if (!await pathExists(manifestPath)) {
|
|
1850
2249
|
if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
|
|
1851
2250
|
}
|
|
@@ -1862,15 +2261,15 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
|
1862
2261
|
async function removeOwnedEndpoint(paths) {
|
|
1863
2262
|
for (const path2 of [paths.manifestPath, paths.socketPath]) {
|
|
1864
2263
|
assertOwnedPath(paths.directory, path2);
|
|
1865
|
-
await
|
|
2264
|
+
await rm4(path2, { force: true }).catch(() => void 0);
|
|
1866
2265
|
}
|
|
1867
2266
|
}
|
|
1868
2267
|
function endpointIdFromManifestName(name) {
|
|
1869
2268
|
return SAFE_MANIFEST_NAME.exec(name)?.[1];
|
|
1870
2269
|
}
|
|
1871
2270
|
function assertOwnedPath(parent, candidate, suffix) {
|
|
1872
|
-
const resolvedParent =
|
|
1873
|
-
const resolvedCandidate =
|
|
2271
|
+
const resolvedParent = resolve4(parent);
|
|
2272
|
+
const resolvedCandidate = resolve4(candidate);
|
|
1874
2273
|
const rel = relative3(resolvedParent, resolvedCandidate);
|
|
1875
2274
|
if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
|
|
1876
2275
|
throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
|
|
@@ -1880,7 +2279,7 @@ function assertOwnedPath(parent, candidate, suffix) {
|
|
|
1880
2279
|
}
|
|
1881
2280
|
}
|
|
1882
2281
|
async function removeStaleOwnedEntry(directory, name, kind, now) {
|
|
1883
|
-
const path2 =
|
|
2282
|
+
const path2 = join6(directory, name);
|
|
1884
2283
|
assertOwnedPath(directory, path2);
|
|
1885
2284
|
try {
|
|
1886
2285
|
const first = await lstat3(path2, { bigint: true });
|
|
@@ -1891,7 +2290,7 @@ async function removeStaleOwnedEntry(directory, name, kind, now) {
|
|
|
1891
2290
|
if (current.dev !== first.dev || current.ino !== first.ino || current.mtimeMs !== first.mtimeMs || (kind === "file" ? !current.isFile() : !current.isSocket())) {
|
|
1892
2291
|
return false;
|
|
1893
2292
|
}
|
|
1894
|
-
await
|
|
2293
|
+
await rm4(path2);
|
|
1895
2294
|
return true;
|
|
1896
2295
|
} catch (error) {
|
|
1897
2296
|
if (isMissing(error)) return false;
|
|
@@ -1908,7 +2307,7 @@ async function ensurePrivateDirectory(path2) {
|
|
|
1908
2307
|
await assertPrivateDirectory2(path2);
|
|
1909
2308
|
} catch (error) {
|
|
1910
2309
|
if (!isMissing(error)) throw error;
|
|
1911
|
-
await
|
|
2310
|
+
await mkdir3(path2, { recursive: true, mode: 448 });
|
|
1912
2311
|
await chmod(path2, 448);
|
|
1913
2312
|
await assertPrivateDirectory2(path2);
|
|
1914
2313
|
}
|
|
@@ -1922,7 +2321,7 @@ async function assertPrivateDirectory2(path2) {
|
|
|
1922
2321
|
throw new Error("Pi Agent Swarm runtime directory permissions are not private");
|
|
1923
2322
|
}
|
|
1924
2323
|
const resolved = await realpath(path2);
|
|
1925
|
-
const resolvedInfo = await
|
|
2324
|
+
const resolvedInfo = await stat2(resolved);
|
|
1926
2325
|
assertOwner(resolvedInfo.uid);
|
|
1927
2326
|
}
|
|
1928
2327
|
function assertOwner(uid) {
|
|
@@ -1944,7 +2343,7 @@ function isMissing(error) {
|
|
|
1944
2343
|
|
|
1945
2344
|
// src/transport-io.ts
|
|
1946
2345
|
import { constants as constants2 } from "node:fs";
|
|
1947
|
-
import { open as
|
|
2346
|
+
import { open as open5 } from "node:fs/promises";
|
|
1948
2347
|
import { createConnection } from "node:net";
|
|
1949
2348
|
import { TextDecoder as TextDecoder3 } from "node:util";
|
|
1950
2349
|
function requestFrame(endpointPath, frame, signal, timeoutMs) {
|
|
@@ -2039,7 +2438,7 @@ function closeSocketServer(server) {
|
|
|
2039
2438
|
});
|
|
2040
2439
|
}
|
|
2041
2440
|
async function readBoundedUtf8(path2, maximum) {
|
|
2042
|
-
const handle = await
|
|
2441
|
+
const handle = await open5(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
2043
2442
|
try {
|
|
2044
2443
|
return await readBoundedHandleUtf8(handle, maximum);
|
|
2045
2444
|
} finally {
|
|
@@ -2194,11 +2593,11 @@ var SwarmTransport = class {
|
|
|
2194
2593
|
while (cursor < manifestResult.records.length && !operationSignal.aborted) {
|
|
2195
2594
|
const index = cursor;
|
|
2196
2595
|
cursor += 1;
|
|
2197
|
-
const
|
|
2198
|
-
if (!
|
|
2596
|
+
const record2 = manifestResult.records[index];
|
|
2597
|
+
if (!record2 || record2.manifest.endpointId === this.peer.endpointId) continue;
|
|
2199
2598
|
try {
|
|
2200
2599
|
const response = await this.request(
|
|
2201
|
-
|
|
2600
|
+
record2,
|
|
2202
2601
|
{ kind: "describe" },
|
|
2203
2602
|
operationSignal,
|
|
2204
2603
|
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
|
|
@@ -2206,7 +2605,7 @@ var SwarmTransport = class {
|
|
|
2206
2605
|
if (response.payload.kind !== "description") {
|
|
2207
2606
|
throw new Error("Pi Agent Swarm peer returned an invalid description response");
|
|
2208
2607
|
}
|
|
2209
|
-
assertDescriptionMatchesManifest(response.payload.peer,
|
|
2608
|
+
assertDescriptionMatchesManifest(response.payload.peer, record2);
|
|
2210
2609
|
if (response.payload.peer.sessionId === this.peer.sessionId) {
|
|
2211
2610
|
addIssue(issues, {
|
|
2212
2611
|
code: "identity_conflict",
|
|
@@ -2215,22 +2614,22 @@ var SwarmTransport = class {
|
|
|
2215
2614
|
});
|
|
2216
2615
|
continue;
|
|
2217
2616
|
}
|
|
2218
|
-
discovered.push({ peer: response.payload.peer, record });
|
|
2617
|
+
discovered.push({ peer: response.payload.peer, record: record2 });
|
|
2219
2618
|
} catch (error) {
|
|
2220
2619
|
if (signal?.aborted || this.lifecycle.signal.aborted) throw error;
|
|
2221
2620
|
if (deadline.signal.aborted) break;
|
|
2222
2621
|
if (isDeadEndpointError(error)) {
|
|
2223
2622
|
addIssue(issues, {
|
|
2224
2623
|
code: "peer_unreachable",
|
|
2225
|
-
sessionId:
|
|
2226
|
-
endpointId:
|
|
2624
|
+
sessionId: record2.manifest.sessionId,
|
|
2625
|
+
endpointId: record2.manifest.endpointId
|
|
2227
2626
|
});
|
|
2228
|
-
await this.removeStaleRecord(
|
|
2627
|
+
await this.removeStaleRecord(record2);
|
|
2229
2628
|
} else if (!isAbortError(error)) {
|
|
2230
2629
|
addIssue(issues, {
|
|
2231
2630
|
code: "protocol_error",
|
|
2232
|
-
sessionId:
|
|
2233
|
-
endpointId:
|
|
2631
|
+
sessionId: record2.manifest.sessionId,
|
|
2632
|
+
endpointId: record2.manifest.endpointId
|
|
2234
2633
|
});
|
|
2235
2634
|
}
|
|
2236
2635
|
}
|
|
@@ -2301,12 +2700,12 @@ var SwarmTransport = class {
|
|
|
2301
2700
|
if (candidates.length === 0) {
|
|
2302
2701
|
throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
|
|
2303
2702
|
}
|
|
2304
|
-
const
|
|
2305
|
-
if (!
|
|
2703
|
+
const record2 = candidates.length === 1 ? candidates[0] : await this.resolveUniqueTarget(targetSessionId, candidates, signal);
|
|
2704
|
+
if (!record2) throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
|
|
2306
2705
|
let response;
|
|
2307
2706
|
try {
|
|
2308
2707
|
response = await this.request(
|
|
2309
|
-
|
|
2708
|
+
record2,
|
|
2310
2709
|
{
|
|
2311
2710
|
kind: "message",
|
|
2312
2711
|
message,
|
|
@@ -2315,7 +2714,7 @@ var SwarmTransport = class {
|
|
|
2315
2714
|
signal
|
|
2316
2715
|
);
|
|
2317
2716
|
} catch (error) {
|
|
2318
|
-
if (isDeadEndpointError(error)) await this.removeStaleRecord(
|
|
2717
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record2);
|
|
2319
2718
|
throw error;
|
|
2320
2719
|
}
|
|
2321
2720
|
if (response.payload.kind !== "ack") {
|
|
@@ -2489,6 +2888,14 @@ var SwarmTransport = class {
|
|
|
2489
2888
|
}
|
|
2490
2889
|
}
|
|
2491
2890
|
messagePolicyError(message, kickoffCapability) {
|
|
2891
|
+
if (message.kind === "handoff" && !(this.options.authorizeHandoff?.(message) ?? false)) {
|
|
2892
|
+
return {
|
|
2893
|
+
kind: "ack",
|
|
2894
|
+
status: "rejected",
|
|
2895
|
+
code: "context_handoff",
|
|
2896
|
+
error: "Target session is not the authorized handoff leader"
|
|
2897
|
+
};
|
|
2898
|
+
}
|
|
2492
2899
|
if (message.kind === "shutdown" && !(this.options.authorizeShutdown?.(message) ?? false)) {
|
|
2493
2900
|
return {
|
|
2494
2901
|
kind: "ack",
|
|
@@ -2498,6 +2905,8 @@ var SwarmTransport = class {
|
|
|
2498
2905
|
};
|
|
2499
2906
|
}
|
|
2500
2907
|
if (message.mode === "request" && !this.peer.acceptsRequests) {
|
|
2908
|
+
const lifecycleRejection = this.options.rejectRequest?.(message);
|
|
2909
|
+
if (lifecycleRejection) return lifecycleRejection;
|
|
2501
2910
|
return {
|
|
2502
2911
|
kind: "ack",
|
|
2503
2912
|
status: "rejected",
|
|
@@ -2574,7 +2983,7 @@ var SwarmTransport = class {
|
|
|
2574
2983
|
}
|
|
2575
2984
|
try {
|
|
2576
2985
|
records.push(
|
|
2577
|
-
await readManifest2(paths.directory,
|
|
2986
|
+
await readManifest2(paths.directory, resolve5(paths.directory, entry.name), endpointId, this.options.group)
|
|
2578
2987
|
);
|
|
2579
2988
|
} catch {
|
|
2580
2989
|
addIssue(issues, { code: "invalid_manifest", endpointId });
|
|
@@ -2587,15 +2996,15 @@ var SwarmTransport = class {
|
|
|
2587
2996
|
records.sort((left, right) => left.manifest.endpointId.localeCompare(right.manifest.endpointId));
|
|
2588
2997
|
return { records, issues, scannedEntries, saturated };
|
|
2589
2998
|
}
|
|
2590
|
-
async request(
|
|
2999
|
+
async request(record2, payload, signal, timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) {
|
|
2591
3000
|
throwIfAborted4(signal, "Pi Agent Swarm request aborted");
|
|
2592
3001
|
const requestId = randomId("req");
|
|
2593
3002
|
const frame = createSignedFrame(
|
|
2594
3003
|
{
|
|
2595
3004
|
groupId: this.options.group.id,
|
|
2596
3005
|
requestId,
|
|
2597
|
-
targetSessionId:
|
|
2598
|
-
targetEndpointId:
|
|
3006
|
+
targetSessionId: record2.manifest.sessionId,
|
|
3007
|
+
targetEndpointId: record2.manifest.endpointId,
|
|
2599
3008
|
senderSessionId: this.peer.sessionId,
|
|
2600
3009
|
senderEndpointId: this.peer.endpointId,
|
|
2601
3010
|
issuedAt: this.now(),
|
|
@@ -2604,7 +3013,7 @@ var SwarmTransport = class {
|
|
|
2604
3013
|
},
|
|
2605
3014
|
this.options.group.secret
|
|
2606
3015
|
);
|
|
2607
|
-
const value = await requestFrame(
|
|
3016
|
+
const value = await requestFrame(record2.socketPath, frame, signal, timeoutMs);
|
|
2608
3017
|
throwIfAborted4(signal, "Pi Agent Swarm request aborted");
|
|
2609
3018
|
const response = verifySignedFrame(value, this.options.group.secret, {
|
|
2610
3019
|
expectedGroupId: this.options.group.id,
|
|
@@ -2613,7 +3022,7 @@ var SwarmTransport = class {
|
|
|
2613
3022
|
now: this.now(),
|
|
2614
3023
|
replay: this.responseReplay
|
|
2615
3024
|
});
|
|
2616
|
-
if (response.requestId !== requestId || response.senderSessionId !==
|
|
3025
|
+
if (response.requestId !== requestId || response.senderSessionId !== record2.manifest.sessionId || response.senderEndpointId !== record2.manifest.endpointId) {
|
|
2617
3026
|
throw new Error("Pi Agent Swarm response identity does not match its request");
|
|
2618
3027
|
}
|
|
2619
3028
|
return response;
|
|
@@ -2621,20 +3030,20 @@ var SwarmTransport = class {
|
|
|
2621
3030
|
async resolveUniqueTarget(targetSessionId, candidates, signal) {
|
|
2622
3031
|
const live = [];
|
|
2623
3032
|
await Promise.all(
|
|
2624
|
-
candidates.map(async (
|
|
3033
|
+
candidates.map(async (record2) => {
|
|
2625
3034
|
try {
|
|
2626
3035
|
const response = await this.request(
|
|
2627
|
-
|
|
3036
|
+
record2,
|
|
2628
3037
|
{ kind: "describe" },
|
|
2629
3038
|
signal,
|
|
2630
3039
|
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
|
|
2631
3040
|
);
|
|
2632
3041
|
if (response.payload.kind !== "description") return;
|
|
2633
|
-
assertDescriptionMatchesManifest(response.payload.peer,
|
|
2634
|
-
live.push(
|
|
3042
|
+
assertDescriptionMatchesManifest(response.payload.peer, record2);
|
|
3043
|
+
live.push(record2);
|
|
2635
3044
|
} catch (error) {
|
|
2636
3045
|
if (isAbortError(error)) throw error;
|
|
2637
|
-
if (isDeadEndpointError(error)) await this.removeStaleRecord(
|
|
3046
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record2);
|
|
2638
3047
|
}
|
|
2639
3048
|
})
|
|
2640
3049
|
);
|
|
@@ -2643,15 +3052,15 @@ var SwarmTransport = class {
|
|
|
2643
3052
|
}
|
|
2644
3053
|
return live[0];
|
|
2645
3054
|
}
|
|
2646
|
-
async removeStaleRecord(
|
|
3055
|
+
async removeStaleRecord(record2) {
|
|
2647
3056
|
try {
|
|
2648
|
-
const current = await readBoundedUtf8(
|
|
2649
|
-
if (current !==
|
|
2650
|
-
await
|
|
2651
|
-
if (
|
|
2652
|
-
const info = await lstat4(
|
|
2653
|
-
if (info?.isSocket() && info.dev ===
|
|
2654
|
-
await
|
|
3057
|
+
const current = await readBoundedUtf8(record2.manifestPath, MAX_MANIFEST_BYTES);
|
|
3058
|
+
if (current !== record2.raw) return;
|
|
3059
|
+
await rm5(record2.manifestPath, { force: true });
|
|
3060
|
+
if (record2.socketIdentity) {
|
|
3061
|
+
const info = await lstat4(record2.socketPath, { bigint: true }).catch(() => void 0);
|
|
3062
|
+
if (info?.isSocket() && info.dev === record2.socketIdentity.dev && info.ino === record2.socketIdentity.ino) {
|
|
3063
|
+
await rm5(record2.socketPath, { force: true });
|
|
2655
3064
|
}
|
|
2656
3065
|
}
|
|
2657
3066
|
} catch {
|
|
@@ -2694,7 +3103,7 @@ async function assertEndpointPathsAvailable(paths) {
|
|
|
2694
3103
|
}
|
|
2695
3104
|
async function readManifest2(directory, manifestPath, endpointId, group) {
|
|
2696
3105
|
assertOwnedPath(directory, manifestPath, ".json");
|
|
2697
|
-
const handle = await
|
|
3106
|
+
const handle = await open6(manifestPath, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
2698
3107
|
try {
|
|
2699
3108
|
const info = await handle.stat({ bigint: true });
|
|
2700
3109
|
if (!info.isFile() || info.size > BigInt(MAX_MANIFEST_BYTES)) {
|
|
@@ -2711,8 +3120,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
|
|
|
2711
3120
|
expectedGroupId: group.id,
|
|
2712
3121
|
expectedEndpointId: endpointId
|
|
2713
3122
|
});
|
|
2714
|
-
const socketPath =
|
|
2715
|
-
if (
|
|
3123
|
+
const socketPath = join7(directory, manifest.socketName);
|
|
3124
|
+
if (dirname5(resolve5(socketPath)) !== resolve5(directory)) {
|
|
2716
3125
|
throw new Error("Pi Agent Swarm endpoint socket path is invalid");
|
|
2717
3126
|
}
|
|
2718
3127
|
const socketInfo = await lstat4(socketPath, { bigint: true }).catch(() => void 0);
|
|
@@ -2736,8 +3145,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
|
|
|
2736
3145
|
await handle.close();
|
|
2737
3146
|
}
|
|
2738
3147
|
}
|
|
2739
|
-
function assertDescriptionMatchesManifest(peer,
|
|
2740
|
-
if (peer.sessionId !==
|
|
3148
|
+
function assertDescriptionMatchesManifest(peer, record2) {
|
|
3149
|
+
if (peer.sessionId !== record2.manifest.sessionId || peer.endpointId !== record2.manifest.endpointId || peer.pid !== record2.manifest.pid) {
|
|
2741
3150
|
throw new Error("Pi Agent Swarm peer identity does not match its endpoint manifest");
|
|
2742
3151
|
}
|
|
2743
3152
|
}
|
|
@@ -2760,7 +3169,7 @@ function addIssue(issues, issue) {
|
|
|
2760
3169
|
issues.push(issue);
|
|
2761
3170
|
}
|
|
2762
3171
|
function randomId(prefix) {
|
|
2763
|
-
return `${prefix}_${
|
|
3172
|
+
return `${prefix}_${randomBytes5(12).toString("hex")}`;
|
|
2764
3173
|
}
|
|
2765
3174
|
function combineSignals(...signals) {
|
|
2766
3175
|
const concrete = signals.filter((signal) => signal !== void 0);
|
|
@@ -2824,9 +3233,9 @@ function defaultSwarmControllerDependencies(pi) {
|
|
|
2824
3233
|
resolveInvocation: (args) => resolvePiInvocation(args),
|
|
2825
3234
|
createLauncher: (invocation, directory, embeddedEnvironment) => createPiLauncher(invocation, directory, embeddedEnvironment),
|
|
2826
3235
|
realpath: realpath2,
|
|
2827
|
-
isDirectory: async (value) => (await
|
|
3236
|
+
isDirectory: async (value) => (await stat3(value)).isDirectory(),
|
|
2828
3237
|
now: Date.now,
|
|
2829
|
-
randomId: (prefix) => `${prefix}_${
|
|
3238
|
+
randomId: (prefix) => `${prefix}_${randomBytes6(16).toString("hex")}`,
|
|
2830
3239
|
sleep: abortableSleep2,
|
|
2831
3240
|
launchTimeoutMs: DEFAULT_LAUNCH_TIMEOUT_MS,
|
|
2832
3241
|
environment: process.env,
|
|
@@ -2865,6 +3274,9 @@ var SwarmController = class {
|
|
|
2865
3274
|
resizeWatching = false;
|
|
2866
3275
|
pendingKickoffIds = /* @__PURE__ */ new Set();
|
|
2867
3276
|
relayChain = Promise.resolve();
|
|
3277
|
+
recycling;
|
|
3278
|
+
recyclingChain = Promise.resolve();
|
|
3279
|
+
successorLaunches = /* @__PURE__ */ new Map();
|
|
2868
3280
|
async sessionStart(event, ctx) {
|
|
2869
3281
|
if (this.activeSessionManager && this.activeSessionManager !== ctx.sessionManager) {
|
|
2870
3282
|
await this.cleanupActive(false);
|
|
@@ -2883,6 +3295,9 @@ var SwarmController = class {
|
|
|
2883
3295
|
this.autoNameInFlight = false;
|
|
2884
3296
|
this.pendingKickoffIds.clear();
|
|
2885
3297
|
this.relayChain = Promise.resolve();
|
|
3298
|
+
this.recycling = void 0;
|
|
3299
|
+
this.recyclingChain = Promise.resolve();
|
|
3300
|
+
this.successorLaunches.clear();
|
|
2886
3301
|
this.startLeadWatcher();
|
|
2887
3302
|
this.startResizeWatcher();
|
|
2888
3303
|
const owner = ctx.sessionManager;
|
|
@@ -2942,6 +3357,10 @@ var SwarmController = class {
|
|
|
2942
3357
|
handoff?.kickoffConsumed ?? false
|
|
2943
3358
|
)
|
|
2944
3359
|
);
|
|
3360
|
+
const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
|
|
3361
|
+
if (recyclingLaunch && this.parentSessionId) {
|
|
3362
|
+
await this.initializeContextRecycling(ctx, recyclingLaunch, this.parentSessionId);
|
|
3363
|
+
}
|
|
2945
3364
|
} catch (error) {
|
|
2946
3365
|
if (this.isCurrent(owner, ownerGeneration)) {
|
|
2947
3366
|
this.notify(ctx, `Pi Agent Swarm could not join the launch group: ${safeError(error)}`, "error");
|
|
@@ -2974,6 +3393,7 @@ var SwarmController = class {
|
|
|
2974
3393
|
...peerName ? { name: peerName } : {},
|
|
2975
3394
|
...peerColor ? { color: peerColor } : {},
|
|
2976
3395
|
...this.parentSessionId ? { parentSessionId: this.parentSessionId } : {},
|
|
3396
|
+
...this.recycling ? { contextRecycling: this.recycling.launch } : {},
|
|
2977
3397
|
expiresAt: this.deps.now() + RELOAD_HANDOFF_TTL_MS
|
|
2978
3398
|
});
|
|
2979
3399
|
}
|
|
@@ -3010,6 +3430,10 @@ var SwarmController = class {
|
|
|
3010
3430
|
} catch {
|
|
3011
3431
|
}
|
|
3012
3432
|
}
|
|
3433
|
+
void this.track(this.recoverProjectHandoffs(ctx)).catch((error) => {
|
|
3434
|
+
if (this.isCurrent(ctx))
|
|
3435
|
+
this.notify(ctx, `Pi Agent Swarm handoff recovery failed: ${safeError(error)}`, "warning");
|
|
3436
|
+
});
|
|
3013
3437
|
return this.snapshot(signal);
|
|
3014
3438
|
});
|
|
3015
3439
|
}
|
|
@@ -3041,9 +3465,235 @@ var SwarmController = class {
|
|
|
3041
3465
|
setAcceptsRequests(ctx, value) {
|
|
3042
3466
|
this.assertCurrentContext(ctx);
|
|
3043
3467
|
if (!this.membership) throw new Error("Pi Agent Swarm is not connected");
|
|
3468
|
+
if (this.recycling?.state === "retired") {
|
|
3469
|
+
throw new Error("Pi Agent Swarm retired workers cannot accept new requests");
|
|
3470
|
+
}
|
|
3044
3471
|
this.membership.rollbackLaunch = void 0;
|
|
3045
3472
|
this.membership.acceptsRequests = value;
|
|
3046
3473
|
this.membership.transport.setAcceptsRequests(value);
|
|
3474
|
+
if (value && this.recycling && ["handoff_pending", "handoff_ready", "failed"].includes(this.recycling.state)) {
|
|
3475
|
+
const recycling = this.recycling;
|
|
3476
|
+
const previousState = recycling.state;
|
|
3477
|
+
recycling.state = "working";
|
|
3478
|
+
recycling.handoffAttempts = 0;
|
|
3479
|
+
void updateWorkerLineage(
|
|
3480
|
+
recycling.projectRoot,
|
|
3481
|
+
recycling.launch.lineageId,
|
|
3482
|
+
{ state: "working" },
|
|
3483
|
+
{ generation: recycling.launch.generation, state: previousState }
|
|
3484
|
+
).catch((error) => {
|
|
3485
|
+
if (this.recycling === recycling)
|
|
3486
|
+
this.notify(ctx, `Pi Agent Swarm could not resume its lineage: ${safeError(error)}`, "error");
|
|
3487
|
+
});
|
|
3488
|
+
}
|
|
3489
|
+
}
|
|
3490
|
+
async initializeContextRecycling(ctx, launch, leaderSessionId) {
|
|
3491
|
+
const model = ctx.model;
|
|
3492
|
+
const specification = {
|
|
3493
|
+
cwd: ctx.cwd,
|
|
3494
|
+
...this.pi.getSessionName() ? { name: this.pi.getSessionName() } : {},
|
|
3495
|
+
...this.color ? { color: this.color } : {},
|
|
3496
|
+
...model ? { model: `${model.provider}/${model.id}` } : {},
|
|
3497
|
+
allowRequests: this.membership?.acceptsRequests ?? false
|
|
3498
|
+
};
|
|
3499
|
+
await verifyWorkerHandoffReadable(ctx.cwd, launch);
|
|
3500
|
+
const lineage = await initializeWorkerLineage({
|
|
3501
|
+
projectRoot: ctx.cwd,
|
|
3502
|
+
launch,
|
|
3503
|
+
leaderSessionId,
|
|
3504
|
+
workerSessionId: ctx.sessionManager.getSessionId(),
|
|
3505
|
+
specification
|
|
3506
|
+
});
|
|
3507
|
+
if (!this.isCurrent(ctx)) return;
|
|
3508
|
+
const staleGeneration = lineage.currentGeneration !== launch.generation;
|
|
3509
|
+
this.recycling = {
|
|
3510
|
+
launch,
|
|
3511
|
+
projectRoot: ctx.cwd,
|
|
3512
|
+
leaderSessionId,
|
|
3513
|
+
specification,
|
|
3514
|
+
state: staleGeneration ? "retired" : lineage.state,
|
|
3515
|
+
handoffAttempts: 0
|
|
3516
|
+
};
|
|
3517
|
+
if (staleGeneration || ["handoff_pending", "handoff_ready", "replacing", "failed"].includes(lineage.state)) {
|
|
3518
|
+
this.freezeForHandoff();
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
async agentSettled(ctx) {
|
|
3522
|
+
if (!this.isCurrent(ctx) || !this.recycling) return;
|
|
3523
|
+
const run = this.recyclingChain.then(() => this.agentSettledOwned(ctx));
|
|
3524
|
+
this.recyclingChain = run.catch(() => void 0);
|
|
3525
|
+
await run.catch((error) => {
|
|
3526
|
+
if (this.isCurrent(ctx))
|
|
3527
|
+
this.notify(ctx, `Pi Agent Swarm context recycling failed: ${safeError(error)}`, "error");
|
|
3528
|
+
});
|
|
3529
|
+
}
|
|
3530
|
+
async agentSettledOwned(ctx) {
|
|
3531
|
+
const recycling = this.recycling;
|
|
3532
|
+
if (!recycling || !this.isCurrent(ctx)) return;
|
|
3533
|
+
if (recycling.state === "completed" || recycling.state === "retired" || recycling.state === "replacing") return;
|
|
3534
|
+
const usage = ctx.getContextUsage();
|
|
3535
|
+
if (usage) {
|
|
3536
|
+
await updateWorkerLineage(
|
|
3537
|
+
recycling.projectRoot,
|
|
3538
|
+
recycling.launch.lineageId,
|
|
3539
|
+
{ contextUsage: { ...usage, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
|
|
3540
|
+
{ generation: recycling.launch.generation, state: recycling.state }
|
|
3541
|
+
);
|
|
3542
|
+
if (this.recycling !== recycling || !this.isCurrent(ctx)) return;
|
|
3543
|
+
}
|
|
3544
|
+
if (recycling.state === "handoff_ready" || recycling.state === "failed") return;
|
|
3545
|
+
if (recycling.state === "handoff_pending") {
|
|
3546
|
+
if (recycling.handoff) {
|
|
3547
|
+
await this.publishHandoff(ctx, recycling.handoff);
|
|
3548
|
+
} else {
|
|
3549
|
+
await this.requestHandoffTurn(ctx, recycling);
|
|
3550
|
+
}
|
|
3551
|
+
return;
|
|
3552
|
+
}
|
|
3553
|
+
const decision = contextHandoffDecision(
|
|
3554
|
+
usage?.percent,
|
|
3555
|
+
recycling.taskStatus,
|
|
3556
|
+
recycling.launch.policy.maxContextPercent
|
|
3557
|
+
);
|
|
3558
|
+
if (decision === "continue") return;
|
|
3559
|
+
if (decision === "complete") {
|
|
3560
|
+
recycling.state = "completed";
|
|
3561
|
+
await updateWorkerLineage(
|
|
3562
|
+
recycling.projectRoot,
|
|
3563
|
+
recycling.launch.lineageId,
|
|
3564
|
+
{ state: "completed" },
|
|
3565
|
+
{ generation: recycling.launch.generation, state: "working" }
|
|
3566
|
+
);
|
|
3567
|
+
return;
|
|
3568
|
+
}
|
|
3569
|
+
if (recycling.launch.replacementCount >= recycling.launch.policy.maxReplacements) {
|
|
3570
|
+
recycling.state = "failed";
|
|
3571
|
+
this.freezeForHandoff();
|
|
3572
|
+
await updateWorkerLineage(
|
|
3573
|
+
recycling.projectRoot,
|
|
3574
|
+
recycling.launch.lineageId,
|
|
3575
|
+
{ state: "failed" },
|
|
3576
|
+
{ generation: recycling.launch.generation, state: "working" }
|
|
3577
|
+
);
|
|
3578
|
+
const text = `Context recycling paused for lineage ${recycling.launch.lineageId}: replacement budget ${recycling.launch.policy.maxReplacements} is exhausted.`;
|
|
3579
|
+
this.notify(ctx, text, "warning");
|
|
3580
|
+
await this.send(ctx, { targetSessionId: recycling.leaderSessionId, text, mode: "notify" });
|
|
3581
|
+
return;
|
|
3582
|
+
}
|
|
3583
|
+
recycling.state = "handoff_pending";
|
|
3584
|
+
recycling.handoffAttempts = 0;
|
|
3585
|
+
this.freezeForHandoff();
|
|
3586
|
+
await updateWorkerLineage(
|
|
3587
|
+
recycling.projectRoot,
|
|
3588
|
+
recycling.launch.lineageId,
|
|
3589
|
+
{ state: "handoff_pending" },
|
|
3590
|
+
{ generation: recycling.launch.generation, state: "working" }
|
|
3591
|
+
);
|
|
3592
|
+
if (recycling.handoff) await this.publishHandoff(ctx, recycling.handoff);
|
|
3593
|
+
else await this.requestHandoffTurn(ctx, recycling);
|
|
3594
|
+
}
|
|
3595
|
+
async requestHandoffTurn(ctx, recycling) {
|
|
3596
|
+
if (!this.isCurrent(ctx) || this.recycling !== recycling) return;
|
|
3597
|
+
if (recycling.handoffAttempts >= 2) {
|
|
3598
|
+
recycling.state = "failed";
|
|
3599
|
+
this.notify(ctx, "Pi Agent Swarm could not obtain a structured handoff; the worker remains frozen.", "error");
|
|
3600
|
+
await updateWorkerLineage(
|
|
3601
|
+
recycling.projectRoot,
|
|
3602
|
+
recycling.launch.lineageId,
|
|
3603
|
+
{ state: "failed" },
|
|
3604
|
+
{ generation: recycling.launch.generation, state: "handoff_pending" }
|
|
3605
|
+
).catch(() => void 0);
|
|
3606
|
+
await this.send(ctx, {
|
|
3607
|
+
targetSessionId: recycling.leaderSessionId,
|
|
3608
|
+
text: `Context recycling stopped for lineage ${recycling.launch.lineageId}: no structured handoff after ${recycling.handoffAttempts} attempts.`,
|
|
3609
|
+
mode: "notify"
|
|
3610
|
+
}).catch(() => void 0);
|
|
3611
|
+
return;
|
|
3612
|
+
}
|
|
3613
|
+
recycling.handoffAttempts += 1;
|
|
3614
|
+
const paths = workerLineagePaths(recycling.projectRoot, recycling.launch.lineageId, recycling.launch.generation);
|
|
3615
|
+
const content = [
|
|
3616
|
+
"Pi Agent Swarm context handoff is required. Do not continue ordinary task work in this turn.",
|
|
3617
|
+
"Call session_bus action=handoff once with a complete handoff object containing all required fields.",
|
|
3618
|
+
`Write the handoff for: ${paths.handoffPath}`,
|
|
3619
|
+
`Put large supporting logs under: ${paths.artifactsDirectory}`,
|
|
3620
|
+
"Do not include invites, capabilities, credentials, environment dumps, or a raw transcript.",
|
|
3621
|
+
"The exact nextAction must allow a fresh worker to continue without repeating completed work."
|
|
3622
|
+
].join("\n");
|
|
3623
|
+
this.pi.sendMessage(
|
|
3624
|
+
{ customType: SWARM_MESSAGE_TYPE, content, display: false, details: {} },
|
|
3625
|
+
{ deliverAs: "followUp", triggerTurn: true }
|
|
3626
|
+
);
|
|
3627
|
+
}
|
|
3628
|
+
async publishHandoff(ctx, handoff, signal) {
|
|
3629
|
+
this.assertCurrentContext(ctx);
|
|
3630
|
+
const recycling = this.recycling;
|
|
3631
|
+
if (recycling?.state !== "handoff_pending") {
|
|
3632
|
+
throw new Error("Pi Agent Swarm is not waiting for a context handoff");
|
|
3633
|
+
}
|
|
3634
|
+
const membership = this.membership;
|
|
3635
|
+
if (!membership) throw new Error("Pi Agent Swarm is not connected");
|
|
3636
|
+
const paths = await publishWorkerHandoff({
|
|
3637
|
+
projectRoot: recycling.projectRoot,
|
|
3638
|
+
lineageId: recycling.launch.lineageId,
|
|
3639
|
+
generation: recycling.launch.generation,
|
|
3640
|
+
leaderSessionId: recycling.leaderSessionId,
|
|
3641
|
+
policy: recycling.launch.policy,
|
|
3642
|
+
launch: recycling.specification,
|
|
3643
|
+
content: handoff,
|
|
3644
|
+
nextAction: handoff.nextAction
|
|
3645
|
+
});
|
|
3646
|
+
if (this.recycling !== recycling || !this.isCurrent(ctx)) throw staleError();
|
|
3647
|
+
const self = membership.transport.peerDescription;
|
|
3648
|
+
const issuedAt = this.deps.now();
|
|
3649
|
+
try {
|
|
3650
|
+
const acknowledgement = await membership.transport.send(
|
|
3651
|
+
recycling.leaderSessionId,
|
|
3652
|
+
{
|
|
3653
|
+
id: this.deps.randomId("msg"),
|
|
3654
|
+
fromSessionId: self.sessionId,
|
|
3655
|
+
...self.name ? { fromName: self.name } : {},
|
|
3656
|
+
fromCwd: self.cwd,
|
|
3657
|
+
toSessionId: recycling.leaderSessionId,
|
|
3658
|
+
mode: "notify",
|
|
3659
|
+
kind: "handoff",
|
|
3660
|
+
text: paths.handoffPath,
|
|
3661
|
+
issuedAt,
|
|
3662
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS
|
|
3663
|
+
},
|
|
3664
|
+
combineSignals2(signal, this.controller.signal)
|
|
3665
|
+
);
|
|
3666
|
+
if (!acknowledgement.accepted) {
|
|
3667
|
+
throw new Error(`Pi Agent Swarm leader rejected the handoff: ${acknowledgement.error ?? "unknown reason"}`);
|
|
3668
|
+
}
|
|
3669
|
+
} catch (error) {
|
|
3670
|
+
if (this.recycling === recycling && recycling.state === "handoff_pending" && this.isCurrent(ctx)) {
|
|
3671
|
+
const latest = await readWorkerLineage(recycling.projectRoot, recycling.launch.lineageId);
|
|
3672
|
+
if (latest.currentGeneration > recycling.launch.generation || latest.state === "replacing") {
|
|
3673
|
+
recycling.state = "handoff_ready";
|
|
3674
|
+
recycling.handoff = handoff;
|
|
3675
|
+
return { handoffPath: paths.handoffPath };
|
|
3676
|
+
}
|
|
3677
|
+
if (latest.currentGeneration === recycling.launch.generation && latest.state === "handoff_ready") {
|
|
3678
|
+
await updateWorkerLineage(
|
|
3679
|
+
recycling.projectRoot,
|
|
3680
|
+
recycling.launch.lineageId,
|
|
3681
|
+
{ state: "handoff_pending" },
|
|
3682
|
+
{ generation: recycling.launch.generation, state: "handoff_ready" }
|
|
3683
|
+
);
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
throw error;
|
|
3687
|
+
}
|
|
3688
|
+
if (this.recycling !== recycling || this.membership !== membership || !this.isCurrent(ctx)) throw staleError();
|
|
3689
|
+
recycling.state = "handoff_ready";
|
|
3690
|
+
recycling.handoff = handoff;
|
|
3691
|
+
return { handoffPath: paths.handoffPath };
|
|
3692
|
+
}
|
|
3693
|
+
freezeForHandoff() {
|
|
3694
|
+
if (!this.membership) return;
|
|
3695
|
+
this.membership.acceptsRequests = false;
|
|
3696
|
+
this.membership.transport.setAcceptsRequests(false);
|
|
3047
3697
|
}
|
|
3048
3698
|
async snapshot(signal) {
|
|
3049
3699
|
if (!this.activeSessionManager || this.controller.signal.aborted) throw staleError();
|
|
@@ -3078,7 +3728,10 @@ var SwarmController = class {
|
|
|
3078
3728
|
const membership = this.membership;
|
|
3079
3729
|
if (!membership) throw new Error("Pi Agent Swarm is not connected");
|
|
3080
3730
|
membership.rollbackLaunch = void 0;
|
|
3081
|
-
|
|
3731
|
+
const usage = this.recycling && options.mode === "reply" ? ctx.getContextUsage() : void 0;
|
|
3732
|
+
const metricPrefix = this.recycling && options.mode === "reply" ? `[Swarm lineage ${this.recycling.launch.lineageId} generation ${this.recycling.launch.generation}; model ${ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "unknown"}; context ${usage?.percent ?? "unknown"}%${usage ? ` (${usage.tokens ?? "unknown"}/${usage.contextWindow} tokens)` : ""}; taskProfile ${this.recycling.launch.policy.taskProfile}; state ${this.recycling.state}; updatedAt ${(/* @__PURE__ */ new Date()).toISOString()}]
|
|
3733
|
+
` : "";
|
|
3734
|
+
if (Buffer.byteLength(`${metricPrefix}${options.text}`) > MAX_MESSAGE_BYTES) {
|
|
3082
3735
|
throw new Error("Pi Agent Swarm message is too large");
|
|
3083
3736
|
}
|
|
3084
3737
|
const self = membership.transport.peerDescription;
|
|
@@ -3090,7 +3743,7 @@ var SwarmController = class {
|
|
|
3090
3743
|
fromCwd: self.cwd,
|
|
3091
3744
|
toSessionId: options.targetSessionId,
|
|
3092
3745
|
mode: options.mode,
|
|
3093
|
-
text: options.text
|
|
3746
|
+
text: `${metricPrefix}${options.text}`,
|
|
3094
3747
|
issuedAt,
|
|
3095
3748
|
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
|
|
3096
3749
|
...options.replyTo ? { replyTo: options.replyTo } : {}
|
|
@@ -3102,6 +3755,10 @@ var SwarmController = class {
|
|
|
3102
3755
|
if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
|
|
3103
3756
|
throw staleError();
|
|
3104
3757
|
}
|
|
3758
|
+
if (acknowledgement.accepted && this.recycling && options.mode === "reply") {
|
|
3759
|
+
this.recycling.taskStatus = options.taskStatus ?? "working";
|
|
3760
|
+
this.recycling.handoff = options.handoff;
|
|
3761
|
+
}
|
|
3105
3762
|
return { message, acknowledgement };
|
|
3106
3763
|
}
|
|
3107
3764
|
/** Send a control-plane shutdown request asking the target peer to exit gracefully. */
|
|
@@ -3147,6 +3804,12 @@ var SwarmController = class {
|
|
|
3147
3804
|
await this.settings.flush();
|
|
3148
3805
|
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3149
3806
|
const launchSettings = this.settings.get().settings;
|
|
3807
|
+
const recyclingLaunch = input.recyclingLaunch ?? (input.contextRecycling ? {
|
|
3808
|
+
lineageId: this.deps.randomId("lineage"),
|
|
3809
|
+
generation: 1,
|
|
3810
|
+
replacementCount: 0,
|
|
3811
|
+
policy: normalizeContextRecyclingPolicy(input.contextRecycling)
|
|
3812
|
+
} : void 0);
|
|
3150
3813
|
const direction = input.direction ?? "right";
|
|
3151
3814
|
const windowLabel = "window";
|
|
3152
3815
|
const launchLayoutLine = "External terminal window (the window manager places it)";
|
|
@@ -3188,7 +3851,7 @@ var SwarmController = class {
|
|
|
3188
3851
|
);
|
|
3189
3852
|
const terminalVersion = await terminalAdapter.assertAvailable(operationSignal);
|
|
3190
3853
|
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3191
|
-
if (launchSettings.confirmSessionLaunch) {
|
|
3854
|
+
if (launchSettings.confirmSessionLaunch && !input.recyclingLaunch) {
|
|
3192
3855
|
const confirmed = await ctx.ui.confirm(
|
|
3193
3856
|
"Create a new Pi session?",
|
|
3194
3857
|
[
|
|
@@ -3197,6 +3860,8 @@ var SwarmController = class {
|
|
|
3197
3860
|
`Color: ${safeTerminalLine(color)}`,
|
|
3198
3861
|
`Cwd: ${safeTerminalLine(cwd)}`,
|
|
3199
3862
|
`Model: ${safeTerminalLine(childModel ? `${childModel.provider}/${childModel.id}` : "Pi default")}`,
|
|
3863
|
+
`Follow-up requests: ${input.allowRequests ? "allowed for trusted peers" : "blocked"}.`,
|
|
3864
|
+
`Context recycling: ${recyclingLaunch ? `${recyclingLaunch.policy.maxContextPercent}% soft handoff, at most ${recyclingLaunch.policy.maxReplacements} replacements` : "disabled"}.`,
|
|
3200
3865
|
"The child may spend model tokens and edit the same workspace concurrently."
|
|
3201
3866
|
].join("\n"),
|
|
3202
3867
|
{ signal: operationSignal }
|
|
@@ -3224,7 +3889,8 @@ var SwarmController = class {
|
|
|
3224
3889
|
kickoffCapability,
|
|
3225
3890
|
childName: name,
|
|
3226
3891
|
childColor: color,
|
|
3227
|
-
acceptsRequests:
|
|
3892
|
+
acceptsRequests: input.allowRequests === true,
|
|
3893
|
+
...recyclingLaunch ? { contextRecycling: recyclingLaunch } : {},
|
|
3228
3894
|
...childModel ? { model: childModel } : {}
|
|
3229
3895
|
};
|
|
3230
3896
|
const launchEnvironment = launchEnvelopeEnvironment(envelope);
|
|
@@ -3288,7 +3954,8 @@ var SwarmController = class {
|
|
|
3288
3954
|
cwd: child.cwd,
|
|
3289
3955
|
terminalId,
|
|
3290
3956
|
terminalVersion: actualTerminalVersion,
|
|
3291
|
-
kickoffAccepted
|
|
3957
|
+
kickoffAccepted,
|
|
3958
|
+
...recyclingLaunch ? { lineageId: recyclingLaunch.lineageId } : {}
|
|
3292
3959
|
};
|
|
3293
3960
|
} catch (error) {
|
|
3294
3961
|
const partial = splitCreated || isTerminalLaunchError(error) && error.splitCreated;
|
|
@@ -3367,11 +4034,34 @@ var SwarmController = class {
|
|
|
3367
4034
|
...kickoffCapability ? { kickoffCapability } : {},
|
|
3368
4035
|
kickoffConsumed: acceptedKickoff,
|
|
3369
4036
|
authorizeShutdown: (message) => message.fromSessionId === this.parentSessionId || this.leadSessionId !== void 0 && message.fromSessionId === this.leadSessionId,
|
|
4037
|
+
authorizeHandoff: () => this.isCurrent(owner, ownerGeneration) && this.leadSessionId === ctx.sessionManager.getSessionId(),
|
|
4038
|
+
rejectRequest: () => {
|
|
4039
|
+
const state = this.recycling?.state;
|
|
4040
|
+
if (!state || !["handoff_pending", "handoff_ready", "replacing", "failed", "retired"].includes(state))
|
|
4041
|
+
return void 0;
|
|
4042
|
+
return {
|
|
4043
|
+
kind: "ack",
|
|
4044
|
+
status: "rejected",
|
|
4045
|
+
code: "context_handoff",
|
|
4046
|
+
error: `Target worker is ${state}; only the context handoff protocol may continue`
|
|
4047
|
+
};
|
|
4048
|
+
},
|
|
3370
4049
|
onMessage: async (message, deliverySignal) => {
|
|
3371
4050
|
if (deliverySignal?.aborted || !this.isCurrent(owner, ownerGeneration)) return;
|
|
3372
4051
|
const activeContext = this.activeContext;
|
|
3373
4052
|
if (message.kind === "shutdown") {
|
|
3374
4053
|
const idle = activeContext?.isIdle() ?? false;
|
|
4054
|
+
if (this.recycling) {
|
|
4055
|
+
const recycling = this.recycling;
|
|
4056
|
+
recycling.state = "retired";
|
|
4057
|
+
const lineage = await readWorkerLineage(recycling.projectRoot, recycling.launch.lineageId);
|
|
4058
|
+
await updateWorkerLineage(
|
|
4059
|
+
recycling.projectRoot,
|
|
4060
|
+
recycling.launch.lineageId,
|
|
4061
|
+
lineage.currentGeneration === recycling.launch.generation ? { state: "retired" } : { retiredThroughGeneration: recycling.launch.generation },
|
|
4062
|
+
{ generation: lineage.currentGeneration }
|
|
4063
|
+
);
|
|
4064
|
+
}
|
|
3375
4065
|
activeContext?.shutdown();
|
|
3376
4066
|
if (idle && activeContext) {
|
|
3377
4067
|
const details = { message };
|
|
@@ -3384,7 +4074,10 @@ var SwarmController = class {
|
|
|
3384
4074
|
return;
|
|
3385
4075
|
}
|
|
3386
4076
|
if (message.kind === "lead") {
|
|
4077
|
+
} else if (message.kind === "handoff") {
|
|
4078
|
+
if (activeContext) await this.acceptWorkerHandoff(activeContext, message);
|
|
3387
4079
|
} else {
|
|
4080
|
+
await this.noteIncomingWork(message);
|
|
3388
4081
|
this.receiveMessage(message);
|
|
3389
4082
|
}
|
|
3390
4083
|
void this.refreshLead().then((changed) => {
|
|
@@ -3428,6 +4121,190 @@ var SwarmController = class {
|
|
|
3428
4121
|
this.endStatus(token);
|
|
3429
4122
|
}
|
|
3430
4123
|
}
|
|
4124
|
+
acceptWorkerHandoff(ctx, message) {
|
|
4125
|
+
const key = `${message.fromSessionId}:${message.text}`;
|
|
4126
|
+
if (this.successorLaunches.has(key)) return;
|
|
4127
|
+
const owner = ctx.sessionManager;
|
|
4128
|
+
const ownerGeneration = this.generation;
|
|
4129
|
+
const task = this.spawnSuccessor(ctx, message).catch((error) => {
|
|
4130
|
+
this.successorLaunches.delete(key);
|
|
4131
|
+
if (this.isCurrent(owner, ownerGeneration)) {
|
|
4132
|
+
this.notify(
|
|
4133
|
+
ctx,
|
|
4134
|
+
`Pi Agent Swarm could not replace worker ${safeTerminalLine(message.fromName ?? message.fromSessionId)}: ${safeError(error)}`,
|
|
4135
|
+
"error"
|
|
4136
|
+
);
|
|
4137
|
+
}
|
|
4138
|
+
});
|
|
4139
|
+
this.successorLaunches.set(key, task);
|
|
4140
|
+
}
|
|
4141
|
+
async recoverProjectHandoffs(ctx) {
|
|
4142
|
+
const directory = resolve6(ctx.cwd, ".pi", "agent-swarm", "lineages");
|
|
4143
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
|
|
4144
|
+
if (error.code === "ENOENT") return [];
|
|
4145
|
+
throw error;
|
|
4146
|
+
});
|
|
4147
|
+
for (const entry of entries) {
|
|
4148
|
+
if (!entry.isDirectory()) continue;
|
|
4149
|
+
let lineage = await readWorkerLineage(ctx.cwd, entry.name).catch(() => void 0);
|
|
4150
|
+
if (!lineage || lineage.leaderSessionId !== ctx.sessionManager.getSessionId()) continue;
|
|
4151
|
+
if (!lineage.workerSessionId || !lineage.currentHandoffPath) continue;
|
|
4152
|
+
const workerSessionId = lineage.workerSessionId;
|
|
4153
|
+
const handoffPath = lineage.currentHandoffPath;
|
|
4154
|
+
const key = `${workerSessionId}:${handoffPath}`;
|
|
4155
|
+
if (this.successorLaunches.has(key)) continue;
|
|
4156
|
+
if (lineage.state === "replacing") {
|
|
4157
|
+
try {
|
|
4158
|
+
await this.restoreHandoffReady(ctx.cwd, entry.name, lineage.currentGeneration);
|
|
4159
|
+
} catch {
|
|
4160
|
+
continue;
|
|
4161
|
+
}
|
|
4162
|
+
lineage = await readWorkerLineage(ctx.cwd, entry.name).catch(() => void 0);
|
|
4163
|
+
if (!lineage) continue;
|
|
4164
|
+
}
|
|
4165
|
+
if (lineage.state !== "handoff_ready" || lineage.workerSessionId !== workerSessionId || lineage.currentHandoffPath !== handoffPath) {
|
|
4166
|
+
continue;
|
|
4167
|
+
}
|
|
4168
|
+
const issuedAt = this.deps.now();
|
|
4169
|
+
this.acceptWorkerHandoff(ctx, {
|
|
4170
|
+
id: this.deps.randomId("msg"),
|
|
4171
|
+
fromSessionId: workerSessionId,
|
|
4172
|
+
fromCwd: ctx.cwd,
|
|
4173
|
+
toSessionId: ctx.sessionManager.getSessionId(),
|
|
4174
|
+
mode: "notify",
|
|
4175
|
+
kind: "handoff",
|
|
4176
|
+
text: handoffPath,
|
|
4177
|
+
issuedAt,
|
|
4178
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS
|
|
4179
|
+
});
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
async spawnSuccessor(ctx, message) {
|
|
4183
|
+
const projectRoot = message.fromCwd;
|
|
4184
|
+
if (!projectRoot) throw new Error("Handoff sender did not provide its project cwd");
|
|
4185
|
+
const handoffPath = resolve6(message.text);
|
|
4186
|
+
const storagePrefix = `${resolve6(projectRoot, ".pi", "agent-swarm", "lineages")}${sep3}`;
|
|
4187
|
+
if (!handoffPath.startsWith(storagePrefix) || basename5(dirname6(handoffPath)) !== "generations") {
|
|
4188
|
+
throw new Error("Handoff path is outside the sender's project lineage storage");
|
|
4189
|
+
}
|
|
4190
|
+
const lineageId = basename5(dirname6(dirname6(handoffPath)));
|
|
4191
|
+
const lineage = await readWorkerLineage(projectRoot, lineageId);
|
|
4192
|
+
if (!this.isCurrent(ctx)) throw staleError();
|
|
4193
|
+
if (lineage.leaderSessionId !== ctx.sessionManager.getSessionId() || resolve6(lineage.currentHandoffPath ?? "") !== handoffPath || lineage.state !== "handoff_ready" || !lineage.nextAction) {
|
|
4194
|
+
throw new Error("Handoff lineage is not ready for this leader");
|
|
4195
|
+
}
|
|
4196
|
+
if (lineage.replacementCount >= lineage.policy.maxReplacements) {
|
|
4197
|
+
throw new Error("Handoff replacement budget is exhausted");
|
|
4198
|
+
}
|
|
4199
|
+
await readFile2(handoffPath, "utf8");
|
|
4200
|
+
const nextGeneration = lineage.currentGeneration + 1;
|
|
4201
|
+
const replacementCount = lineage.replacementCount + 1;
|
|
4202
|
+
await updateWorkerLineage(
|
|
4203
|
+
projectRoot,
|
|
4204
|
+
lineageId,
|
|
4205
|
+
{ state: "replacing" },
|
|
4206
|
+
{ generation: lineage.currentGeneration, state: "handoff_ready" }
|
|
4207
|
+
);
|
|
4208
|
+
const baseName = lineage.launch.name ?? `Worker ${lineageId.slice(-6)}`;
|
|
4209
|
+
const continuation = [
|
|
4210
|
+
`Continue Swarm lineage ${lineageId}, generation ${nextGeneration}.`,
|
|
4211
|
+
`Read the exact handoff at ${handoffPath}.`,
|
|
4212
|
+
`Original objective: ${lineage.originalObjective}`,
|
|
4213
|
+
`Remaining objective: ${lineage.remainingWork ?? "See the handoff."}`,
|
|
4214
|
+
`Exact next action: ${lineage.nextAction}`,
|
|
4215
|
+
"Do not repeat completed work. Read artifact paths only when needed. Report through session_bus with taskStatus."
|
|
4216
|
+
].join("\n");
|
|
4217
|
+
let result;
|
|
4218
|
+
try {
|
|
4219
|
+
result = await this.spawn(ctx, {
|
|
4220
|
+
cwd: lineage.launch.cwd,
|
|
4221
|
+
model: lineage.launch.model,
|
|
4222
|
+
name: `${baseName} \xB7 G${nextGeneration}`.slice(0, 200),
|
|
4223
|
+
...lineage.launch.color ? { color: lineage.launch.color } : {},
|
|
4224
|
+
allowRequests: lineage.launch.allowRequests,
|
|
4225
|
+
recyclingLaunch: {
|
|
4226
|
+
lineageId,
|
|
4227
|
+
generation: nextGeneration,
|
|
4228
|
+
replacementCount,
|
|
4229
|
+
policy: lineage.policy,
|
|
4230
|
+
handoffPath
|
|
4231
|
+
},
|
|
4232
|
+
task: continuation
|
|
4233
|
+
});
|
|
4234
|
+
if (!result.kickoffAccepted) throw new Error("Successor did not accept its continuation");
|
|
4235
|
+
if (!this.isCurrent(ctx)) throw staleError();
|
|
4236
|
+
} catch (error) {
|
|
4237
|
+
if (result && (!result.kickoffAccepted || !this.isCurrent(ctx))) {
|
|
4238
|
+
await this.shutdownPeer(ctx, result.sessionId).catch(() => void 0);
|
|
4239
|
+
}
|
|
4240
|
+
await this.restoreHandoffReady(projectRoot, lineageId, lineage.currentGeneration);
|
|
4241
|
+
throw error;
|
|
4242
|
+
}
|
|
4243
|
+
await updateWorkerLineage(
|
|
4244
|
+
projectRoot,
|
|
4245
|
+
lineageId,
|
|
4246
|
+
{
|
|
4247
|
+
state: "working",
|
|
4248
|
+
currentGeneration: nextGeneration,
|
|
4249
|
+
replacementCount,
|
|
4250
|
+
successorSessionId: result.sessionId
|
|
4251
|
+
},
|
|
4252
|
+
{ generation: nextGeneration }
|
|
4253
|
+
);
|
|
4254
|
+
let predecessorRetired = false;
|
|
4255
|
+
let shutdownError = "unknown reason";
|
|
4256
|
+
for (let attempt = 0; attempt < 2 && this.isCurrent(ctx); attempt += 1) {
|
|
4257
|
+
try {
|
|
4258
|
+
const shutdown = await this.shutdownPeer(ctx, message.fromSessionId);
|
|
4259
|
+
predecessorRetired = shutdown.acknowledgement.accepted;
|
|
4260
|
+
shutdownError = shutdown.acknowledgement.error ?? "shutdown rejected";
|
|
4261
|
+
} catch (error) {
|
|
4262
|
+
shutdownError = safeError(error);
|
|
4263
|
+
}
|
|
4264
|
+
if (predecessorRetired) break;
|
|
4265
|
+
if (attempt === 0) await this.deps.sleep(25, this.controller.signal).catch(() => void 0);
|
|
4266
|
+
}
|
|
4267
|
+
if (predecessorRetired && this.isCurrent(ctx)) {
|
|
4268
|
+
await updateWorkerLineage(
|
|
4269
|
+
projectRoot,
|
|
4270
|
+
lineageId,
|
|
4271
|
+
{ retiredThroughGeneration: lineage.currentGeneration },
|
|
4272
|
+
{ generation: nextGeneration, state: "working" }
|
|
4273
|
+
);
|
|
4274
|
+
} else if (this.isCurrent(ctx)) {
|
|
4275
|
+
this.notify(
|
|
4276
|
+
ctx,
|
|
4277
|
+
`Successor is ready, but the predecessor remains frozen: ${safeTerminalLine(shutdownError)}`,
|
|
4278
|
+
"warning"
|
|
4279
|
+
);
|
|
4280
|
+
}
|
|
4281
|
+
if (this.isCurrent(ctx)) {
|
|
4282
|
+
this.notify(
|
|
4283
|
+
ctx,
|
|
4284
|
+
`Pi Agent Swarm replaced ${safeTerminalLine(baseName)} with generation ${nextGeneration}.`,
|
|
4285
|
+
"info"
|
|
4286
|
+
);
|
|
4287
|
+
}
|
|
4288
|
+
}
|
|
4289
|
+
async restoreHandoffReady(projectRoot, lineageId, generation) {
|
|
4290
|
+
const latest = await readWorkerLineage(projectRoot, lineageId);
|
|
4291
|
+
if (latest.currentGeneration === generation && latest.state === "replacing") {
|
|
4292
|
+
await updateWorkerLineage(projectRoot, lineageId, { state: "handoff_ready" }, { generation, state: "replacing" });
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
4295
|
+
async noteIncomingWork(message) {
|
|
4296
|
+
const recycling = this.recycling;
|
|
4297
|
+
if (!recycling || message.mode !== "kickoff" && message.mode !== "request") return;
|
|
4298
|
+
recycling.taskStatus = "working";
|
|
4299
|
+
recycling.handoff = void 0;
|
|
4300
|
+
recycling.state = "working";
|
|
4301
|
+
recycling.handoffAttempts = 0;
|
|
4302
|
+
const patch = { state: "working" };
|
|
4303
|
+
if (message.mode === "kickoff" && recycling.launch.generation === 1) patch.originalObjective = message.text;
|
|
4304
|
+
await updateWorkerLineage(recycling.projectRoot, recycling.launch.lineageId, patch, {
|
|
4305
|
+
generation: recycling.launch.generation
|
|
4306
|
+
});
|
|
4307
|
+
}
|
|
3431
4308
|
receiveMessage(message) {
|
|
3432
4309
|
const sender = message.fromName ?? message.fromSessionId;
|
|
3433
4310
|
const heading = message.kind === "steer" ? `Pi Agent Swarm: user steered ${sender} (${message.fromSessionId}):` : `Pi Agent Swarm ${message.mode} from ${sender} (${message.fromSessionId}).`;
|
|
@@ -3482,7 +4359,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
3482
4359
|
throw new Error(`Pi Agent Swarm child readiness timed out after ${this.deps.launchTimeoutMs}ms`);
|
|
3483
4360
|
}
|
|
3484
4361
|
async resolveSpawnCwd(ctx, value) {
|
|
3485
|
-
const requested = value?.trim() ?
|
|
4362
|
+
const requested = value?.trim() ? resolve6(ctx.cwd, value) : ctx.cwd;
|
|
3486
4363
|
const canonical = await this.deps.realpath(requested);
|
|
3487
4364
|
if (canonical.includes("\0") || Buffer.byteLength(canonical) > 4096) {
|
|
3488
4365
|
throw new Error("Pi Agent Swarm child cwd is invalid or too large");
|
|
@@ -3523,7 +4400,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
3523
4400
|
membership?.group.secret.fill(0);
|
|
3524
4401
|
}
|
|
3525
4402
|
if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
|
|
3526
|
-
await
|
|
4403
|
+
await rm6(join8(directory, "lead.json"), { force: true }).catch(() => void 0);
|
|
3527
4404
|
}
|
|
3528
4405
|
this.leadSessionId = void 0;
|
|
3529
4406
|
});
|
|
@@ -3579,7 +4456,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
3579
4456
|
}
|
|
3580
4457
|
leadPath() {
|
|
3581
4458
|
const directory = this.membership?.transport.endpointManifest?.directory;
|
|
3582
|
-
return directory ?
|
|
4459
|
+
return directory ? join8(directory, "lead.json") : void 0;
|
|
3583
4460
|
}
|
|
3584
4461
|
async refreshLead() {
|
|
3585
4462
|
const path2 = this.leadPath();
|
|
@@ -3589,7 +4466,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
3589
4466
|
return changed;
|
|
3590
4467
|
}
|
|
3591
4468
|
try {
|
|
3592
|
-
const raw = JSON.parse(await
|
|
4469
|
+
const raw = JSON.parse(await readFile2(path2, "utf8"));
|
|
3593
4470
|
const next = typeof raw.sessionId === "string" ? raw.sessionId : void 0;
|
|
3594
4471
|
const changed = next !== this.leadSessionId;
|
|
3595
4472
|
this.leadSessionId = next;
|
|
@@ -3634,18 +4511,18 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
|
|
|
3634
4511
|
throwIfAborted5(signal, "Pi Agent Swarm lead change aborted");
|
|
3635
4512
|
const path2 = this.leadPath();
|
|
3636
4513
|
if (!path2) throw new Error("Pi Agent Swarm runtime directory is unavailable");
|
|
3637
|
-
const
|
|
4514
|
+
const record2 = {
|
|
3638
4515
|
sessionId: target.sessionId,
|
|
3639
4516
|
...target.name ? { name: target.name } : {},
|
|
3640
4517
|
at: this.deps.now()
|
|
3641
4518
|
};
|
|
3642
4519
|
const temporary = `${path2}.tmp-${process.pid}`;
|
|
3643
4520
|
try {
|
|
3644
|
-
await
|
|
4521
|
+
await writeFile3(temporary, `${JSON.stringify(record2)}
|
|
3645
4522
|
`, { encoding: "utf8", flag: "wx" });
|
|
3646
|
-
await
|
|
4523
|
+
await rename4(temporary, path2);
|
|
3647
4524
|
} finally {
|
|
3648
|
-
await
|
|
4525
|
+
await rm6(temporary, { force: true }).catch(() => void 0);
|
|
3649
4526
|
}
|
|
3650
4527
|
this.leadSessionId = target.sessionId;
|
|
3651
4528
|
await this.broadcastLeadChange(target);
|
|
@@ -3935,13 +4812,60 @@ function isRecord5(value) {
|
|
|
3935
4812
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
3936
4813
|
import { Type } from "typebox";
|
|
3937
4814
|
var DIRECTIONS = ["right", "down", "left", "up"];
|
|
3938
|
-
var BUS_ACTIONS = ["list", "send", "reply", "shutdown"];
|
|
4815
|
+
var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff"];
|
|
3939
4816
|
var SEND_MODES = ["notify", "request"];
|
|
3940
4817
|
var MAX_LISTED_PEERS = 64;
|
|
3941
4818
|
var MAX_LIST_RESULT_BYTES = 40 * 1024;
|
|
4819
|
+
var handoffSchema = Type.Object(
|
|
4820
|
+
{
|
|
4821
|
+
originalObjective: Type.String({ maxLength: 8192 }),
|
|
4822
|
+
currentState: Type.String({ maxLength: 8192 }),
|
|
4823
|
+
completedWork: Type.String({ maxLength: 8192 }),
|
|
4824
|
+
remainingWork: Type.String({ maxLength: 8192 }),
|
|
4825
|
+
modifiedFiles: Type.String({ maxLength: 8192 }),
|
|
4826
|
+
verification: Type.String({ maxLength: 8192 }),
|
|
4827
|
+
decisions: Type.String({ maxLength: 8192 }),
|
|
4828
|
+
blocker: Type.String({ maxLength: 8192 }),
|
|
4829
|
+
nextAction: Type.String({ maxLength: 8192 }),
|
|
4830
|
+
artifacts: Type.Array(Type.String({ maxLength: 4096 }), { maxItems: 32 })
|
|
4831
|
+
},
|
|
4832
|
+
{ additionalProperties: false }
|
|
4833
|
+
);
|
|
3942
4834
|
var spawnSchema = Type.Object(
|
|
3943
4835
|
{
|
|
3944
4836
|
direction: Type.Optional(StringEnum(DIRECTIONS, { description: "Terminal window direction" })),
|
|
4837
|
+
allowRequests: Type.Optional(
|
|
4838
|
+
Type.Boolean({
|
|
4839
|
+
description: "Allow trusted peers to request follow-up turns in the child after its initial task; defaults to false. This can incur model charges and concurrent workspace edits."
|
|
4840
|
+
})
|
|
4841
|
+
),
|
|
4842
|
+
contextRecycling: Type.Optional(
|
|
4843
|
+
Type.Object(
|
|
4844
|
+
{
|
|
4845
|
+
taskProfile: Type.Union([Type.Literal("short"), Type.Literal("long"), Type.Literal("auto")], {
|
|
4846
|
+
description: "Leader's assessment of the assignment duration"
|
|
4847
|
+
}),
|
|
4848
|
+
maxContextPercent: Type.Optional(
|
|
4849
|
+
Type.Number({
|
|
4850
|
+
description: "Soft handoff threshold; defaults to 50 and never aborts the current turn",
|
|
4851
|
+
minimum: 1,
|
|
4852
|
+
maximum: 100
|
|
4853
|
+
})
|
|
4854
|
+
),
|
|
4855
|
+
maxReplacements: Type.Optional(
|
|
4856
|
+
Type.Integer({
|
|
4857
|
+
description: "Maximum authorized automatic successors; defaults to 3, maximum 10",
|
|
4858
|
+
minimum: 0,
|
|
4859
|
+
maximum: 10
|
|
4860
|
+
})
|
|
4861
|
+
)
|
|
4862
|
+
},
|
|
4863
|
+
{
|
|
4864
|
+
additionalProperties: false,
|
|
4865
|
+
description: "Authorize bounded automatic worker replacement after a stable-boundary handoff. Omit to disable recycling."
|
|
4866
|
+
}
|
|
4867
|
+
)
|
|
4868
|
+
),
|
|
3945
4869
|
task: Type.Optional(
|
|
3946
4870
|
Type.String({
|
|
3947
4871
|
description: "Optional first task sent after child readiness",
|
|
@@ -3982,7 +4906,13 @@ var busSchema = Type.Object(
|
|
|
3982
4906
|
mode: Type.Optional(StringEnum(SEND_MODES, { description: "Notify without a turn or request one turn" })),
|
|
3983
4907
|
replyTo: Type.Optional(
|
|
3984
4908
|
Type.String({ description: "Original message id for a reply", minLength: 1, maxLength: 128 })
|
|
3985
|
-
)
|
|
4909
|
+
),
|
|
4910
|
+
taskStatus: Type.Optional(
|
|
4911
|
+
Type.Union([Type.Literal("working"), Type.Literal("completed")], {
|
|
4912
|
+
description: "Worker task state for context recycling; completed prevents successor creation"
|
|
4913
|
+
})
|
|
4914
|
+
),
|
|
4915
|
+
handoff: Type.Optional(handoffSchema)
|
|
3986
4916
|
},
|
|
3987
4917
|
{ additionalProperties: false }
|
|
3988
4918
|
);
|
|
@@ -3994,7 +4924,9 @@ function registerSwarmTools(pi, controller) {
|
|
|
3994
4924
|
promptSnippet: "Start a collaborating Pi session in an external terminal window",
|
|
3995
4925
|
promptGuidelines: [
|
|
3996
4926
|
"Use session_spawn only when the user explicitly asks to open or start another Pi session.",
|
|
3997
|
-
"Do not claim the child is ready until session_spawn returns authenticated readiness metadata."
|
|
4927
|
+
"Do not claim the child is ready until session_spawn returns authenticated readiness metadata.",
|
|
4928
|
+
"Use allowRequests only when the user wants this worker to accept follow-up tasks in the same session; it defaults to false.",
|
|
4929
|
+
"Use contextRecycling only with explicit user authorization for bounded automatic worker replacement; the threshold is soft and never interrupts a healthy turn."
|
|
3998
4930
|
],
|
|
3999
4931
|
parameters: spawnSchema,
|
|
4000
4932
|
executionMode: "sequential",
|
|
@@ -4027,7 +4959,8 @@ function registerSwarmTools(pi, controller) {
|
|
|
4027
4959
|
promptSnippet: "List or message Pi Agent Swarm sessions on this machine",
|
|
4028
4960
|
promptGuidelines: [
|
|
4029
4961
|
"Use session_bus to communicate with sessions already connected through Pi Agent Swarm.",
|
|
4030
|
-
"Treat session_bus accepted acknowledgements as extension delivery only, not proof that a remote task succeeded."
|
|
4962
|
+
"Treat session_bus accepted acknowledgements as extension delivery only, not proof that a remote task succeeded.",
|
|
4963
|
+
"Workers with contextRecycling must report taskStatus=completed when done; unfinished workers publish a structured handoff when asked."
|
|
4031
4964
|
],
|
|
4032
4965
|
parameters: busSchema,
|
|
4033
4966
|
executionMode: "sequential",
|
|
@@ -4037,6 +4970,8 @@ function registerSwarmTools(pi, controller) {
|
|
|
4037
4970
|
assertAbsent(params.message, "message", "list");
|
|
4038
4971
|
assertAbsent(params.mode, "mode", "list");
|
|
4039
4972
|
assertAbsent(params.replyTo, "replyTo", "list");
|
|
4973
|
+
assertAbsent(params.taskStatus, "taskStatus", "list");
|
|
4974
|
+
assertAbsent(params.handoff, "handoff", "list");
|
|
4040
4975
|
const snapshot = await controller.snapshot(signal);
|
|
4041
4976
|
if (!snapshot.connected) {
|
|
4042
4977
|
return {
|
|
@@ -4050,21 +4985,49 @@ function registerSwarmTools(pi, controller) {
|
|
|
4050
4985
|
assertAbsent(params.message, "message", "shutdown");
|
|
4051
4986
|
assertAbsent(params.mode, "mode", "shutdown");
|
|
4052
4987
|
assertAbsent(params.replyTo, "replyTo", "shutdown");
|
|
4988
|
+
assertAbsent(params.taskStatus, "taskStatus", "shutdown");
|
|
4989
|
+
assertAbsent(params.handoff, "handoff", "shutdown");
|
|
4053
4990
|
const shutdownTarget = required(params.targetSessionId, "targetSessionId");
|
|
4054
4991
|
const result2 = await controller.shutdownPeer(ctx, shutdownTarget, signal);
|
|
4055
4992
|
return shutdownResult(result2, shutdownTarget);
|
|
4056
4993
|
}
|
|
4994
|
+
if (params.action === "handoff") {
|
|
4995
|
+
assertAbsent(params.targetSessionId, "targetSessionId", "handoff");
|
|
4996
|
+
assertAbsent(params.message, "message", "handoff");
|
|
4997
|
+
assertAbsent(params.mode, "mode", "handoff");
|
|
4998
|
+
assertAbsent(params.replyTo, "replyTo", "handoff");
|
|
4999
|
+
assertAbsent(params.taskStatus, "taskStatus", "handoff");
|
|
5000
|
+
if (!params.handoff) throw new Error("session_bus handoff is required for this action");
|
|
5001
|
+
const result2 = await controller.publishHandoff(ctx, params.handoff, signal);
|
|
5002
|
+
return {
|
|
5003
|
+
content: [{ type: "text", text: `Worker handoff is ready: ${safeTerminalLine(result2.handoffPath)}` }],
|
|
5004
|
+
details: result2
|
|
5005
|
+
};
|
|
5006
|
+
}
|
|
4057
5007
|
const targetSessionId = required(params.targetSessionId, "targetSessionId");
|
|
4058
5008
|
const message = required(params.message, "message");
|
|
4059
5009
|
if (params.action === "send") {
|
|
4060
5010
|
assertAbsent(params.replyTo, "replyTo", "send");
|
|
5011
|
+
assertAbsent(params.taskStatus, "taskStatus", "send");
|
|
5012
|
+
assertAbsent(params.handoff, "handoff", "send");
|
|
4061
5013
|
const mode = params.mode ?? "notify";
|
|
4062
5014
|
const result2 = await controller.send(ctx, { targetSessionId, text: message, mode }, signal);
|
|
4063
5015
|
return deliveryResult(result2, targetSessionId);
|
|
4064
5016
|
}
|
|
4065
5017
|
assertAbsent(params.mode, "mode", "reply");
|
|
4066
5018
|
const replyTo = required(params.replyTo, "replyTo");
|
|
4067
|
-
const result = await controller.send(
|
|
5019
|
+
const result = await controller.send(
|
|
5020
|
+
ctx,
|
|
5021
|
+
{
|
|
5022
|
+
targetSessionId,
|
|
5023
|
+
text: message,
|
|
5024
|
+
mode: "reply",
|
|
5025
|
+
replyTo,
|
|
5026
|
+
...params.taskStatus ? { taskStatus: params.taskStatus } : {},
|
|
5027
|
+
...params.handoff ? { handoff: params.handoff } : {}
|
|
5028
|
+
},
|
|
5029
|
+
signal
|
|
5030
|
+
);
|
|
4068
5031
|
return deliveryResult(result, targetSessionId);
|
|
4069
5032
|
}
|
|
4070
5033
|
});
|
|
@@ -4159,12 +5122,12 @@ function assertAbsent(value, field, action) {
|
|
|
4159
5122
|
}
|
|
4160
5123
|
|
|
4161
5124
|
// src/pi-agent-swarm.ts
|
|
4162
|
-
var USAGE = "Usage: /swarm, /swarm start, or /swarm <piagentswarm:v1:invite>";
|
|
5125
|
+
var USAGE = "Usage: /swarm, /swarm start, /swarm requests <on|off>, or /swarm <piagentswarm:v1:invite>";
|
|
4163
5126
|
function createPiSwarmExtension(dependencies = {}) {
|
|
4164
5127
|
return function piSwarmExtension(pi) {
|
|
4165
5128
|
const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
|
|
4166
5129
|
const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
|
|
4167
|
-
const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-
|
|
5130
|
+
const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-NLK5I2DA.ts")));
|
|
4168
5131
|
pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
|
|
4169
5132
|
registerSwarmTools(pi, controller);
|
|
4170
5133
|
pi.on("session_start", async (event, ctx) => {
|
|
@@ -4176,6 +5139,9 @@ function createPiSwarmExtension(dependencies = {}) {
|
|
|
4176
5139
|
pi.on("turn_end", async (_event, ctx) => {
|
|
4177
5140
|
controller.noteTurnEnd(ctx);
|
|
4178
5141
|
});
|
|
5142
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
5143
|
+
await controller.agentSettled(ctx);
|
|
5144
|
+
});
|
|
4179
5145
|
pi.on("session_info_changed", async (event, ctx) => {
|
|
4180
5146
|
await controller.noteSessionInfoChanged(event.name, ctx);
|
|
4181
5147
|
});
|
|
@@ -4184,7 +5150,16 @@ function createPiSwarmExtension(dependencies = {}) {
|
|
|
4184
5150
|
void controller.relaySteerInput(event.text, ctx);
|
|
4185
5151
|
});
|
|
4186
5152
|
pi.registerCommand("swarm", {
|
|
4187
|
-
description: "Spawn a worker
|
|
5153
|
+
description: "Spawn a worker, manage a local group, or allow follow-up requests",
|
|
5154
|
+
getArgumentCompletions(prefix) {
|
|
5155
|
+
const normalized = prefix.trimStart();
|
|
5156
|
+
const separator = normalized.search(/\s/u);
|
|
5157
|
+
if (separator < 0) return argumentCompletions(["start", "requests"], normalized);
|
|
5158
|
+
if (normalized.slice(0, separator) !== "requests") return null;
|
|
5159
|
+
const value = normalized.slice(separator).trimStart();
|
|
5160
|
+
if (/\s/u.test(value)) return null;
|
|
5161
|
+
return argumentCompletions(["on", "off"], value);
|
|
5162
|
+
},
|
|
4188
5163
|
handler: async (rawArgs, ctx) => {
|
|
4189
5164
|
const args = rawArgs.trim();
|
|
4190
5165
|
if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
|
|
@@ -4194,6 +5169,10 @@ function createPiSwarmExtension(dependencies = {}) {
|
|
|
4194
5169
|
await startGroupDirectly(controller, ctx);
|
|
4195
5170
|
return;
|
|
4196
5171
|
}
|
|
5172
|
+
if (args === "requests on" || args === "requests off") {
|
|
5173
|
+
setRequestPolicyDirectly(controller, ctx, args === "requests on");
|
|
5174
|
+
return;
|
|
5175
|
+
}
|
|
4197
5176
|
if (args) {
|
|
4198
5177
|
await joinDirectInvite(controller, args, ctx);
|
|
4199
5178
|
return;
|
|
@@ -4259,6 +5238,17 @@ async function startGroupDirectly(controller, ctx) {
|
|
|
4259
5238
|
ctx.ui.notify("Started a local Pi Agent Swarm group. You are its lead.", "info");
|
|
4260
5239
|
}
|
|
4261
5240
|
}
|
|
5241
|
+
function argumentCompletions(values, prefix) {
|
|
5242
|
+
const matches = values.filter((value) => value.startsWith(prefix)).map((value) => ({ value, label: value }));
|
|
5243
|
+
return matches.length > 0 ? matches : null;
|
|
5244
|
+
}
|
|
5245
|
+
function setRequestPolicyDirectly(controller, ctx, value) {
|
|
5246
|
+
if (controller.sessionSignal.aborted) return;
|
|
5247
|
+
controller.setAcceptsRequests(ctx, value);
|
|
5248
|
+
if (controller.isCurrent(ctx)) {
|
|
5249
|
+
ctx.ui.notify(`Follow-up agent requests ${value ? "enabled" : "blocked"} for this session.`, "info");
|
|
5250
|
+
}
|
|
5251
|
+
}
|
|
4262
5252
|
function menuSource(controller) {
|
|
4263
5253
|
return {
|
|
4264
5254
|
snapshot: (signal) => controller.snapshot(signal),
|
|
@@ -4290,6 +5280,9 @@ function menuSource(controller) {
|
|
|
4290
5280
|
if (controller.isCurrent(commandContext)) {
|
|
4291
5281
|
commandContext.ui.notify(`Theme set to ${palette}.`, "info");
|
|
4292
5282
|
}
|
|
5283
|
+
},
|
|
5284
|
+
setRequests: async (commandContext, value) => {
|
|
5285
|
+
setRequestPolicyDirectly(controller, commandContext, value);
|
|
4293
5286
|
}
|
|
4294
5287
|
};
|
|
4295
5288
|
}
|