pi-agent-swarm 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 {
@@ -643,15 +647,130 @@ import { constants } from "node:fs";
643
647
  import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
644
648
  import { basename, dirname, join } from "node:path";
645
649
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
650
+
651
+ // src/auto-name.ts
652
+ import { contentText } from "@earendil-works/pi-ai";
653
+ var AUTO_NAME_PREFIX = "MAN-";
654
+ var AUTO_NAME_TURN_THRESHOLD = 3;
655
+ var AUTO_NAME_MAX_TITLE_CHARS = 24;
656
+ var AUTO_NAME_MAX_MESSAGE_CHARS = 500;
657
+ var AUTO_NAME_MAX_CONTEXT_CHARS = 2e3;
658
+ var AUTO_NAME_TIMEOUT_MS = 12e4;
659
+ var AUTO_NAME_MAX_ATTEMPTS = 3;
660
+ var DEFAULT_MANAGER_NAME_PATTERN = /^MANAGER-\S{8}$/u;
661
+ var AUTO_NAME_MODEL_PATTERN = /^[^\s/]+\/[^\s/]+$/u;
662
+ function isDefaultManagerName(name) {
663
+ return name !== void 0 && DEFAULT_MANAGER_NAME_PATTERN.test(name);
664
+ }
665
+ function isAutoNameModel(value) {
666
+ return AUTO_NAME_MODEL_PATTERN.test(value);
667
+ }
668
+ function toAutoName(raw) {
669
+ if (!raw) return void 0;
670
+ const line = safeTerminalLine(raw).replace(/^[\s"'`“”‘’#>*_~-]+/u, "").replace(/[\s"'`“”‘’.,;:!?。,;:!?…·#>*_~-]+$/u, "").trim();
671
+ if (!line) return void 0;
672
+ const title = [...line].slice(0, AUTO_NAME_MAX_TITLE_CHARS).join("");
673
+ return `${AUTO_NAME_PREFIX}${title}`;
674
+ }
675
+ function collectAutoNameMessages(ctx) {
676
+ const messages = [];
677
+ let total = 0;
678
+ for (const entry of ctx.sessionManager.getBranch()) {
679
+ if (messages.length >= AUTO_NAME_TURN_THRESHOLD || total >= AUTO_NAME_MAX_CONTEXT_CHARS) break;
680
+ if (entry.type !== "message") continue;
681
+ const message = entry.message;
682
+ if (!isRecord2(message) || message.role !== "user") continue;
683
+ const content = message.content;
684
+ if (typeof content !== "string" && !Array.isArray(content)) continue;
685
+ const text = safeTerminalLine(contentText(content));
686
+ if (!text) continue;
687
+ const clipped = [...text].slice(0, AUTO_NAME_MAX_MESSAGE_CHARS).join("");
688
+ messages.push(clipped);
689
+ total += clipped.length;
690
+ }
691
+ return messages;
692
+ }
693
+ function buildAutoNamePrompt(messages) {
694
+ return [
695
+ "Summarize the user's goal in this conversation as a short session title.",
696
+ "",
697
+ "Rules:",
698
+ "- Reply with only the title: no quotes, no prefix, no trailing punctuation.",
699
+ "- Use the same language as the user messages.",
700
+ `- Keep it under ${AUTO_NAME_MAX_TITLE_CHARS} characters.`,
701
+ '- Name the task or topic, for example "\u4FEE\u590D\u767B\u5F55\u9875\u6837\u5F0F" or "Add payments API retry".',
702
+ "",
703
+ "User messages:",
704
+ ...messages.map((message, index) => `${index + 1}. ${message}`)
705
+ ].join("\n");
706
+ }
707
+ function resolveAutoNameModel(ctx, configured) {
708
+ if (!configured) return ctx.model;
709
+ const slash = configured.indexOf("/");
710
+ return ctx.modelRegistry.find(configured.slice(0, slash), configured.slice(slash + 1));
711
+ }
712
+ async function completeSessionTitle(ctx, model, prompt, signal) {
713
+ const message = await ctx.modelRegistry.complete(
714
+ model,
715
+ { messages: [{ role: "user", content: prompt, timestamp: Date.now() }] },
716
+ { signal }
717
+ );
718
+ return contentText(message.content);
719
+ }
720
+ var AutoNamer = class {
721
+ turnsSeen = 0;
722
+ attempts = 0;
723
+ userNamed = false;
724
+ reset() {
725
+ this.turnsSeen = 0;
726
+ this.attempts = 0;
727
+ this.userNamed = false;
728
+ }
729
+ /**
730
+ * Record a name change produced outside the auto-namer. A default manager
731
+ * name is the extension's own bootstrap and ignored; anything else means the
732
+ * user (or a handoff) owns the name and auto-naming stays out of the way.
733
+ */
734
+ noteExternalName(name) {
735
+ if (isDefaultManagerName(name)) return;
736
+ this.userNamed = true;
737
+ }
738
+ /**
739
+ * Count one completed turn and report whether an auto-name attempt should
740
+ * start now. Each returned true consumes one attempt; after a successful
741
+ * naming the session no longer carries the default name, so later turns
742
+ * permanently settle via the userNamed path.
743
+ */
744
+ noteTurn(currentName, enabled) {
745
+ if (this.userNamed) return false;
746
+ this.turnsSeen += 1;
747
+ if (this.turnsSeen < AUTO_NAME_TURN_THRESHOLD) return false;
748
+ if (currentName !== void 0 && !isDefaultManagerName(currentName)) {
749
+ this.userNamed = true;
750
+ return false;
751
+ }
752
+ if (!enabled || this.attempts >= AUTO_NAME_MAX_ATTEMPTS) return false;
753
+ this.attempts += 1;
754
+ return true;
755
+ }
756
+ };
757
+ function isRecord2(value) {
758
+ return typeof value === "object" && value !== null && !Array.isArray(value);
759
+ }
760
+
761
+ // src/settings.ts
646
762
  var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
647
763
  var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
648
764
  var DEFAULT_SWARM_SETTINGS = Object.freeze({
765
+ autoName: true,
649
766
  colorPalette: "muted",
650
767
  confirmSessionLaunch: true,
651
768
  externalCommand: "alacritty -e",
652
769
  pinToLeadWorkspace: false
653
770
  });
654
771
  var SETTING_FIELDS = [
772
+ "autoName",
773
+ "autoNameModel",
655
774
  "colorPalette",
656
775
  "confirmSessionLaunch",
657
776
  "externalCommand",
@@ -662,9 +781,21 @@ function swarmSettingsFilePath() {
662
781
  return join(getAgentDir(), SWARM_SETTINGS_FILE);
663
782
  }
664
783
  function normalizeSwarmSettingsDocument(value) {
665
- if (!isRecord2(value)) return void 0;
784
+ if (!isRecord3(value)) return void 0;
666
785
  const settings = { ...DEFAULT_SWARM_SETTINGS };
667
786
  const sources = builtInSources();
787
+ if (Object.hasOwn(value, "autoName")) {
788
+ if (typeof value.autoName !== "boolean") return void 0;
789
+ settings.autoName = value.autoName;
790
+ sources.autoName = "user";
791
+ }
792
+ if (Object.hasOwn(value, "autoNameModel")) {
793
+ if (typeof value.autoNameModel !== "string" || !isAutoNameModel(value.autoNameModel.trim())) {
794
+ return void 0;
795
+ }
796
+ settings.autoNameModel = value.autoNameModel.trim();
797
+ sources.autoNameModel = "user";
798
+ }
668
799
  if (Object.hasOwn(value, "colorPalette")) {
669
800
  if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return void 0;
670
801
  settings.colorPalette = value.colorPalette;
@@ -709,7 +840,7 @@ async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
709
840
  try {
710
841
  const document = JSON.parse(text);
711
842
  const normalized = normalizeSwarmSettingsDocument(document);
712
- if (!normalized || !isRecord2(document)) {
843
+ if (!normalized || !isRecord3(document)) {
713
844
  return invalidLoad(path2, "the document is malformed or contains an invalid setting");
714
845
  }
715
846
  return { kind: "loaded", path: path2, document, ...normalized };
@@ -733,6 +864,8 @@ function createInMemorySwarmSettingsRuntime() {
733
864
  settings: { ...state.settings, ...canonical },
734
865
  sources: {
735
866
  ...state.sources,
867
+ ...canonical.autoName !== void 0 ? { autoName: "user" } : {},
868
+ ...canonical.autoNameModel !== void 0 ? { autoNameModel: "user" } : {},
736
869
  ...canonical.colorPalette !== void 0 ? { colorPalette: "user" } : {},
737
870
  ...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
738
871
  ...canonical.externalCommand ? { externalCommand: "user" } : {},
@@ -806,7 +939,7 @@ function createSwarmSettingsRuntime(options = {}) {
806
939
  };
807
940
  }
808
941
  function normalizePatch(patch) {
809
- if (!isRecord2(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
942
+ if (!isRecord3(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
810
943
  throw new Error("Refusing to update unknown Pi Agent Swarm settings.");
811
944
  }
812
945
  const normalized = normalizeSwarmSettingsDocument(patch);
@@ -891,6 +1024,8 @@ function invalidLoad(path2, reason) {
891
1024
  }
892
1025
  function builtInSources() {
893
1026
  return {
1027
+ autoName: "built-in",
1028
+ autoNameModel: "built-in",
894
1029
  colorPalette: "built-in",
895
1030
  confirmSessionLaunch: "built-in",
896
1031
  externalCommand: "built-in",
@@ -904,7 +1039,7 @@ function freezeState(state) {
904
1039
  sources: Object.freeze({ ...state.sources })
905
1040
  });
906
1041
  }
907
- function isRecord2(value) {
1042
+ function isRecord3(value) {
908
1043
  return typeof value === "object" && value !== null && !Array.isArray(value);
909
1044
  }
910
1045
  function isNodeError(error) {
@@ -915,14 +1050,365 @@ function formatError(error) {
915
1050
  }
916
1051
 
917
1052
  // src/swarm-controller.ts
918
- import { randomBytes as randomBytes5 } from "node:crypto";
919
- import { readFile, realpath as realpath2, rename as rename3, rm as rm5, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
920
- import { join as join7, resolve as resolve5 } from "node:path";
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
+ }
921
1407
 
922
1408
  // src/external.ts
923
1409
  import { spawn } from "node:child_process";
924
1410
  import { existsSync } from "node:fs";
925
- import { join as join2 } from "node:path";
1411
+ import { join as join3 } from "node:path";
926
1412
  var ExternalLaunchError = class extends Error {
927
1413
  constructor(message, splitCreated = false, terminalId) {
928
1414
  super(message);
@@ -1025,7 +1511,7 @@ function isOnPath(binary) {
1025
1511
  if (binary.includes("/")) return existsSync(binary);
1026
1512
  const path2 = process.env.PATH ?? "";
1027
1513
  for (const dir of path2.split(":")) {
1028
- if (dir && existsSync(join2(dir, binary))) return true;
1514
+ if (dir && existsSync(join3(dir, binary))) return true;
1029
1515
  }
1030
1516
  return false;
1031
1517
  }
@@ -1073,7 +1559,8 @@ var SWARM_LAUNCH_ENV_KEYS = [
1073
1559
  "PI_SWARM_ACCEPT_REQUESTS",
1074
1560
  "PI_SWARM_MODEL_PROVIDER",
1075
1561
  "PI_SWARM_MODEL_ID",
1076
- "PI_SWARM_THINKING"
1562
+ "PI_SWARM_THINKING",
1563
+ "PI_SWARM_CONTEXT_RECYCLING"
1077
1564
  ];
1078
1565
  var THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
1079
1566
  var SAFE_ID2 = /^[A-Za-z0-9_-]{1,128}$/u;
@@ -1093,6 +1580,7 @@ function consumeLaunchEnvelope(environment = process.env) {
1093
1580
  const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
1094
1581
  const childColor = optionalHexColor(values.PI_SWARM_COLOR);
1095
1582
  const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
1583
+ const contextRecycling = parseContextRecycling(values.PI_SWARM_CONTEXT_RECYCLING);
1096
1584
  const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
1097
1585
  const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
1098
1586
  if (provider === void 0 !== (id === void 0)) {
@@ -1113,6 +1601,7 @@ function consumeLaunchEnvelope(environment = process.env) {
1113
1601
  ...childName ? { childName } : {},
1114
1602
  ...childColor ? { childColor } : {},
1115
1603
  acceptsRequests,
1604
+ ...contextRecycling ? { contextRecycling } : {},
1116
1605
  ...provider && id ? {
1117
1606
  model: {
1118
1607
  provider,
@@ -1129,6 +1618,7 @@ function launchEnvelopeEnvironment(envelope) {
1129
1618
  PI_SWARM_LAUNCH_ID: envelope.launchId,
1130
1619
  PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
1131
1620
  PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
1621
+ ...envelope.contextRecycling ? { PI_SWARM_CONTEXT_RECYCLING: JSON.stringify(envelope.contextRecycling) } : {},
1132
1622
  ...envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {},
1133
1623
  ...envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {},
1134
1624
  ...envelope.model ? {
@@ -1138,6 +1628,46 @@ function launchEnvelopeEnvironment(envelope) {
1138
1628
  } : {}
1139
1629
  };
1140
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
+ }
1141
1671
  function parseBoolean(value) {
1142
1672
  if (value === void 0 || value === "0") return false;
1143
1673
  if (value === "1") return true;
@@ -1164,12 +1694,12 @@ function optionalHexColor(value) {
1164
1694
  }
1165
1695
 
1166
1696
  // src/launcher.ts
1167
- import { randomBytes as randomBytes2 } from "node:crypto";
1168
- import { lstat as lstat2, open as open2, rm as rm2 } from "node:fs/promises";
1169
- import { join as join3, relative, resolve } from "node:path";
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";
1170
1700
  async function createPiLauncher(invocation, directory, embeddedEnvironment) {
1171
1701
  await assertPrivateDirectory(directory);
1172
- const launcherPath = join3(directory, `launch-${randomBytes2(8).toString("hex")}.sh`);
1702
+ const launcherPath = join4(directory, `launch-${randomBytes3(8).toString("hex")}.sh`);
1173
1703
  assertInside(directory, launcherPath);
1174
1704
  const command = [invocation.command, ...invocation.args];
1175
1705
  for (const value of command) {
@@ -1181,7 +1711,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
1181
1711
  ...environment.map(([key, value]) => `export ${key}=${quoteShell(value)}`)
1182
1712
  ] : [];
1183
1713
  const source = ["#!/bin/sh", ...setup, `exec ${command.map(quoteShell).join(" ")}`, ""].join("\n");
1184
- const handle = await open2(launcherPath, "wx", 448);
1714
+ const handle = await open3(launcherPath, "wx", 448);
1185
1715
  try {
1186
1716
  await handle.writeFile(source, "utf8");
1187
1717
  await handle.sync();
@@ -1189,7 +1719,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
1189
1719
  await handle.close();
1190
1720
  } catch (error) {
1191
1721
  await handle.close().catch(() => void 0);
1192
- await rm2(launcherPath, { force: true }).catch(() => void 0);
1722
+ await rm3(launcherPath, { force: true }).catch(() => void 0);
1193
1723
  throw error;
1194
1724
  }
1195
1725
  let cleaned = false;
@@ -1200,7 +1730,7 @@ async function createPiLauncher(invocation, directory, embeddedEnvironment) {
1200
1730
  if (cleaned) return;
1201
1731
  cleaned = true;
1202
1732
  assertInside(directory, launcherPath);
1203
- await rm2(launcherPath, { force: true });
1733
+ await rm3(launcherPath, { force: true });
1204
1734
  }
1205
1735
  };
1206
1736
  }
@@ -1232,7 +1762,7 @@ async function assertPrivateDirectory(path2) {
1232
1762
  }
1233
1763
  }
1234
1764
  function assertInside(parent, candidate) {
1235
- const rel = relative(resolve(parent), resolve(candidate));
1765
+ const rel = relative(resolve2(parent), resolve2(candidate));
1236
1766
  if (!rel || rel === ".." || rel.startsWith("../")) {
1237
1767
  throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
1238
1768
  }
@@ -1293,19 +1823,19 @@ function readManifest(packageDirectory) {
1293
1823
  } catch {
1294
1824
  throw resolutionError(packageDirectory, "the package manifest is unavailable or invalid");
1295
1825
  }
1296
- if (!isRecord3(value) || value.name !== CORE_PACKAGE_NAME) {
1826
+ if (!isRecord4(value) || value.name !== CORE_PACKAGE_NAME) {
1297
1827
  throw resolutionError(packageDirectory, "the package manifest has an unexpected package name");
1298
1828
  }
1299
1829
  return value;
1300
1830
  }
1301
1831
  function resolveDeclaredBin(packageDirectory, manifest) {
1302
1832
  const bin = manifest.bin;
1303
- const piBin = isRecord3(bin) ? bin.pi : void 0;
1833
+ const piBin = isRecord4(bin) ? bin.pi : void 0;
1304
1834
  if (typeof piBin !== "string" || !piBin.trim()) {
1305
1835
  throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
1306
1836
  }
1307
1837
  const candidate = path.resolve(packageDirectory, piBin);
1308
- if (path.isAbsolute(piBin) || !isWithin(packageDirectory, candidate)) {
1838
+ if (path.isAbsolute(piBin) || !isWithin2(packageDirectory, candidate)) {
1309
1839
  throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
1310
1840
  }
1311
1841
  return candidate;
@@ -1314,7 +1844,7 @@ function resolveExistingFile(packageDirectory, candidate, reason) {
1314
1844
  try {
1315
1845
  const resolved = fs.realpathSync(candidate);
1316
1846
  if (!fs.statSync(resolved).isFile()) throw new Error("not a file");
1317
- if (!isWithin(packageDirectory, resolved)) {
1847
+ if (!isWithin2(packageDirectory, resolved)) {
1318
1848
  throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
1319
1849
  }
1320
1850
  return resolved;
@@ -1343,7 +1873,7 @@ function resolveStandaloneExecutable(packageDirectory, runtime) {
1343
1873
  }
1344
1874
  return resolved;
1345
1875
  }
1346
- function isWithin(parent, candidate) {
1876
+ function isWithin2(parent, candidate) {
1347
1877
  const relative4 = path.relative(parent, candidate);
1348
1878
  return relative4 === "" || !relative4.startsWith(`..${path.sep}`) && relative4 !== ".." && !path.isAbsolute(relative4);
1349
1879
  }
@@ -1353,7 +1883,7 @@ function resolutionError(packageDirectory, reason) {
1353
1883
  `Unable to resolve the Pi CLI from ${JSON.stringify(displayed)}: ${reason}. Reinstall the matching Pi core package before spawning a session.`
1354
1884
  );
1355
1885
  }
1356
- function isRecord3(value) {
1886
+ function isRecord4(value) {
1357
1887
  return typeof value === "object" && value !== null && !Array.isArray(value);
1358
1888
  }
1359
1889
 
@@ -1545,10 +2075,10 @@ function collectAncestors(pid, readPpid) {
1545
2075
  }
1546
2076
  function readProcPpid(pid) {
1547
2077
  try {
1548
- const stat3 = readFileSync2(`/proc/${pid}/stat`, "utf8");
1549
- const close = stat3.lastIndexOf(")");
2078
+ const stat4 = readFileSync2(`/proc/${pid}/stat`, "utf8");
2079
+ const close = stat4.lastIndexOf(")");
1550
2080
  if (close < 0) return void 0;
1551
- const fields = stat3.slice(close + 2).split(" ");
2081
+ const fields = stat4.slice(close + 2).split(" ");
1552
2082
  const ppid = Number(fields[1]);
1553
2083
  return Number.isInteger(ppid) && ppid > 0 ? ppid : void 0;
1554
2084
  } catch {
@@ -1560,12 +2090,12 @@ function quoteI3Value(value) {
1560
2090
  }
1561
2091
  async function abortableSleep(milliseconds, signal) {
1562
2092
  throwIfAborted3(signal, "Pi Agent Swarm i3 workspace wait was aborted");
1563
- await new Promise((resolve6, reject) => {
2093
+ await new Promise((resolve7, reject) => {
1564
2094
  const finish = (error) => {
1565
2095
  clearTimeout(timer);
1566
2096
  signal?.removeEventListener("abort", abort);
1567
2097
  if (error) reject(error);
1568
- else resolve6();
2098
+ else resolve7();
1569
2099
  };
1570
2100
  const timer = setTimeout(() => finish(), milliseconds);
1571
2101
  const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
@@ -1603,17 +2133,17 @@ function createTerminalLaunchError(message, splitCreated, terminalId) {
1603
2133
  }
1604
2134
 
1605
2135
  // src/transport.ts
1606
- import { randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
2136
+ import { randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
1607
2137
  import { constants as constants3 } from "node:fs";
1608
- import { chmod as chmod2, lstat as lstat4, open as open5, opendir as opendir2, rm as rm4 } from "node:fs/promises";
2138
+ import { chmod as chmod2, lstat as lstat4, open as open6, opendir as opendir2, rm as rm5 } from "node:fs/promises";
1609
2139
  import { createServer } from "node:net";
1610
- import { basename as basename4, dirname as dirname4, join as join6, resolve as resolve4 } from "node:path";
2140
+ import { basename as basename4, dirname as dirname5, join as join7, resolve as resolve5 } from "node:path";
1611
2141
 
1612
2142
  // src/runtime-directory.ts
1613
- import { randomBytes as randomBytes3 } from "node:crypto";
1614
- import { chmod, lstat as lstat3, mkdir as mkdir2, open as open3, opendir, realpath, rename as rename2, rm as rm3, stat } from "node:fs/promises";
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";
1615
2145
  import { tmpdir } from "node:os";
1616
- import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative3, resolve as resolve3 } from "node:path";
2146
+ import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative3, resolve as resolve4 } from "node:path";
1617
2147
  var MAX_UNIX_SOCKET_PATH_BYTES = 103;
1618
2148
  var MAX_MANIFEST_BYTES = 8 * 1024;
1619
2149
  var ORPHAN_GRACE_MS = 6e4;
@@ -1629,21 +2159,21 @@ function defaultRuntimeBaseDirectory() {
1629
2159
  throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
1630
2160
  }
1631
2161
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
1632
- if (process.platform === "darwin") return join5("/tmp", `pi-swarm-${uid}`);
2162
+ if (process.platform === "darwin") return join6("/tmp", `pi-swarm-${uid}`);
1633
2163
  const runtime = process.env.XDG_RUNTIME_DIR;
1634
- if (runtime && isAbsolute2(runtime) && Buffer.byteLength(join5(runtime, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES) {
1635
- return join5(runtime, "pi-swarm");
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");
1636
2166
  }
1637
- const systemTmp = resolve3(tmpdir());
1638
- const candidate = join5(systemTmp, `pi-swarm-${uid}`);
1639
- const socketCandidate = join5(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
1640
- return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join5("/tmp", `pi-swarm-${uid}`);
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}`);
1641
2171
  }
1642
2172
  async function ensureGroupRuntimeDirectory(groupId, options = {}) {
1643
2173
  if (!SAFE_GROUP_ID.test(groupId)) throw new Error("Pi Agent Swarm runtime group id is invalid");
1644
- const baseDirectory = resolve3(options.baseDirectory ?? defaultRuntimeBaseDirectory());
1645
- const directory = join5(baseDirectory, groupId);
1646
- const longestSocket = join5(directory, `${"x".repeat(24)}.sock`);
2174
+ const baseDirectory = resolve4(options.baseDirectory ?? defaultRuntimeBaseDirectory());
2175
+ const directory = join6(baseDirectory, groupId);
2176
+ const longestSocket = join6(directory, `${"x".repeat(24)}.sock`);
1647
2177
  if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
1648
2178
  throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
1649
2179
  }
@@ -1653,7 +2183,7 @@ async function ensureGroupRuntimeDirectory(groupId, options = {}) {
1653
2183
  }
1654
2184
  function createEndpointPaths(directory, endpointId) {
1655
2185
  if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
1656
- const socketPath = join5(directory, `${endpointId}.sock`);
2186
+ const socketPath = join6(directory, `${endpointId}.sock`);
1657
2187
  if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
1658
2188
  throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
1659
2189
  }
@@ -1661,14 +2191,14 @@ function createEndpointPaths(directory, endpointId) {
1661
2191
  directory,
1662
2192
  endpointId,
1663
2193
  socketPath,
1664
- manifestPath: join5(directory, `${endpointId}.json`)
2194
+ manifestPath: join6(directory, `${endpointId}.json`)
1665
2195
  };
1666
2196
  }
1667
2197
  function randomEndpointId() {
1668
- return randomBytes3(12).toString("hex");
2198
+ return randomBytes4(12).toString("hex");
1669
2199
  }
1670
2200
  async function publishManifest(manifestPath, manifest) {
1671
- const parent = dirname3(manifestPath);
2201
+ const parent = dirname4(manifestPath);
1672
2202
  await assertPrivateDirectory2(parent);
1673
2203
  assertOwnedPath(parent, manifestPath, ".json");
1674
2204
  const body = `${JSON.stringify(manifest)}
@@ -1676,19 +2206,19 @@ async function publishManifest(manifestPath, manifest) {
1676
2206
  if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
1677
2207
  throw new Error("Pi Agent Swarm endpoint manifest is too large");
1678
2208
  }
1679
- const temporaryPath = join5(parent, `.${basename3(manifestPath)}.${randomBytes3(8).toString("hex")}.tmp`);
2209
+ const temporaryPath = join6(parent, `.${basename3(manifestPath)}.${randomBytes4(8).toString("hex")}.tmp`);
1680
2210
  let handle;
1681
2211
  try {
1682
- handle = await open3(temporaryPath, "wx", 384);
2212
+ handle = await open4(temporaryPath, "wx", 384);
1683
2213
  await handle.writeFile(body, "utf8");
1684
2214
  await handle.sync();
1685
2215
  await handle.close();
1686
2216
  handle = void 0;
1687
- await rename2(temporaryPath, manifestPath);
2217
+ await rename3(temporaryPath, manifestPath);
1688
2218
  await chmod(manifestPath, 384);
1689
2219
  } finally {
1690
2220
  await handle?.close().catch(() => void 0);
1691
- await rm3(temporaryPath, { force: true }).catch(() => void 0);
2221
+ await rm4(temporaryPath, { force: true }).catch(() => void 0);
1692
2222
  }
1693
2223
  }
1694
2224
  async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
@@ -1714,7 +2244,7 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
1714
2244
  for (const name of names) {
1715
2245
  const socketMatch = SAFE_SOCKET_NAME.exec(name);
1716
2246
  if (socketMatch) {
1717
- const manifestPath = join5(directory, `${socketMatch[1]}.json`);
2247
+ const manifestPath = join6(directory, `${socketMatch[1]}.json`);
1718
2248
  if (!await pathExists(manifestPath)) {
1719
2249
  if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
1720
2250
  }
@@ -1731,15 +2261,15 @@ async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
1731
2261
  async function removeOwnedEndpoint(paths) {
1732
2262
  for (const path2 of [paths.manifestPath, paths.socketPath]) {
1733
2263
  assertOwnedPath(paths.directory, path2);
1734
- await rm3(path2, { force: true }).catch(() => void 0);
2264
+ await rm4(path2, { force: true }).catch(() => void 0);
1735
2265
  }
1736
2266
  }
1737
2267
  function endpointIdFromManifestName(name) {
1738
2268
  return SAFE_MANIFEST_NAME.exec(name)?.[1];
1739
2269
  }
1740
2270
  function assertOwnedPath(parent, candidate, suffix) {
1741
- const resolvedParent = resolve3(parent);
1742
- const resolvedCandidate = resolve3(candidate);
2271
+ const resolvedParent = resolve4(parent);
2272
+ const resolvedCandidate = resolve4(candidate);
1743
2273
  const rel = relative3(resolvedParent, resolvedCandidate);
1744
2274
  if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
1745
2275
  throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
@@ -1749,7 +2279,7 @@ function assertOwnedPath(parent, candidate, suffix) {
1749
2279
  }
1750
2280
  }
1751
2281
  async function removeStaleOwnedEntry(directory, name, kind, now) {
1752
- const path2 = join5(directory, name);
2282
+ const path2 = join6(directory, name);
1753
2283
  assertOwnedPath(directory, path2);
1754
2284
  try {
1755
2285
  const first = await lstat3(path2, { bigint: true });
@@ -1760,7 +2290,7 @@ async function removeStaleOwnedEntry(directory, name, kind, now) {
1760
2290
  if (current.dev !== first.dev || current.ino !== first.ino || current.mtimeMs !== first.mtimeMs || (kind === "file" ? !current.isFile() : !current.isSocket())) {
1761
2291
  return false;
1762
2292
  }
1763
- await rm3(path2);
2293
+ await rm4(path2);
1764
2294
  return true;
1765
2295
  } catch (error) {
1766
2296
  if (isMissing(error)) return false;
@@ -1777,7 +2307,7 @@ async function ensurePrivateDirectory(path2) {
1777
2307
  await assertPrivateDirectory2(path2);
1778
2308
  } catch (error) {
1779
2309
  if (!isMissing(error)) throw error;
1780
- await mkdir2(path2, { recursive: true, mode: 448 });
2310
+ await mkdir3(path2, { recursive: true, mode: 448 });
1781
2311
  await chmod(path2, 448);
1782
2312
  await assertPrivateDirectory2(path2);
1783
2313
  }
@@ -1791,7 +2321,7 @@ async function assertPrivateDirectory2(path2) {
1791
2321
  throw new Error("Pi Agent Swarm runtime directory permissions are not private");
1792
2322
  }
1793
2323
  const resolved = await realpath(path2);
1794
- const resolvedInfo = await stat(resolved);
2324
+ const resolvedInfo = await stat2(resolved);
1795
2325
  assertOwner(resolvedInfo.uid);
1796
2326
  }
1797
2327
  function assertOwner(uid) {
@@ -1813,7 +2343,7 @@ function isMissing(error) {
1813
2343
 
1814
2344
  // src/transport-io.ts
1815
2345
  import { constants as constants2 } from "node:fs";
1816
- import { open as open4 } from "node:fs/promises";
2346
+ import { open as open5 } from "node:fs/promises";
1817
2347
  import { createConnection } from "node:net";
1818
2348
  import { TextDecoder as TextDecoder3 } from "node:util";
1819
2349
  function requestFrame(endpointPath, frame, signal, timeoutMs) {
@@ -1908,7 +2438,7 @@ function closeSocketServer(server) {
1908
2438
  });
1909
2439
  }
1910
2440
  async function readBoundedUtf8(path2, maximum) {
1911
- const handle = await open4(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
2441
+ const handle = await open5(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
1912
2442
  try {
1913
2443
  return await readBoundedHandleUtf8(handle, maximum);
1914
2444
  } finally {
@@ -2063,11 +2593,11 @@ var SwarmTransport = class {
2063
2593
  while (cursor < manifestResult.records.length && !operationSignal.aborted) {
2064
2594
  const index = cursor;
2065
2595
  cursor += 1;
2066
- const record = manifestResult.records[index];
2067
- if (!record || record.manifest.endpointId === this.peer.endpointId) continue;
2596
+ const record2 = manifestResult.records[index];
2597
+ if (!record2 || record2.manifest.endpointId === this.peer.endpointId) continue;
2068
2598
  try {
2069
2599
  const response = await this.request(
2070
- record,
2600
+ record2,
2071
2601
  { kind: "describe" },
2072
2602
  operationSignal,
2073
2603
  this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
@@ -2075,7 +2605,7 @@ var SwarmTransport = class {
2075
2605
  if (response.payload.kind !== "description") {
2076
2606
  throw new Error("Pi Agent Swarm peer returned an invalid description response");
2077
2607
  }
2078
- assertDescriptionMatchesManifest(response.payload.peer, record);
2608
+ assertDescriptionMatchesManifest(response.payload.peer, record2);
2079
2609
  if (response.payload.peer.sessionId === this.peer.sessionId) {
2080
2610
  addIssue(issues, {
2081
2611
  code: "identity_conflict",
@@ -2084,22 +2614,22 @@ var SwarmTransport = class {
2084
2614
  });
2085
2615
  continue;
2086
2616
  }
2087
- discovered.push({ peer: response.payload.peer, record });
2617
+ discovered.push({ peer: response.payload.peer, record: record2 });
2088
2618
  } catch (error) {
2089
2619
  if (signal?.aborted || this.lifecycle.signal.aborted) throw error;
2090
2620
  if (deadline.signal.aborted) break;
2091
2621
  if (isDeadEndpointError(error)) {
2092
2622
  addIssue(issues, {
2093
2623
  code: "peer_unreachable",
2094
- sessionId: record.manifest.sessionId,
2095
- endpointId: record.manifest.endpointId
2624
+ sessionId: record2.manifest.sessionId,
2625
+ endpointId: record2.manifest.endpointId
2096
2626
  });
2097
- await this.removeStaleRecord(record);
2627
+ await this.removeStaleRecord(record2);
2098
2628
  } else if (!isAbortError(error)) {
2099
2629
  addIssue(issues, {
2100
2630
  code: "protocol_error",
2101
- sessionId: record.manifest.sessionId,
2102
- endpointId: record.manifest.endpointId
2631
+ sessionId: record2.manifest.sessionId,
2632
+ endpointId: record2.manifest.endpointId
2103
2633
  });
2104
2634
  }
2105
2635
  }
@@ -2170,12 +2700,12 @@ var SwarmTransport = class {
2170
2700
  if (candidates.length === 0) {
2171
2701
  throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
2172
2702
  }
2173
- const record = candidates.length === 1 ? candidates[0] : await this.resolveUniqueTarget(targetSessionId, candidates, signal);
2174
- if (!record) throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
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`);
2175
2705
  let response;
2176
2706
  try {
2177
2707
  response = await this.request(
2178
- record,
2708
+ record2,
2179
2709
  {
2180
2710
  kind: "message",
2181
2711
  message,
@@ -2184,7 +2714,7 @@ var SwarmTransport = class {
2184
2714
  signal
2185
2715
  );
2186
2716
  } catch (error) {
2187
- if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
2717
+ if (isDeadEndpointError(error)) await this.removeStaleRecord(record2);
2188
2718
  throw error;
2189
2719
  }
2190
2720
  if (response.payload.kind !== "ack") {
@@ -2358,6 +2888,14 @@ var SwarmTransport = class {
2358
2888
  }
2359
2889
  }
2360
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
+ }
2361
2899
  if (message.kind === "shutdown" && !(this.options.authorizeShutdown?.(message) ?? false)) {
2362
2900
  return {
2363
2901
  kind: "ack",
@@ -2367,6 +2905,8 @@ var SwarmTransport = class {
2367
2905
  };
2368
2906
  }
2369
2907
  if (message.mode === "request" && !this.peer.acceptsRequests) {
2908
+ const lifecycleRejection = this.options.rejectRequest?.(message);
2909
+ if (lifecycleRejection) return lifecycleRejection;
2370
2910
  return {
2371
2911
  kind: "ack",
2372
2912
  status: "rejected",
@@ -2443,7 +2983,7 @@ var SwarmTransport = class {
2443
2983
  }
2444
2984
  try {
2445
2985
  records.push(
2446
- await readManifest2(paths.directory, resolve4(paths.directory, entry.name), endpointId, this.options.group)
2986
+ await readManifest2(paths.directory, resolve5(paths.directory, entry.name), endpointId, this.options.group)
2447
2987
  );
2448
2988
  } catch {
2449
2989
  addIssue(issues, { code: "invalid_manifest", endpointId });
@@ -2456,15 +2996,15 @@ var SwarmTransport = class {
2456
2996
  records.sort((left, right) => left.manifest.endpointId.localeCompare(right.manifest.endpointId));
2457
2997
  return { records, issues, scannedEntries, saturated };
2458
2998
  }
2459
- async request(record, payload, signal, timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) {
2999
+ async request(record2, payload, signal, timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) {
2460
3000
  throwIfAborted4(signal, "Pi Agent Swarm request aborted");
2461
3001
  const requestId = randomId("req");
2462
3002
  const frame = createSignedFrame(
2463
3003
  {
2464
3004
  groupId: this.options.group.id,
2465
3005
  requestId,
2466
- targetSessionId: record.manifest.sessionId,
2467
- targetEndpointId: record.manifest.endpointId,
3006
+ targetSessionId: record2.manifest.sessionId,
3007
+ targetEndpointId: record2.manifest.endpointId,
2468
3008
  senderSessionId: this.peer.sessionId,
2469
3009
  senderEndpointId: this.peer.endpointId,
2470
3010
  issuedAt: this.now(),
@@ -2473,7 +3013,7 @@ var SwarmTransport = class {
2473
3013
  },
2474
3014
  this.options.group.secret
2475
3015
  );
2476
- const value = await requestFrame(record.socketPath, frame, signal, timeoutMs);
3016
+ const value = await requestFrame(record2.socketPath, frame, signal, timeoutMs);
2477
3017
  throwIfAborted4(signal, "Pi Agent Swarm request aborted");
2478
3018
  const response = verifySignedFrame(value, this.options.group.secret, {
2479
3019
  expectedGroupId: this.options.group.id,
@@ -2482,7 +3022,7 @@ var SwarmTransport = class {
2482
3022
  now: this.now(),
2483
3023
  replay: this.responseReplay
2484
3024
  });
2485
- if (response.requestId !== requestId || response.senderSessionId !== record.manifest.sessionId || response.senderEndpointId !== record.manifest.endpointId) {
3025
+ if (response.requestId !== requestId || response.senderSessionId !== record2.manifest.sessionId || response.senderEndpointId !== record2.manifest.endpointId) {
2486
3026
  throw new Error("Pi Agent Swarm response identity does not match its request");
2487
3027
  }
2488
3028
  return response;
@@ -2490,20 +3030,20 @@ var SwarmTransport = class {
2490
3030
  async resolveUniqueTarget(targetSessionId, candidates, signal) {
2491
3031
  const live = [];
2492
3032
  await Promise.all(
2493
- candidates.map(async (record) => {
3033
+ candidates.map(async (record2) => {
2494
3034
  try {
2495
3035
  const response = await this.request(
2496
- record,
3036
+ record2,
2497
3037
  { kind: "describe" },
2498
3038
  signal,
2499
3039
  this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
2500
3040
  );
2501
3041
  if (response.payload.kind !== "description") return;
2502
- assertDescriptionMatchesManifest(response.payload.peer, record);
2503
- live.push(record);
3042
+ assertDescriptionMatchesManifest(response.payload.peer, record2);
3043
+ live.push(record2);
2504
3044
  } catch (error) {
2505
3045
  if (isAbortError(error)) throw error;
2506
- if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
3046
+ if (isDeadEndpointError(error)) await this.removeStaleRecord(record2);
2507
3047
  }
2508
3048
  })
2509
3049
  );
@@ -2512,15 +3052,15 @@ var SwarmTransport = class {
2512
3052
  }
2513
3053
  return live[0];
2514
3054
  }
2515
- async removeStaleRecord(record) {
3055
+ async removeStaleRecord(record2) {
2516
3056
  try {
2517
- const current = await readBoundedUtf8(record.manifestPath, MAX_MANIFEST_BYTES);
2518
- if (current !== record.raw) return;
2519
- await rm4(record.manifestPath, { force: true });
2520
- if (record.socketIdentity) {
2521
- const info = await lstat4(record.socketPath, { bigint: true }).catch(() => void 0);
2522
- if (info?.isSocket() && info.dev === record.socketIdentity.dev && info.ino === record.socketIdentity.ino) {
2523
- await rm4(record.socketPath, { force: true });
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 });
2524
3064
  }
2525
3065
  }
2526
3066
  } catch {
@@ -2563,7 +3103,7 @@ async function assertEndpointPathsAvailable(paths) {
2563
3103
  }
2564
3104
  async function readManifest2(directory, manifestPath, endpointId, group) {
2565
3105
  assertOwnedPath(directory, manifestPath, ".json");
2566
- const handle = await open5(manifestPath, constants3.O_RDONLY | constants3.O_NOFOLLOW);
3106
+ const handle = await open6(manifestPath, constants3.O_RDONLY | constants3.O_NOFOLLOW);
2567
3107
  try {
2568
3108
  const info = await handle.stat({ bigint: true });
2569
3109
  if (!info.isFile() || info.size > BigInt(MAX_MANIFEST_BYTES)) {
@@ -2580,8 +3120,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
2580
3120
  expectedGroupId: group.id,
2581
3121
  expectedEndpointId: endpointId
2582
3122
  });
2583
- const socketPath = join6(directory, manifest.socketName);
2584
- if (dirname4(resolve4(socketPath)) !== resolve4(directory)) {
3123
+ const socketPath = join7(directory, manifest.socketName);
3124
+ if (dirname5(resolve5(socketPath)) !== resolve5(directory)) {
2585
3125
  throw new Error("Pi Agent Swarm endpoint socket path is invalid");
2586
3126
  }
2587
3127
  const socketInfo = await lstat4(socketPath, { bigint: true }).catch(() => void 0);
@@ -2605,8 +3145,8 @@ async function readManifest2(directory, manifestPath, endpointId, group) {
2605
3145
  await handle.close();
2606
3146
  }
2607
3147
  }
2608
- function assertDescriptionMatchesManifest(peer, record) {
2609
- if (peer.sessionId !== record.manifest.sessionId || peer.endpointId !== record.manifest.endpointId || peer.pid !== record.manifest.pid) {
3148
+ function assertDescriptionMatchesManifest(peer, record2) {
3149
+ if (peer.sessionId !== record2.manifest.sessionId || peer.endpointId !== record2.manifest.endpointId || peer.pid !== record2.manifest.pid) {
2610
3150
  throw new Error("Pi Agent Swarm peer identity does not match its endpoint manifest");
2611
3151
  }
2612
3152
  }
@@ -2629,7 +3169,7 @@ function addIssue(issues, issue) {
2629
3169
  issues.push(issue);
2630
3170
  }
2631
3171
  function randomId(prefix) {
2632
- return `${prefix}_${randomBytes4(12).toString("hex")}`;
3172
+ return `${prefix}_${randomBytes5(12).toString("hex")}`;
2633
3173
  }
2634
3174
  function combineSignals(...signals) {
2635
3175
  const concrete = signals.filter((signal) => signal !== void 0);
@@ -2693,9 +3233,9 @@ function defaultSwarmControllerDependencies(pi) {
2693
3233
  resolveInvocation: (args) => resolvePiInvocation(args),
2694
3234
  createLauncher: (invocation, directory, embeddedEnvironment) => createPiLauncher(invocation, directory, embeddedEnvironment),
2695
3235
  realpath: realpath2,
2696
- isDirectory: async (value) => (await stat2(value)).isDirectory(),
3236
+ isDirectory: async (value) => (await stat3(value)).isDirectory(),
2697
3237
  now: Date.now,
2698
- randomId: (prefix) => `${prefix}_${randomBytes5(16).toString("hex")}`,
3238
+ randomId: (prefix) => `${prefix}_${randomBytes6(16).toString("hex")}`,
2699
3239
  sleep: abortableSleep2,
2700
3240
  launchTimeoutMs: DEFAULT_LAUNCH_TIMEOUT_MS,
2701
3241
  environment: process.env,
@@ -2723,11 +3263,20 @@ var SwarmController = class {
2723
3263
  leadSessionId;
2724
3264
  /** A human-started session is the default lead of its own (not yet started) group. */
2725
3265
  defaultLead = false;
3266
+ autoNamer = new AutoNamer();
3267
+ /** Auto-naming applies only to human-started sessions, never to spawned children. */
3268
+ autoNameEligible = false;
3269
+ /** Set while the auto-namer applies its own name so the change is not read as manual. */
3270
+ applyingAutoName;
3271
+ autoNameInFlight = false;
2726
3272
  leadWatcher;
2727
3273
  resizeListener = () => this.onTerminalResize();
2728
3274
  resizeWatching = false;
2729
3275
  pendingKickoffIds = /* @__PURE__ */ new Set();
2730
3276
  relayChain = Promise.resolve();
3277
+ recycling;
3278
+ recyclingChain = Promise.resolve();
3279
+ successorLaunches = /* @__PURE__ */ new Map();
2731
3280
  async sessionStart(event, ctx) {
2732
3281
  if (this.activeSessionManager && this.activeSessionManager !== ctx.sessionManager) {
2733
3282
  await this.cleanupActive(false);
@@ -2740,8 +3289,15 @@ var SwarmController = class {
2740
3289
  this.parentSessionId = void 0;
2741
3290
  this.leadSessionId = void 0;
2742
3291
  this.defaultLead = false;
3292
+ this.autoNamer.reset();
3293
+ this.autoNameEligible = false;
3294
+ this.applyingAutoName = void 0;
3295
+ this.autoNameInFlight = false;
2743
3296
  this.pendingKickoffIds.clear();
2744
3297
  this.relayChain = Promise.resolve();
3298
+ this.recycling = void 0;
3299
+ this.recyclingChain = Promise.resolve();
3300
+ this.successorLaunches.clear();
2745
3301
  this.startLeadWatcher();
2746
3302
  this.startResizeWatcher();
2747
3303
  const owner = ctx.sessionManager;
@@ -2767,6 +3323,7 @@ var SwarmController = class {
2767
3323
  this.pi.setSessionName(`MANAGER-${ctx.sessionManager.getSessionId().slice(0, 8)}`);
2768
3324
  }
2769
3325
  this.defaultLead = true;
3326
+ this.autoNameEligible = true;
2770
3327
  await this.renderFooterStatus(ctx);
2771
3328
  return;
2772
3329
  }
@@ -2800,6 +3357,10 @@ var SwarmController = class {
2800
3357
  handoff?.kickoffConsumed ?? false
2801
3358
  )
2802
3359
  );
3360
+ const recyclingLaunch = envelope?.contextRecycling ?? handoff?.contextRecycling;
3361
+ if (recyclingLaunch && this.parentSessionId) {
3362
+ await this.initializeContextRecycling(ctx, recyclingLaunch, this.parentSessionId);
3363
+ }
2803
3364
  } catch (error) {
2804
3365
  if (this.isCurrent(owner, ownerGeneration)) {
2805
3366
  this.notify(ctx, `Pi Agent Swarm could not join the launch group: ${safeError(error)}`, "error");
@@ -2832,6 +3393,7 @@ var SwarmController = class {
2832
3393
  ...peerName ? { name: peerName } : {},
2833
3394
  ...peerColor ? { color: peerColor } : {},
2834
3395
  ...this.parentSessionId ? { parentSessionId: this.parentSessionId } : {},
3396
+ ...this.recycling ? { contextRecycling: this.recycling.launch } : {},
2835
3397
  expiresAt: this.deps.now() + RELOAD_HANDOFF_TTL_MS
2836
3398
  });
2837
3399
  }
@@ -2868,6 +3430,10 @@ var SwarmController = class {
2868
3430
  } catch {
2869
3431
  }
2870
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
+ });
2871
3437
  return this.snapshot(signal);
2872
3438
  });
2873
3439
  }
@@ -2899,9 +3465,235 @@ var SwarmController = class {
2899
3465
  setAcceptsRequests(ctx, value) {
2900
3466
  this.assertCurrentContext(ctx);
2901
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
+ }
2902
3471
  this.membership.rollbackLaunch = void 0;
2903
3472
  this.membership.acceptsRequests = value;
2904
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);
2905
3697
  }
2906
3698
  async snapshot(signal) {
2907
3699
  if (!this.activeSessionManager || this.controller.signal.aborted) throw staleError();
@@ -2936,7 +3728,10 @@ var SwarmController = class {
2936
3728
  const membership = this.membership;
2937
3729
  if (!membership) throw new Error("Pi Agent Swarm is not connected");
2938
3730
  membership.rollbackLaunch = void 0;
2939
- if (Buffer.byteLength(options.text) > MAX_MESSAGE_BYTES) {
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) {
2940
3735
  throw new Error("Pi Agent Swarm message is too large");
2941
3736
  }
2942
3737
  const self = membership.transport.peerDescription;
@@ -2948,7 +3743,7 @@ var SwarmController = class {
2948
3743
  fromCwd: self.cwd,
2949
3744
  toSessionId: options.targetSessionId,
2950
3745
  mode: options.mode,
2951
- text: options.text,
3746
+ text: `${metricPrefix}${options.text}`,
2952
3747
  issuedAt,
2953
3748
  expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
2954
3749
  ...options.replyTo ? { replyTo: options.replyTo } : {}
@@ -2960,6 +3755,10 @@ var SwarmController = class {
2960
3755
  if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
2961
3756
  throw staleError();
2962
3757
  }
3758
+ if (acknowledgement.accepted && this.recycling && options.mode === "reply") {
3759
+ this.recycling.taskStatus = options.taskStatus ?? "working";
3760
+ this.recycling.handoff = options.handoff;
3761
+ }
2963
3762
  return { message, acknowledgement };
2964
3763
  }
2965
3764
  /** Send a control-plane shutdown request asking the target peer to exit gracefully. */
@@ -3005,6 +3804,12 @@ var SwarmController = class {
3005
3804
  await this.settings.flush();
3006
3805
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
3007
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);
3008
3813
  const direction = input.direction ?? "right";
3009
3814
  const windowLabel = "window";
3010
3815
  const launchLayoutLine = "External terminal window (the window manager places it)";
@@ -3046,7 +3851,7 @@ var SwarmController = class {
3046
3851
  );
3047
3852
  const terminalVersion = await terminalAdapter.assertAvailable(operationSignal);
3048
3853
  if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
3049
- if (launchSettings.confirmSessionLaunch) {
3854
+ if (launchSettings.confirmSessionLaunch && !input.recyclingLaunch) {
3050
3855
  const confirmed = await ctx.ui.confirm(
3051
3856
  "Create a new Pi session?",
3052
3857
  [
@@ -3055,6 +3860,8 @@ var SwarmController = class {
3055
3860
  `Color: ${safeTerminalLine(color)}`,
3056
3861
  `Cwd: ${safeTerminalLine(cwd)}`,
3057
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"}.`,
3058
3865
  "The child may spend model tokens and edit the same workspace concurrently."
3059
3866
  ].join("\n"),
3060
3867
  { signal: operationSignal }
@@ -3082,7 +3889,8 @@ var SwarmController = class {
3082
3889
  kickoffCapability,
3083
3890
  childName: name,
3084
3891
  childColor: color,
3085
- acceptsRequests: false,
3892
+ acceptsRequests: input.allowRequests === true,
3893
+ ...recyclingLaunch ? { contextRecycling: recyclingLaunch } : {},
3086
3894
  ...childModel ? { model: childModel } : {}
3087
3895
  };
3088
3896
  const launchEnvironment = launchEnvelopeEnvironment(envelope);
@@ -3146,7 +3954,8 @@ var SwarmController = class {
3146
3954
  cwd: child.cwd,
3147
3955
  terminalId,
3148
3956
  terminalVersion: actualTerminalVersion,
3149
- kickoffAccepted
3957
+ kickoffAccepted,
3958
+ ...recyclingLaunch ? { lineageId: recyclingLaunch.lineageId } : {}
3150
3959
  };
3151
3960
  } catch (error) {
3152
3961
  const partial = splitCreated || isTerminalLaunchError(error) && error.splitCreated;
@@ -3225,11 +4034,34 @@ var SwarmController = class {
3225
4034
  ...kickoffCapability ? { kickoffCapability } : {},
3226
4035
  kickoffConsumed: acceptedKickoff,
3227
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
+ },
3228
4049
  onMessage: async (message, deliverySignal) => {
3229
4050
  if (deliverySignal?.aborted || !this.isCurrent(owner, ownerGeneration)) return;
3230
4051
  const activeContext = this.activeContext;
3231
4052
  if (message.kind === "shutdown") {
3232
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
+ }
3233
4065
  activeContext?.shutdown();
3234
4066
  if (idle && activeContext) {
3235
4067
  const details = { message };
@@ -3242,7 +4074,10 @@ var SwarmController = class {
3242
4074
  return;
3243
4075
  }
3244
4076
  if (message.kind === "lead") {
4077
+ } else if (message.kind === "handoff") {
4078
+ if (activeContext) await this.acceptWorkerHandoff(activeContext, message);
3245
4079
  } else {
4080
+ await this.noteIncomingWork(message);
3246
4081
  this.receiveMessage(message);
3247
4082
  }
3248
4083
  void this.refreshLead().then((changed) => {
@@ -3286,6 +4121,190 @@ var SwarmController = class {
3286
4121
  this.endStatus(token);
3287
4122
  }
3288
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
+ }
3289
4308
  receiveMessage(message) {
3290
4309
  const sender = message.fromName ?? message.fromSessionId;
3291
4310
  const heading = message.kind === "steer" ? `Pi Agent Swarm: user steered ${sender} (${message.fromSessionId}):` : `Pi Agent Swarm ${message.mode} from ${sender} (${message.fromSessionId}).`;
@@ -3340,7 +4359,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3340
4359
  throw new Error(`Pi Agent Swarm child readiness timed out after ${this.deps.launchTimeoutMs}ms`);
3341
4360
  }
3342
4361
  async resolveSpawnCwd(ctx, value) {
3343
- const requested = value?.trim() ? resolve5(ctx.cwd, value) : ctx.cwd;
4362
+ const requested = value?.trim() ? resolve6(ctx.cwd, value) : ctx.cwd;
3344
4363
  const canonical = await this.deps.realpath(requested);
3345
4364
  if (canonical.includes("\0") || Buffer.byteLength(canonical) > 4096) {
3346
4365
  throw new Error("Pi Agent Swarm child cwd is invalid or too large");
@@ -3381,7 +4400,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3381
4400
  membership?.group.secret.fill(0);
3382
4401
  }
3383
4402
  if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
3384
- await rm5(join7(directory, "lead.json"), { force: true }).catch(() => void 0);
4403
+ await rm6(join8(directory, "lead.json"), { force: true }).catch(() => void 0);
3385
4404
  }
3386
4405
  this.leadSessionId = void 0;
3387
4406
  });
@@ -3437,7 +4456,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3437
4456
  }
3438
4457
  leadPath() {
3439
4458
  const directory = this.membership?.transport.endpointManifest?.directory;
3440
- return directory ? join7(directory, "lead.json") : void 0;
4459
+ return directory ? join8(directory, "lead.json") : void 0;
3441
4460
  }
3442
4461
  async refreshLead() {
3443
4462
  const path2 = this.leadPath();
@@ -3447,7 +4466,7 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3447
4466
  return changed;
3448
4467
  }
3449
4468
  try {
3450
- const raw = JSON.parse(await readFile(path2, "utf8"));
4469
+ const raw = JSON.parse(await readFile2(path2, "utf8"));
3451
4470
  const next = typeof raw.sessionId === "string" ? raw.sessionId : void 0;
3452
4471
  const changed = next !== this.leadSessionId;
3453
4472
  this.leadSessionId = next;
@@ -3492,18 +4511,18 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3492
4511
  throwIfAborted5(signal, "Pi Agent Swarm lead change aborted");
3493
4512
  const path2 = this.leadPath();
3494
4513
  if (!path2) throw new Error("Pi Agent Swarm runtime directory is unavailable");
3495
- const record = {
4514
+ const record2 = {
3496
4515
  sessionId: target.sessionId,
3497
4516
  ...target.name ? { name: target.name } : {},
3498
4517
  at: this.deps.now()
3499
4518
  };
3500
4519
  const temporary = `${path2}.tmp-${process.pid}`;
3501
4520
  try {
3502
- await writeFile2(temporary, `${JSON.stringify(record)}
4521
+ await writeFile3(temporary, `${JSON.stringify(record2)}
3503
4522
  `, { encoding: "utf8", flag: "wx" });
3504
- await rename3(temporary, path2);
4523
+ await rename4(temporary, path2);
3505
4524
  } finally {
3506
- await rm5(temporary, { force: true }).catch(() => void 0);
4525
+ await rm6(temporary, { force: true }).catch(() => void 0);
3507
4526
  }
3508
4527
  this.leadSessionId = target.sessionId;
3509
4528
  await this.broadcastLeadChange(target);
@@ -3553,6 +4572,78 @@ Reply through session_bus action reply to session ${message.fromSessionId} with
3553
4572
  this.membership?.transport.setName(normalized);
3554
4573
  await this.renderFooterStatus(ctx);
3555
4574
  }
4575
+ /**
4576
+ * Count completed turns and start the one-shot auto-name attempt for a
4577
+ * human-started session. The attempt runs in the background as an owned task
4578
+ * so shutdown waits for it; it never blocks the turn_end event path. The
4579
+ * returned promise resolves when the attempt settles (tests await it).
4580
+ */
4581
+ noteTurnEnd(ctx) {
4582
+ if (!this.isCurrent(ctx)) return Promise.resolve();
4583
+ if (!this.autoNameEligible) return Promise.resolve();
4584
+ if (this.autoNameInFlight) return Promise.resolve();
4585
+ if (!this.autoNamer.noteTurn(this.pi.getSessionName(), this.settings.get().settings.autoName)) {
4586
+ return Promise.resolve();
4587
+ }
4588
+ this.autoNameInFlight = true;
4589
+ const task = this.runAutoName(ctx, ctx.sessionManager, this.generation).finally(() => {
4590
+ this.autoNameInFlight = false;
4591
+ });
4592
+ return this.track(task);
4593
+ }
4594
+ /**
4595
+ * Keep the roster peer name and the footer badge in sync when the session
4596
+ * name changes outside the extension (for example `/name`), and treat a
4597
+ * custom name as the user taking over so auto-naming steps aside.
4598
+ */
4599
+ async noteSessionInfoChanged(name, ctx) {
4600
+ if (!this.isCurrent(ctx)) return;
4601
+ if (name === void 0 || name !== this.applyingAutoName) this.autoNamer.noteExternalName(name);
4602
+ if (name) this.membership?.transport.setName(name);
4603
+ await this.renderFooterStatus(ctx);
4604
+ }
4605
+ /**
4606
+ * Best-effort naming: summarize the first turns into `MAN-<title>` with the
4607
+ * current (or configured) model. Any failure keeps the default MANAGER-<id>
4608
+ * name, is recorded as a session entry for diagnosis, and is retried on a
4609
+ * later turn until the attempt budget runs out. The session name is
4610
+ * re-checked right before applying so a rename that happened during the
4611
+ * completion always wins.
4612
+ */
4613
+ async runAutoName(ctx, owner, ownerGeneration) {
4614
+ try {
4615
+ const configured = this.settings.get().settings.autoNameModel;
4616
+ const model = resolveAutoNameModel(ctx, configured);
4617
+ if (!model) {
4618
+ if (configured) {
4619
+ this.notify(
4620
+ ctx,
4621
+ `Pi Agent Swarm could not resolve autoNameModel "${configured}"; keeping the default session name.`,
4622
+ "warning"
4623
+ );
4624
+ }
4625
+ return;
4626
+ }
4627
+ const messages = collectAutoNameMessages(ctx);
4628
+ if (messages.length === 0) return;
4629
+ const signal = AbortSignal.any([this.controller.signal, AbortSignal.timeout(AUTO_NAME_TIMEOUT_MS)]);
4630
+ const complete = this.deps.completeSessionTitle ?? completeSessionTitle;
4631
+ const raw = await complete(ctx, model, buildAutoNamePrompt(messages), signal);
4632
+ if (!this.isCurrent(owner, ownerGeneration)) return;
4633
+ const name = toAutoName(raw);
4634
+ if (!name) return;
4635
+ const currentName = this.pi.getSessionName();
4636
+ if (currentName !== void 0 && !isDefaultManagerName(currentName)) return;
4637
+ this.applyingAutoName = name;
4638
+ try {
4639
+ await this.setOwnName(ctx, name, signal);
4640
+ } finally {
4641
+ this.applyingAutoName = void 0;
4642
+ }
4643
+ } catch (error) {
4644
+ this.pi.appendEntry("pi-swarm-auto-name", { ok: false, error: safeTerminalLine(safeError(error)) });
4645
+ }
4646
+ }
3556
4647
  /**
3557
4648
  * Best-effort, ordered relay of a direct user steer to the parent session so it
3558
4649
  * stays aligned. This returns immediately: sends are chained so ordering is
@@ -3665,11 +4756,11 @@ function recentSwarmState(ctx) {
3665
4756
  const messageIds = [];
3666
4757
  const consumedLaunchIds = /* @__PURE__ */ new Set();
3667
4758
  for (const entry of ctx.sessionManager.getBranch().slice(-1024)) {
3668
- if (!isRecord4(entry) || entry.type !== "custom_message" || entry.customType !== SWARM_MESSAGE_TYPE) {
4759
+ if (!isRecord5(entry) || entry.type !== "custom_message" || entry.customType !== SWARM_MESSAGE_TYPE) {
3669
4760
  continue;
3670
4761
  }
3671
4762
  const details = entry.details;
3672
- if (!isRecord4(details) || !isRecord4(details.message) || typeof details.message.id !== "string") {
4763
+ if (!isRecord5(details) || !isRecord5(details.message) || typeof details.message.id !== "string") {
3673
4764
  continue;
3674
4765
  }
3675
4766
  messageIds.push(details.message.id);
@@ -3713,7 +4804,7 @@ function truncateToBytes(value, maxBytes) {
3713
4804
  if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
3714
4805
  return Buffer.from(value, "utf8").subarray(0, maxBytes).toString("utf8");
3715
4806
  }
3716
- function isRecord4(value) {
4807
+ function isRecord5(value) {
3717
4808
  return typeof value === "object" && value !== null && !Array.isArray(value);
3718
4809
  }
3719
4810
 
@@ -3721,13 +4812,60 @@ function isRecord4(value) {
3721
4812
  import { StringEnum } from "@earendil-works/pi-ai";
3722
4813
  import { Type } from "typebox";
3723
4814
  var DIRECTIONS = ["right", "down", "left", "up"];
3724
- var BUS_ACTIONS = ["list", "send", "reply", "shutdown"];
4815
+ var BUS_ACTIONS = ["list", "send", "reply", "shutdown", "handoff"];
3725
4816
  var SEND_MODES = ["notify", "request"];
3726
4817
  var MAX_LISTED_PEERS = 64;
3727
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
+ );
3728
4834
  var spawnSchema = Type.Object(
3729
4835
  {
3730
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
+ ),
3731
4869
  task: Type.Optional(
3732
4870
  Type.String({
3733
4871
  description: "Optional first task sent after child readiness",
@@ -3768,7 +4906,13 @@ var busSchema = Type.Object(
3768
4906
  mode: Type.Optional(StringEnum(SEND_MODES, { description: "Notify without a turn or request one turn" })),
3769
4907
  replyTo: Type.Optional(
3770
4908
  Type.String({ description: "Original message id for a reply", minLength: 1, maxLength: 128 })
3771
- )
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)
3772
4916
  },
3773
4917
  { additionalProperties: false }
3774
4918
  );
@@ -3780,7 +4924,9 @@ function registerSwarmTools(pi, controller) {
3780
4924
  promptSnippet: "Start a collaborating Pi session in an external terminal window",
3781
4925
  promptGuidelines: [
3782
4926
  "Use session_spawn only when the user explicitly asks to open or start another Pi session.",
3783
- "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."
3784
4930
  ],
3785
4931
  parameters: spawnSchema,
3786
4932
  executionMode: "sequential",
@@ -3813,7 +4959,8 @@ function registerSwarmTools(pi, controller) {
3813
4959
  promptSnippet: "List or message Pi Agent Swarm sessions on this machine",
3814
4960
  promptGuidelines: [
3815
4961
  "Use session_bus to communicate with sessions already connected through Pi Agent Swarm.",
3816
- "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."
3817
4964
  ],
3818
4965
  parameters: busSchema,
3819
4966
  executionMode: "sequential",
@@ -3823,6 +4970,8 @@ function registerSwarmTools(pi, controller) {
3823
4970
  assertAbsent(params.message, "message", "list");
3824
4971
  assertAbsent(params.mode, "mode", "list");
3825
4972
  assertAbsent(params.replyTo, "replyTo", "list");
4973
+ assertAbsent(params.taskStatus, "taskStatus", "list");
4974
+ assertAbsent(params.handoff, "handoff", "list");
3826
4975
  const snapshot = await controller.snapshot(signal);
3827
4976
  if (!snapshot.connected) {
3828
4977
  return {
@@ -3836,21 +4985,49 @@ function registerSwarmTools(pi, controller) {
3836
4985
  assertAbsent(params.message, "message", "shutdown");
3837
4986
  assertAbsent(params.mode, "mode", "shutdown");
3838
4987
  assertAbsent(params.replyTo, "replyTo", "shutdown");
4988
+ assertAbsent(params.taskStatus, "taskStatus", "shutdown");
4989
+ assertAbsent(params.handoff, "handoff", "shutdown");
3839
4990
  const shutdownTarget = required(params.targetSessionId, "targetSessionId");
3840
4991
  const result2 = await controller.shutdownPeer(ctx, shutdownTarget, signal);
3841
4992
  return shutdownResult(result2, shutdownTarget);
3842
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
+ }
3843
5007
  const targetSessionId = required(params.targetSessionId, "targetSessionId");
3844
5008
  const message = required(params.message, "message");
3845
5009
  if (params.action === "send") {
3846
5010
  assertAbsent(params.replyTo, "replyTo", "send");
5011
+ assertAbsent(params.taskStatus, "taskStatus", "send");
5012
+ assertAbsent(params.handoff, "handoff", "send");
3847
5013
  const mode = params.mode ?? "notify";
3848
5014
  const result2 = await controller.send(ctx, { targetSessionId, text: message, mode }, signal);
3849
5015
  return deliveryResult(result2, targetSessionId);
3850
5016
  }
3851
5017
  assertAbsent(params.mode, "mode", "reply");
3852
5018
  const replyTo = required(params.replyTo, "replyTo");
3853
- const result = await controller.send(ctx, { targetSessionId, text: message, mode: "reply", replyTo }, signal);
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
+ );
3854
5031
  return deliveryResult(result, targetSessionId);
3855
5032
  }
3856
5033
  });
@@ -3945,12 +5122,12 @@ function assertAbsent(value, field, action) {
3945
5122
  }
3946
5123
 
3947
5124
  // src/pi-agent-swarm.ts
3948
- 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>";
3949
5126
  function createPiSwarmExtension(dependencies = {}) {
3950
5127
  return function piSwarmExtension(pi) {
3951
5128
  const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
3952
5129
  const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
3953
- const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-RH6GY6U4.ts")));
5130
+ const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-NLK5I2DA.ts")));
3954
5131
  pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
3955
5132
  registerSwarmTools(pi, controller);
3956
5133
  pi.on("session_start", async (event, ctx) => {
@@ -3959,12 +5136,30 @@ function createPiSwarmExtension(dependencies = {}) {
3959
5136
  pi.on("session_shutdown", async (event, ctx) => {
3960
5137
  await controller.sessionShutdown(event, ctx);
3961
5138
  });
5139
+ pi.on("turn_end", async (_event, ctx) => {
5140
+ controller.noteTurnEnd(ctx);
5141
+ });
5142
+ pi.on("agent_settled", async (_event, ctx) => {
5143
+ await controller.agentSettled(ctx);
5144
+ });
5145
+ pi.on("session_info_changed", async (event, ctx) => {
5146
+ await controller.noteSessionInfoChanged(event.name, ctx);
5147
+ });
3962
5148
  pi.on("input", async (event, ctx) => {
3963
5149
  if (event.source !== "interactive") return;
3964
5150
  void controller.relaySteerInput(event.text, ctx);
3965
5151
  });
3966
5152
  pi.registerCommand("swarm", {
3967
- description: "Spawn a worker Pi session, or start/join a local group",
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
+ },
3968
5163
  handler: async (rawArgs, ctx) => {
3969
5164
  const args = rawArgs.trim();
3970
5165
  if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
@@ -3974,6 +5169,10 @@ function createPiSwarmExtension(dependencies = {}) {
3974
5169
  await startGroupDirectly(controller, ctx);
3975
5170
  return;
3976
5171
  }
5172
+ if (args === "requests on" || args === "requests off") {
5173
+ setRequestPolicyDirectly(controller, ctx, args === "requests on");
5174
+ return;
5175
+ }
3977
5176
  if (args) {
3978
5177
  await joinDirectInvite(controller, args, ctx);
3979
5178
  return;
@@ -4039,6 +5238,17 @@ async function startGroupDirectly(controller, ctx) {
4039
5238
  ctx.ui.notify("Started a local Pi Agent Swarm group. You are its lead.", "info");
4040
5239
  }
4041
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
+ }
4042
5252
  function menuSource(controller) {
4043
5253
  return {
4044
5254
  snapshot: (signal) => controller.snapshot(signal),
@@ -4070,6 +5280,9 @@ function menuSource(controller) {
4070
5280
  if (controller.isCurrent(commandContext)) {
4071
5281
  commandContext.ui.notify(`Theme set to ${palette}.`, "info");
4072
5282
  }
5283
+ },
5284
+ setRequests: async (commandContext, value) => {
5285
+ setRequestPolicyDirectly(controller, commandContext, value);
4073
5286
  }
4074
5287
  };
4075
5288
  }