pi-agent-swarm 0.0.0 → 0.2.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/LICENSE +21 -0
- package/README.md +240 -2
- package/dist/chunks/chunk-77JHO3GV.ts +144 -0
- package/dist/chunks/chunk-77JHO3GV.ts.map +7 -0
- package/dist/chunks/menu-RH6GY6U4.ts +119 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +7 -0
- package/dist/index.ts +4092 -0
- package/dist/index.ts.map +7 -0
- package/package.json +54 -2
- package/src/color.ts +129 -0
- package/src/external.ts +150 -0
- package/src/footer.ts +63 -0
- package/src/i3-workspace.ts +281 -0
- package/src/index.ts +1 -0
- package/src/launch-envelope.ts +124 -0
- package/src/launcher.ts +93 -0
- package/src/menu.ts +131 -0
- package/src/pi-agent-swarm.ts +173 -0
- package/src/pi-invocation.ts +144 -0
- package/src/protocol.ts +766 -0
- package/src/reload-handoff.ts +33 -0
- package/src/renderer.ts +30 -0
- package/src/runtime-directory.ts +249 -0
- package/src/settings.ts +369 -0
- package/src/swarm-controller.ts +1353 -0
- package/src/terminal.ts +54 -0
- package/src/text.ts +42 -0
- package/src/tools.ts +275 -0
- package/src/transport-io.ts +155 -0
- package/src/transport.ts +939 -0
package/dist/index.ts
ADDED
|
@@ -0,0 +1,4092 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
badge,
|
|
5
|
+
contrastTextColor,
|
|
6
|
+
normalizeOptionalText,
|
|
7
|
+
normalizeSwarmColor,
|
|
8
|
+
pickSwarmColor,
|
|
9
|
+
safeError,
|
|
10
|
+
safeTerminalLine,
|
|
11
|
+
safeTerminalText,
|
|
12
|
+
swarmColorName,
|
|
13
|
+
swarmColorPalette
|
|
14
|
+
} from "./chunks/chunk-77JHO3GV.ts";
|
|
15
|
+
|
|
16
|
+
// src/protocol.ts
|
|
17
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
|
+
import { TextDecoder as TextDecoder2 } from "node:util";
|
|
19
|
+
var SWARM_PROTOCOL_VERSION = 3;
|
|
20
|
+
var INVITE_PREFIX = "piagentswarm:v1:";
|
|
21
|
+
var MAX_FRAME_BYTES = 32 * 1024;
|
|
22
|
+
var MAX_MESSAGE_BYTES = 16 * 1024;
|
|
23
|
+
var DEFAULT_CLOCK_SKEW_MS = 6e4;
|
|
24
|
+
var DEFAULT_MESSAGE_TTL_MS = 2 * 6e4;
|
|
25
|
+
var MAX_MESSAGE_LIFETIME_MS = 5 * 6e4;
|
|
26
|
+
var GROUP_DOMAIN = "pi-agent-swarm/group/v1\0";
|
|
27
|
+
var FRAME_MAC_DOMAIN = "pi-agent-swarm/frame/v2\0";
|
|
28
|
+
var MANIFEST_MAC_DOMAIN = "pi-agent-swarm/manifest/v2\0";
|
|
29
|
+
var SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
30
|
+
var GROUP_ID = /^[a-f0-9]{32}$/u;
|
|
31
|
+
var ENDPOINT_ID = /^[a-f0-9]{24}$/u;
|
|
32
|
+
var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/u;
|
|
33
|
+
var BASE64URL_MAC = /^[A-Za-z0-9_-]{43}$/u;
|
|
34
|
+
var ACK_CODES = /* @__PURE__ */ new Set([
|
|
35
|
+
"delivery_failed",
|
|
36
|
+
"kickoff_consumed",
|
|
37
|
+
"launch_mismatch",
|
|
38
|
+
"rate_limited",
|
|
39
|
+
"requests_disabled",
|
|
40
|
+
"shutdown_unauthorized",
|
|
41
|
+
"target_busy"
|
|
42
|
+
]);
|
|
43
|
+
function createGroup(secret = randomBytes(32)) {
|
|
44
|
+
const copied = Buffer.from(secret);
|
|
45
|
+
if (copied.length !== 32) throw new Error("Pi Agent Swarm group secret must be exactly 32 bytes");
|
|
46
|
+
const id = createHash("sha256").update(GROUP_DOMAIN).update(copied).digest("hex").slice(0, 32);
|
|
47
|
+
return { id, secret: copied };
|
|
48
|
+
}
|
|
49
|
+
function formatInvite(secret) {
|
|
50
|
+
return `${INVITE_PREFIX}${createGroup(secret).secret.toString("base64url")}`;
|
|
51
|
+
}
|
|
52
|
+
function parseInvite(value) {
|
|
53
|
+
if (value !== value.trim() || !value.startsWith(INVITE_PREFIX)) {
|
|
54
|
+
throw new Error("Pi Agent Swarm invite is invalid");
|
|
55
|
+
}
|
|
56
|
+
const encoded = value.slice(INVITE_PREFIX.length);
|
|
57
|
+
if (!BASE64URL_32_BYTES.test(encoded)) throw new Error("Pi Agent Swarm invite is invalid");
|
|
58
|
+
let secret;
|
|
59
|
+
try {
|
|
60
|
+
secret = Buffer.from(encoded, "base64url");
|
|
61
|
+
} catch {
|
|
62
|
+
throw new Error("Pi Agent Swarm invite is invalid");
|
|
63
|
+
}
|
|
64
|
+
if (secret.length !== 32 || secret.toString("base64url") !== encoded) {
|
|
65
|
+
throw new Error("Pi Agent Swarm invite is invalid");
|
|
66
|
+
}
|
|
67
|
+
return createGroup(secret);
|
|
68
|
+
}
|
|
69
|
+
function createSignedFrame(input, secret) {
|
|
70
|
+
const frameWithoutMac = {
|
|
71
|
+
version: SWARM_PROTOCOL_VERSION,
|
|
72
|
+
...normalizeUnsignedFrame(input)
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
...frameWithoutMac,
|
|
76
|
+
mac: keyedMac(FRAME_MAC_DOMAIN, frameWithoutMac, secret)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function verifySignedFrame(value, secret, options) {
|
|
80
|
+
const frame = normalizeSignedFrame(value);
|
|
81
|
+
if (frame.groupId !== options.expectedGroupId) {
|
|
82
|
+
throw new Error("Pi Agent Swarm frame belongs to the wrong group");
|
|
83
|
+
}
|
|
84
|
+
if (frame.targetSessionId !== options.expectedTargetSessionId) {
|
|
85
|
+
throw new Error("Pi Agent Swarm frame targets another session");
|
|
86
|
+
}
|
|
87
|
+
if (frame.targetEndpointId !== options.expectedTargetEndpointId) {
|
|
88
|
+
throw new Error("Pi Agent Swarm frame targets another endpoint instance");
|
|
89
|
+
}
|
|
90
|
+
const now = options.now ?? Date.now();
|
|
91
|
+
const maxClockSkewMs = options.maxClockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
|
|
92
|
+
if (Math.abs(now - frame.issuedAt) > maxClockSkewMs) {
|
|
93
|
+
throw new Error("Pi Agent Swarm frame expired outside the accepted clock window");
|
|
94
|
+
}
|
|
95
|
+
const { mac, ...unsigned } = frame;
|
|
96
|
+
const expected = keyedMac(FRAME_MAC_DOMAIN, unsigned, secret);
|
|
97
|
+
if (!safeMacEqual(mac, expected)) throw new Error("Pi Agent Swarm frame authentication failed");
|
|
98
|
+
const replayKey = [frame.senderSessionId, frame.senderEndpointId, frame.requestId, frame.nonce].join(":");
|
|
99
|
+
if (options.replay && !options.replay.accept(replayKey, now)) {
|
|
100
|
+
throw new Error("Pi Agent Swarm frame was replayed");
|
|
101
|
+
}
|
|
102
|
+
return frame;
|
|
103
|
+
}
|
|
104
|
+
function createSignedEndpointManifest(input, secret) {
|
|
105
|
+
const manifestWithoutMac = {
|
|
106
|
+
version: SWARM_PROTOCOL_VERSION,
|
|
107
|
+
...normalizeUnsignedEndpointManifest(input)
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
...manifestWithoutMac,
|
|
111
|
+
mac: keyedMac(MANIFEST_MAC_DOMAIN, manifestWithoutMac, secret)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function verifySignedEndpointManifest(value, secret, options) {
|
|
115
|
+
const manifest = normalizeSignedEndpointManifest(value);
|
|
116
|
+
if (manifest.groupId !== options.expectedGroupId) {
|
|
117
|
+
throw new Error("Pi Agent Swarm endpoint manifest belongs to the wrong group");
|
|
118
|
+
}
|
|
119
|
+
if (manifest.endpointId !== options.expectedEndpointId) {
|
|
120
|
+
throw new Error("Pi Agent Swarm endpoint manifest identity does not match its filename");
|
|
121
|
+
}
|
|
122
|
+
if (manifest.socketName !== `${manifest.endpointId}.sock`) {
|
|
123
|
+
throw new Error("Pi Agent Swarm endpoint manifest socket does not match its identity");
|
|
124
|
+
}
|
|
125
|
+
const { mac, ...unsigned } = manifest;
|
|
126
|
+
const expected = keyedMac(MANIFEST_MAC_DOMAIN, unsigned, secret);
|
|
127
|
+
if (!safeMacEqual(mac, expected)) {
|
|
128
|
+
throw new Error("Pi Agent Swarm endpoint manifest authentication failed");
|
|
129
|
+
}
|
|
130
|
+
return manifest;
|
|
131
|
+
}
|
|
132
|
+
function validateMessage(value) {
|
|
133
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm message must be an object");
|
|
134
|
+
assertExactKeys(
|
|
135
|
+
value,
|
|
136
|
+
[
|
|
137
|
+
"expiresAt",
|
|
138
|
+
"fromCwd",
|
|
139
|
+
"fromName",
|
|
140
|
+
"fromSessionId",
|
|
141
|
+
"id",
|
|
142
|
+
"issuedAt",
|
|
143
|
+
"kind",
|
|
144
|
+
"launchId",
|
|
145
|
+
"mode",
|
|
146
|
+
"replyTo",
|
|
147
|
+
"text",
|
|
148
|
+
"toSessionId"
|
|
149
|
+
],
|
|
150
|
+
"message"
|
|
151
|
+
);
|
|
152
|
+
const id = requiredId(value.id, "message id");
|
|
153
|
+
const fromSessionId = requiredId(value.fromSessionId, "sender session id");
|
|
154
|
+
const fromName = optionalBoundedString(value.fromName, "sender name", 200);
|
|
155
|
+
const fromCwd = optionalBoundedString(value.fromCwd, "sender cwd", 4096);
|
|
156
|
+
const toSessionId = requiredId(value.toSessionId, "target session id");
|
|
157
|
+
const mode = value.mode;
|
|
158
|
+
if (mode !== "notify" && mode !== "request" && mode !== "reply" && mode !== "kickoff") {
|
|
159
|
+
throw new Error("Pi Agent Swarm message mode is invalid");
|
|
160
|
+
}
|
|
161
|
+
if (typeof value.text !== "string") throw new Error("Pi Agent Swarm message text must be a string");
|
|
162
|
+
if (Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES) {
|
|
163
|
+
throw new Error("Pi Agent Swarm message is too large");
|
|
164
|
+
}
|
|
165
|
+
const issuedAt = finiteInteger(value.issuedAt, "message issued time");
|
|
166
|
+
const expiresAt = finiteInteger(value.expiresAt, "message expiry time");
|
|
167
|
+
if (expiresAt <= issuedAt || expiresAt - issuedAt > MAX_MESSAGE_LIFETIME_MS) {
|
|
168
|
+
throw new Error("Pi Agent Swarm message lifetime is invalid");
|
|
169
|
+
}
|
|
170
|
+
const replyTo = optionalId(value.replyTo, "reply message id");
|
|
171
|
+
const launchId = optionalId(value.launchId, "launch id");
|
|
172
|
+
if (value.kind !== void 0 && value.kind !== "lead" && value.kind !== "steer" && value.kind !== "shutdown") {
|
|
173
|
+
throw new Error("Pi Agent Swarm message kind is invalid");
|
|
174
|
+
}
|
|
175
|
+
if (mode === "reply" && !replyTo) throw new Error("Pi Agent Swarm reply requires a reply message id");
|
|
176
|
+
if (mode === "kickoff" && !launchId) throw new Error("Pi Agent Swarm kickoff requires a launch id");
|
|
177
|
+
return {
|
|
178
|
+
id,
|
|
179
|
+
fromSessionId,
|
|
180
|
+
...fromName ? { fromName } : {},
|
|
181
|
+
...fromCwd ? { fromCwd } : {},
|
|
182
|
+
toSessionId,
|
|
183
|
+
mode,
|
|
184
|
+
text: value.text,
|
|
185
|
+
issuedAt,
|
|
186
|
+
expiresAt,
|
|
187
|
+
...replyTo ? { replyTo } : {},
|
|
188
|
+
...launchId ? { launchId } : {},
|
|
189
|
+
...value.kind !== void 0 ? { kind: value.kind } : {}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function validateMessageTiming(message, now) {
|
|
193
|
+
if (message.issuedAt > now + DEFAULT_CLOCK_SKEW_MS) {
|
|
194
|
+
throw new Error("Pi Agent Swarm message was issued too far in the future");
|
|
195
|
+
}
|
|
196
|
+
if (message.expiresAt < now) throw new Error("Pi Agent Swarm message has expired");
|
|
197
|
+
}
|
|
198
|
+
var ReplayWindow = class {
|
|
199
|
+
constructor(capacity, ttlMs) {
|
|
200
|
+
this.capacity = capacity;
|
|
201
|
+
this.ttlMs = ttlMs;
|
|
202
|
+
if (!Number.isInteger(capacity) || capacity < 1) throw new Error("Replay capacity is invalid");
|
|
203
|
+
if (!Number.isFinite(ttlMs) || ttlMs < 1) throw new Error("Replay TTL is invalid");
|
|
204
|
+
}
|
|
205
|
+
capacity;
|
|
206
|
+
ttlMs;
|
|
207
|
+
entries = /* @__PURE__ */ new Map();
|
|
208
|
+
accept(key, now) {
|
|
209
|
+
if (this.has(key, now)) return false;
|
|
210
|
+
this.record(key, now);
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
has(key, now) {
|
|
214
|
+
this.prune(now);
|
|
215
|
+
return this.entries.has(key);
|
|
216
|
+
}
|
|
217
|
+
record(key, now) {
|
|
218
|
+
this.prune(now);
|
|
219
|
+
this.entries.delete(key);
|
|
220
|
+
this.entries.set(key, now + this.ttlMs);
|
|
221
|
+
while (this.entries.size > this.capacity) {
|
|
222
|
+
const oldest = this.entries.keys().next().value;
|
|
223
|
+
if (oldest === void 0) break;
|
|
224
|
+
this.entries.delete(oldest);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
get size() {
|
|
228
|
+
return this.entries.size;
|
|
229
|
+
}
|
|
230
|
+
prune(now) {
|
|
231
|
+
for (const [key, expiresAt] of this.entries) {
|
|
232
|
+
if (expiresAt > now) continue;
|
|
233
|
+
this.entries.delete(key);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
var FixedWindowRateLimiter = class {
|
|
238
|
+
constructor(limit, windowMs, maxKeys = 128) {
|
|
239
|
+
this.limit = limit;
|
|
240
|
+
this.windowMs = windowMs;
|
|
241
|
+
this.maxKeys = maxKeys;
|
|
242
|
+
if (!Number.isInteger(limit) || limit < 1) throw new Error("Rate limit is invalid");
|
|
243
|
+
if (!Number.isFinite(windowMs) || windowMs < 1) throw new Error("Rate window is invalid");
|
|
244
|
+
if (!Number.isInteger(maxKeys) || maxKeys < 1) throw new Error("Rate key limit is invalid");
|
|
245
|
+
}
|
|
246
|
+
limit;
|
|
247
|
+
windowMs;
|
|
248
|
+
maxKeys;
|
|
249
|
+
entries = /* @__PURE__ */ new Map();
|
|
250
|
+
accept(key, now) {
|
|
251
|
+
const current = this.entries.get(key);
|
|
252
|
+
if (!current || now - current.start >= this.windowMs || now < current.start) {
|
|
253
|
+
this.entries.delete(key);
|
|
254
|
+
this.entries.set(key, { start: now, count: 1 });
|
|
255
|
+
this.trim();
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
if (current.count >= this.limit) return false;
|
|
259
|
+
current.count += 1;
|
|
260
|
+
this.entries.delete(key);
|
|
261
|
+
this.entries.set(key, current);
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
retryAfterMs(key, now) {
|
|
265
|
+
const current = this.entries.get(key);
|
|
266
|
+
if (!current || now < current.start || now - current.start >= this.windowMs) return 0;
|
|
267
|
+
return Math.max(1, current.start + this.windowMs - now);
|
|
268
|
+
}
|
|
269
|
+
trim() {
|
|
270
|
+
while (this.entries.size > this.maxKeys) {
|
|
271
|
+
const oldest = this.entries.keys().next().value;
|
|
272
|
+
if (oldest === void 0) break;
|
|
273
|
+
this.entries.delete(oldest);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
var JsonLineDecoder = class {
|
|
278
|
+
constructor(options) {
|
|
279
|
+
this.options = options;
|
|
280
|
+
this.maxBytes = options.maxBytes ?? MAX_FRAME_BYTES;
|
|
281
|
+
}
|
|
282
|
+
options;
|
|
283
|
+
buffer = Buffer.alloc(0);
|
|
284
|
+
discarding = false;
|
|
285
|
+
maxBytes;
|
|
286
|
+
push(chunk) {
|
|
287
|
+
let incoming = Buffer.from(chunk);
|
|
288
|
+
if (this.discarding) {
|
|
289
|
+
const newline = incoming.indexOf(10);
|
|
290
|
+
if (newline < 0) return;
|
|
291
|
+
incoming = incoming.subarray(newline + 1);
|
|
292
|
+
this.discarding = false;
|
|
293
|
+
}
|
|
294
|
+
if (incoming.length === 0) return;
|
|
295
|
+
this.buffer = Buffer.concat([this.buffer, incoming]);
|
|
296
|
+
while (true) {
|
|
297
|
+
const newline = this.buffer.indexOf(10);
|
|
298
|
+
if (newline < 0) break;
|
|
299
|
+
const line = this.buffer.subarray(0, newline);
|
|
300
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
301
|
+
if (line.length > this.maxBytes) {
|
|
302
|
+
this.options.onError(new Error("Pi Agent Swarm JSONL record is too large"));
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
this.decodeLine(line);
|
|
306
|
+
}
|
|
307
|
+
if (this.buffer.length > this.maxBytes) {
|
|
308
|
+
this.buffer = Buffer.alloc(0);
|
|
309
|
+
this.discarding = true;
|
|
310
|
+
this.options.onError(new Error("Pi Agent Swarm JSONL record is too large"));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
finish() {
|
|
314
|
+
if (this.discarding) {
|
|
315
|
+
this.discarding = false;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (this.buffer.length === 0) return;
|
|
319
|
+
const line = this.buffer;
|
|
320
|
+
this.buffer = Buffer.alloc(0);
|
|
321
|
+
this.decodeLine(line);
|
|
322
|
+
}
|
|
323
|
+
decodeLine(value) {
|
|
324
|
+
const line = value.at(-1) === 13 ? value.subarray(0, -1) : value;
|
|
325
|
+
if (line.length === 0) return;
|
|
326
|
+
let text;
|
|
327
|
+
try {
|
|
328
|
+
text = new TextDecoder2("utf-8", { fatal: true }).decode(line);
|
|
329
|
+
} catch {
|
|
330
|
+
this.options.onError(new Error("Pi Agent Swarm JSONL record contains invalid UTF-8"));
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
this.options.onValue(JSON.parse(text));
|
|
335
|
+
} catch {
|
|
336
|
+
this.options.onError(new Error("Pi Agent Swarm JSONL record is malformed JSON"));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
function validatePeerDescription(value) {
|
|
341
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm peer description is invalid");
|
|
342
|
+
assertExactKeys(
|
|
343
|
+
value,
|
|
344
|
+
["acceptsRequests", "color", "cwd", "endpointId", "launchId", "name", "pid", "protocolVersion", "sessionId"],
|
|
345
|
+
"peer description"
|
|
346
|
+
);
|
|
347
|
+
if (value.protocolVersion !== SWARM_PROTOCOL_VERSION) {
|
|
348
|
+
throw new Error("Pi Agent Swarm peer protocol version is unsupported");
|
|
349
|
+
}
|
|
350
|
+
const sessionId = requiredId(value.sessionId, "peer session id");
|
|
351
|
+
const endpointId = requiredEndpointId(value.endpointId, "peer endpoint id");
|
|
352
|
+
const name = optionalBoundedString(value.name, "peer name", 200);
|
|
353
|
+
const cwd = optionalBoundedString(value.cwd, "peer cwd", 4096);
|
|
354
|
+
if (cwd === void 0) throw new Error("Pi Agent Swarm peer cwd is invalid");
|
|
355
|
+
const pid = finiteInteger(value.pid, "peer process id");
|
|
356
|
+
if (pid < 1) throw new Error("Pi Agent Swarm peer process id is invalid");
|
|
357
|
+
const launchId = optionalId(value.launchId, "peer launch id");
|
|
358
|
+
if (typeof value.acceptsRequests !== "boolean") {
|
|
359
|
+
throw new Error("Pi Agent Swarm peer request policy is invalid");
|
|
360
|
+
}
|
|
361
|
+
let color;
|
|
362
|
+
if (value.color !== void 0) {
|
|
363
|
+
if (typeof value.color !== "string" || !/^#[0-9a-f]{6}$/u.test(value.color.toLowerCase())) {
|
|
364
|
+
throw new Error("Pi Agent Swarm peer color is invalid");
|
|
365
|
+
}
|
|
366
|
+
color = value.color.toLowerCase();
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
protocolVersion: SWARM_PROTOCOL_VERSION,
|
|
370
|
+
sessionId,
|
|
371
|
+
endpointId,
|
|
372
|
+
...name ? { name } : {},
|
|
373
|
+
...color ? { color } : {},
|
|
374
|
+
cwd,
|
|
375
|
+
pid,
|
|
376
|
+
...launchId ? { launchId } : {},
|
|
377
|
+
acceptsRequests: value.acceptsRequests
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function normalizeUnsignedFrame(value) {
|
|
381
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm frame must be an object");
|
|
382
|
+
assertExactKeys(
|
|
383
|
+
value,
|
|
384
|
+
[
|
|
385
|
+
"groupId",
|
|
386
|
+
"issuedAt",
|
|
387
|
+
"nonce",
|
|
388
|
+
"payload",
|
|
389
|
+
"requestId",
|
|
390
|
+
"senderEndpointId",
|
|
391
|
+
"senderSessionId",
|
|
392
|
+
"targetEndpointId",
|
|
393
|
+
"targetSessionId"
|
|
394
|
+
],
|
|
395
|
+
"frame"
|
|
396
|
+
);
|
|
397
|
+
return normalizeUnsignedFrameFields(value);
|
|
398
|
+
}
|
|
399
|
+
function normalizeUnsignedFrameFields(value) {
|
|
400
|
+
const groupId = value.groupId;
|
|
401
|
+
if (typeof groupId !== "string" || !GROUP_ID.test(groupId)) {
|
|
402
|
+
throw new Error("Pi Agent Swarm frame group id is invalid");
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
groupId,
|
|
406
|
+
requestId: requiredId(value.requestId, "request id"),
|
|
407
|
+
targetSessionId: requiredId(value.targetSessionId, "target session id"),
|
|
408
|
+
targetEndpointId: requiredEndpointId(value.targetEndpointId, "target endpoint id"),
|
|
409
|
+
senderSessionId: requiredId(value.senderSessionId, "sender session id"),
|
|
410
|
+
senderEndpointId: requiredEndpointId(value.senderEndpointId, "sender endpoint id"),
|
|
411
|
+
issuedAt: finiteInteger(value.issuedAt, "frame issued time"),
|
|
412
|
+
nonce: requiredId(value.nonce, "frame nonce"),
|
|
413
|
+
payload: validatePayload(value.payload)
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
function normalizeSignedFrame(value) {
|
|
417
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm frame must be an object");
|
|
418
|
+
assertExactKeys(
|
|
419
|
+
value,
|
|
420
|
+
[
|
|
421
|
+
"groupId",
|
|
422
|
+
"issuedAt",
|
|
423
|
+
"mac",
|
|
424
|
+
"nonce",
|
|
425
|
+
"payload",
|
|
426
|
+
"requestId",
|
|
427
|
+
"senderEndpointId",
|
|
428
|
+
"senderSessionId",
|
|
429
|
+
"targetEndpointId",
|
|
430
|
+
"targetSessionId",
|
|
431
|
+
"version"
|
|
432
|
+
],
|
|
433
|
+
"signed frame"
|
|
434
|
+
);
|
|
435
|
+
if (value.version !== SWARM_PROTOCOL_VERSION) {
|
|
436
|
+
throw new Error("Pi Agent Swarm frame protocol version is unsupported");
|
|
437
|
+
}
|
|
438
|
+
const normalized = normalizeUnsignedFrameFields(value);
|
|
439
|
+
if (typeof value.mac !== "string" || !BASE64URL_MAC.test(value.mac)) {
|
|
440
|
+
throw new Error("Pi Agent Swarm frame authentication tag is invalid");
|
|
441
|
+
}
|
|
442
|
+
return { version: SWARM_PROTOCOL_VERSION, ...normalized, mac: value.mac };
|
|
443
|
+
}
|
|
444
|
+
function validatePayload(value) {
|
|
445
|
+
if (!isRecord(value) || typeof value.kind !== "string") {
|
|
446
|
+
throw new Error("Pi Agent Swarm frame payload is invalid");
|
|
447
|
+
}
|
|
448
|
+
if (value.kind === "describe") {
|
|
449
|
+
assertExactKeys(value, ["kind"], "describe payload");
|
|
450
|
+
return { kind: "describe" };
|
|
451
|
+
}
|
|
452
|
+
if (value.kind === "description") {
|
|
453
|
+
assertExactKeys(value, ["kind", "peer"], "description payload");
|
|
454
|
+
return { kind: "description", peer: validatePeerDescription(value.peer) };
|
|
455
|
+
}
|
|
456
|
+
if (value.kind === "message") {
|
|
457
|
+
assertExactKeys(value, ["kickoffCapability", "kind", "message"], "message payload");
|
|
458
|
+
const kickoffCapability = optionalId(value.kickoffCapability, "kickoff capability");
|
|
459
|
+
const message = validateMessage(value.message);
|
|
460
|
+
if (kickoffCapability && message.mode !== "kickoff") {
|
|
461
|
+
throw new Error("Pi Agent Swarm kickoff capability is invalid for this message mode");
|
|
462
|
+
}
|
|
463
|
+
return {
|
|
464
|
+
kind: "message",
|
|
465
|
+
message,
|
|
466
|
+
...kickoffCapability ? { kickoffCapability } : {}
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
if (value.kind === "ack") {
|
|
470
|
+
assertExactKeys(value, ["code", "error", "kind", "retryAfterMs", "status"], "ack payload");
|
|
471
|
+
const status = value.status;
|
|
472
|
+
if (status !== "accepted" && status !== "duplicate" && status !== "rejected" && status !== "busy") {
|
|
473
|
+
throw new Error("Pi Agent Swarm ack status is invalid");
|
|
474
|
+
}
|
|
475
|
+
const code = optionalAckCode(value.code);
|
|
476
|
+
const error = optionalBoundedString(value.error, "ack error", 1e3);
|
|
477
|
+
const retryAfterMs = optionalPositiveInteger(value.retryAfterMs, "ack retry delay", 864e5);
|
|
478
|
+
if (status === "accepted" || status === "duplicate") {
|
|
479
|
+
if (code || error || retryAfterMs !== void 0) {
|
|
480
|
+
throw new Error("Pi Agent Swarm successful ack contains rejection details");
|
|
481
|
+
}
|
|
482
|
+
} else if (!code) {
|
|
483
|
+
throw new Error("Pi Agent Swarm rejected ack requires an error code");
|
|
484
|
+
}
|
|
485
|
+
return {
|
|
486
|
+
kind: "ack",
|
|
487
|
+
status,
|
|
488
|
+
...code ? { code } : {},
|
|
489
|
+
...error ? { error } : {},
|
|
490
|
+
...retryAfterMs !== void 0 ? { retryAfterMs } : {}
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
throw new Error("Pi Agent Swarm frame payload kind is invalid");
|
|
494
|
+
}
|
|
495
|
+
function normalizeUnsignedEndpointManifest(value) {
|
|
496
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm endpoint manifest must be an object");
|
|
497
|
+
assertExactKeys(
|
|
498
|
+
value,
|
|
499
|
+
["endpointId", "groupId", "pid", "publishedAt", "sessionId", "socketName"],
|
|
500
|
+
"endpoint manifest"
|
|
501
|
+
);
|
|
502
|
+
return normalizeUnsignedEndpointManifestFields(value);
|
|
503
|
+
}
|
|
504
|
+
function normalizeUnsignedEndpointManifestFields(value) {
|
|
505
|
+
const groupId = value.groupId;
|
|
506
|
+
if (typeof groupId !== "string" || !GROUP_ID.test(groupId)) {
|
|
507
|
+
throw new Error("Pi Agent Swarm endpoint manifest group id is invalid");
|
|
508
|
+
}
|
|
509
|
+
const endpointId = requiredEndpointId(value.endpointId, "endpoint manifest id");
|
|
510
|
+
const socketName = value.socketName;
|
|
511
|
+
if (typeof socketName !== "string" || socketName !== `${endpointId}.sock`) {
|
|
512
|
+
throw new Error("Pi Agent Swarm endpoint manifest socket name is invalid");
|
|
513
|
+
}
|
|
514
|
+
const pid = finiteInteger(value.pid, "endpoint manifest process id");
|
|
515
|
+
if (pid < 1) throw new Error("Pi Agent Swarm endpoint manifest process id is invalid");
|
|
516
|
+
return {
|
|
517
|
+
groupId,
|
|
518
|
+
endpointId,
|
|
519
|
+
sessionId: requiredId(value.sessionId, "endpoint manifest session id"),
|
|
520
|
+
socketName,
|
|
521
|
+
pid,
|
|
522
|
+
publishedAt: finiteInteger(value.publishedAt, "endpoint manifest publication time")
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function normalizeSignedEndpointManifest(value) {
|
|
526
|
+
if (!isRecord(value)) throw new Error("Pi Agent Swarm endpoint manifest must be an object");
|
|
527
|
+
assertExactKeys(
|
|
528
|
+
value,
|
|
529
|
+
["endpointId", "groupId", "mac", "pid", "publishedAt", "sessionId", "socketName", "version"],
|
|
530
|
+
"signed endpoint manifest"
|
|
531
|
+
);
|
|
532
|
+
if (value.version !== SWARM_PROTOCOL_VERSION) {
|
|
533
|
+
throw new Error("Pi Agent Swarm endpoint manifest protocol version is unsupported");
|
|
534
|
+
}
|
|
535
|
+
const normalized = normalizeUnsignedEndpointManifestFields(value);
|
|
536
|
+
if (typeof value.mac !== "string" || !BASE64URL_MAC.test(value.mac)) {
|
|
537
|
+
throw new Error("Pi Agent Swarm endpoint manifest authentication tag is invalid");
|
|
538
|
+
}
|
|
539
|
+
return { version: SWARM_PROTOCOL_VERSION, ...normalized, mac: value.mac };
|
|
540
|
+
}
|
|
541
|
+
function keyedMac(domain, value, secret) {
|
|
542
|
+
const key = Buffer.from(secret);
|
|
543
|
+
if (key.length !== 32) throw new Error("Pi Agent Swarm group secret must be exactly 32 bytes");
|
|
544
|
+
return createHmac("sha256", key).update(domain).update(canonicalJson(value)).digest("base64url");
|
|
545
|
+
}
|
|
546
|
+
function safeMacEqual(actual, expected) {
|
|
547
|
+
const actualBytes = Buffer.from(actual);
|
|
548
|
+
const expectedBytes = Buffer.from(expected);
|
|
549
|
+
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
|
|
550
|
+
}
|
|
551
|
+
function canonicalJson(value) {
|
|
552
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") {
|
|
553
|
+
return JSON.stringify(value);
|
|
554
|
+
}
|
|
555
|
+
if (typeof value === "number") {
|
|
556
|
+
if (!Number.isFinite(value)) throw new Error("Pi Agent Swarm frame contains a non-finite number");
|
|
557
|
+
return JSON.stringify(value);
|
|
558
|
+
}
|
|
559
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
|
|
560
|
+
if (isRecord(value)) {
|
|
561
|
+
return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
562
|
+
}
|
|
563
|
+
throw new Error("Pi Agent Swarm frame contains unsupported data");
|
|
564
|
+
}
|
|
565
|
+
function requiredId(value, label) {
|
|
566
|
+
if (typeof value !== "string" || !SAFE_ID.test(value)) {
|
|
567
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid`);
|
|
568
|
+
}
|
|
569
|
+
return value;
|
|
570
|
+
}
|
|
571
|
+
function requiredEndpointId(value, label) {
|
|
572
|
+
if (typeof value !== "string" || !ENDPOINT_ID.test(value)) {
|
|
573
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid`);
|
|
574
|
+
}
|
|
575
|
+
return value;
|
|
576
|
+
}
|
|
577
|
+
function optionalId(value, label) {
|
|
578
|
+
if (value === void 0) return void 0;
|
|
579
|
+
return requiredId(value, label);
|
|
580
|
+
}
|
|
581
|
+
function optionalAckCode(value) {
|
|
582
|
+
if (value === void 0) return void 0;
|
|
583
|
+
if (typeof value !== "string" || !ACK_CODES.has(value)) {
|
|
584
|
+
throw new Error("Pi Agent Swarm ack error code is invalid");
|
|
585
|
+
}
|
|
586
|
+
return value;
|
|
587
|
+
}
|
|
588
|
+
function optionalBoundedString(value, label, maxBytes) {
|
|
589
|
+
if (value === void 0) return void 0;
|
|
590
|
+
if (typeof value !== "string" || Buffer.byteLength(value, "utf8") > maxBytes) {
|
|
591
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid`);
|
|
592
|
+
}
|
|
593
|
+
return value;
|
|
594
|
+
}
|
|
595
|
+
function optionalPositiveInteger(value, label, maximum) {
|
|
596
|
+
if (value === void 0) return void 0;
|
|
597
|
+
const normalized = finiteInteger(value, label);
|
|
598
|
+
if (normalized < 1 || normalized > maximum) throw new Error(`Pi Agent Swarm ${label} is invalid`);
|
|
599
|
+
return normalized;
|
|
600
|
+
}
|
|
601
|
+
function finiteInteger(value, label) {
|
|
602
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
603
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid`);
|
|
604
|
+
}
|
|
605
|
+
return value;
|
|
606
|
+
}
|
|
607
|
+
function assertExactKeys(value, allowed, label) {
|
|
608
|
+
const allowedKeys = new Set(allowed);
|
|
609
|
+
for (const key of Object.keys(value)) {
|
|
610
|
+
if (!allowedKeys.has(key)) throw new Error(`Pi Agent Swarm ${label} contains an unknown field`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
function isRecord(value) {
|
|
614
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/renderer.ts
|
|
618
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
619
|
+
var SWARM_MESSAGE_TYPE = "pi-agent-swarm-message";
|
|
620
|
+
var renderSwarmMessage = (message, options, theme) => {
|
|
621
|
+
const details = message.details;
|
|
622
|
+
if (!details?.message) return void 0;
|
|
623
|
+
const value = details.message;
|
|
624
|
+
const sender = safeTerminalLine(value.fromName ?? value.fromSessionId) || "unknown session";
|
|
625
|
+
const mode = value.mode === "request" || value.mode === "kickoff" ? "request" : value.mode;
|
|
626
|
+
const lines = [theme.fg("accent", theme.bold(`Pi Agent Swarm ${mode} \xB7 ${sender}`)), safeTerminalText(value.text)];
|
|
627
|
+
if (options.expanded) {
|
|
628
|
+
lines.push(
|
|
629
|
+
theme.fg("dim", `Session: ${safeTerminalLine(value.fromSessionId)}`),
|
|
630
|
+
theme.fg("dim", `Cwd: ${safeTerminalLine(value.fromCwd ?? "unknown")}`),
|
|
631
|
+
theme.fg("dim", `Message: ${safeTerminalLine(value.id)}`)
|
|
632
|
+
);
|
|
633
|
+
if (value.replyTo) {
|
|
634
|
+
lines.push(theme.fg("dim", `Reply to: ${safeTerminalLine(value.replyTo)}`));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return new Text(lines.join("\n"), options.outputPad, 0);
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
// src/settings.ts
|
|
641
|
+
import { randomUUID } from "node:crypto";
|
|
642
|
+
import { constants } from "node:fs";
|
|
643
|
+
import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
644
|
+
import { basename, dirname, join } from "node:path";
|
|
645
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
646
|
+
var SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
|
|
647
|
+
var MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
|
|
648
|
+
var DEFAULT_SWARM_SETTINGS = Object.freeze({
|
|
649
|
+
colorPalette: "muted",
|
|
650
|
+
confirmSessionLaunch: true,
|
|
651
|
+
externalCommand: "alacritty -e",
|
|
652
|
+
pinToLeadWorkspace: false
|
|
653
|
+
});
|
|
654
|
+
var SETTING_FIELDS = [
|
|
655
|
+
"colorPalette",
|
|
656
|
+
"confirmSessionLaunch",
|
|
657
|
+
"externalCommand",
|
|
658
|
+
"pinToLeadWorkspace"
|
|
659
|
+
];
|
|
660
|
+
var SETTING_FIELD_SET = new Set(SETTING_FIELDS);
|
|
661
|
+
function swarmSettingsFilePath() {
|
|
662
|
+
return join(getAgentDir(), SWARM_SETTINGS_FILE);
|
|
663
|
+
}
|
|
664
|
+
function normalizeSwarmSettingsDocument(value) {
|
|
665
|
+
if (!isRecord2(value)) return void 0;
|
|
666
|
+
const settings = { ...DEFAULT_SWARM_SETTINGS };
|
|
667
|
+
const sources = builtInSources();
|
|
668
|
+
if (Object.hasOwn(value, "colorPalette")) {
|
|
669
|
+
if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return void 0;
|
|
670
|
+
settings.colorPalette = value.colorPalette;
|
|
671
|
+
sources.colorPalette = "user";
|
|
672
|
+
}
|
|
673
|
+
if (Object.hasOwn(value, "confirmSessionLaunch")) {
|
|
674
|
+
if (typeof value.confirmSessionLaunch !== "boolean") return void 0;
|
|
675
|
+
settings.confirmSessionLaunch = value.confirmSessionLaunch;
|
|
676
|
+
sources.confirmSessionLaunch = "user";
|
|
677
|
+
}
|
|
678
|
+
if (Object.hasOwn(value, "externalCommand")) {
|
|
679
|
+
if (typeof value.externalCommand !== "string" || value.externalCommand.trim().length === 0) {
|
|
680
|
+
return void 0;
|
|
681
|
+
}
|
|
682
|
+
settings.externalCommand = value.externalCommand.trim();
|
|
683
|
+
sources.externalCommand = "user";
|
|
684
|
+
}
|
|
685
|
+
if (Object.hasOwn(value, "pinToLeadWorkspace")) {
|
|
686
|
+
if (typeof value.pinToLeadWorkspace !== "boolean") return void 0;
|
|
687
|
+
settings.pinToLeadWorkspace = value.pinToLeadWorkspace;
|
|
688
|
+
sources.pinToLeadWorkspace = "user";
|
|
689
|
+
}
|
|
690
|
+
return { settings, sources };
|
|
691
|
+
}
|
|
692
|
+
async function loadSwarmSettings(path2 = swarmSettingsFilePath(), signal) {
|
|
693
|
+
let text;
|
|
694
|
+
try {
|
|
695
|
+
text = await readSettingsDocument(path2, signal);
|
|
696
|
+
} catch (error) {
|
|
697
|
+
if (signal?.aborted) throw error;
|
|
698
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
699
|
+
return {
|
|
700
|
+
kind: "missing",
|
|
701
|
+
path: path2,
|
|
702
|
+
document: {},
|
|
703
|
+
settings: { ...DEFAULT_SWARM_SETTINGS },
|
|
704
|
+
sources: builtInSources()
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
return invalidLoad(path2, formatError(error));
|
|
708
|
+
}
|
|
709
|
+
try {
|
|
710
|
+
const document = JSON.parse(text);
|
|
711
|
+
const normalized = normalizeSwarmSettingsDocument(document);
|
|
712
|
+
if (!normalized || !isRecord2(document)) {
|
|
713
|
+
return invalidLoad(path2, "the document is malformed or contains an invalid setting");
|
|
714
|
+
}
|
|
715
|
+
return { kind: "loaded", path: path2, document, ...normalized };
|
|
716
|
+
} catch (error) {
|
|
717
|
+
return invalidLoad(path2, formatError(error));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
function createInMemorySwarmSettingsRuntime() {
|
|
721
|
+
let state = {
|
|
722
|
+
settings: { ...DEFAULT_SWARM_SETTINGS },
|
|
723
|
+
sources: builtInSources(),
|
|
724
|
+
canSave: true
|
|
725
|
+
};
|
|
726
|
+
return {
|
|
727
|
+
get: () => freezeState(state),
|
|
728
|
+
getPath: () => "",
|
|
729
|
+
reload: async () => freezeState(state),
|
|
730
|
+
update: async (patch) => {
|
|
731
|
+
const canonical = normalizePatch(patch);
|
|
732
|
+
state = {
|
|
733
|
+
settings: { ...state.settings, ...canonical },
|
|
734
|
+
sources: {
|
|
735
|
+
...state.sources,
|
|
736
|
+
...canonical.colorPalette !== void 0 ? { colorPalette: "user" } : {},
|
|
737
|
+
...canonical.confirmSessionLaunch !== void 0 ? { confirmSessionLaunch: "user" } : {},
|
|
738
|
+
...canonical.externalCommand ? { externalCommand: "user" } : {},
|
|
739
|
+
...canonical.pinToLeadWorkspace !== void 0 ? { pinToLeadWorkspace: "user" } : {}
|
|
740
|
+
},
|
|
741
|
+
canSave: true
|
|
742
|
+
};
|
|
743
|
+
return freezeState(state);
|
|
744
|
+
},
|
|
745
|
+
flush: async () => void 0
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
function createSwarmSettingsRuntime(options = {}) {
|
|
749
|
+
let resolvedPath;
|
|
750
|
+
const getPath = () => {
|
|
751
|
+
resolvedPath ??= typeof options.path === "function" ? options.path() : options.path ?? swarmSettingsFilePath();
|
|
752
|
+
return resolvedPath;
|
|
753
|
+
};
|
|
754
|
+
const operations = {
|
|
755
|
+
writeFile,
|
|
756
|
+
rename,
|
|
757
|
+
...options.operations
|
|
758
|
+
};
|
|
759
|
+
let state = {
|
|
760
|
+
settings: { ...DEFAULT_SWARM_SETTINGS },
|
|
761
|
+
sources: builtInSources(),
|
|
762
|
+
canSave: true
|
|
763
|
+
};
|
|
764
|
+
let queue = Promise.resolve();
|
|
765
|
+
const enqueue = (operation) => {
|
|
766
|
+
const result = queue.then(operation, operation);
|
|
767
|
+
queue = result.then(
|
|
768
|
+
() => void 0,
|
|
769
|
+
() => void 0
|
|
770
|
+
);
|
|
771
|
+
return result;
|
|
772
|
+
};
|
|
773
|
+
return {
|
|
774
|
+
get: () => freezeState(state),
|
|
775
|
+
getPath,
|
|
776
|
+
reload(signal) {
|
|
777
|
+
return enqueue(async () => {
|
|
778
|
+
const loaded = await loadSwarmSettings(getPath(), signal);
|
|
779
|
+
if (loaded.kind === "invalid") {
|
|
780
|
+
state = { ...state, issue: loaded.issue, canSave: false };
|
|
781
|
+
return freezeState(state);
|
|
782
|
+
}
|
|
783
|
+
state = { settings: loaded.settings, sources: loaded.sources, canSave: true };
|
|
784
|
+
return freezeState(state);
|
|
785
|
+
});
|
|
786
|
+
},
|
|
787
|
+
update(patch) {
|
|
788
|
+
return enqueue(async () => {
|
|
789
|
+
const canonicalPatch = normalizePatch(patch);
|
|
790
|
+
const latest = await loadSwarmSettings(getPath());
|
|
791
|
+
if (latest.kind === "invalid") {
|
|
792
|
+
state = { ...state, issue: latest.issue, canSave: false };
|
|
793
|
+
throw new Error(`Cannot update malformed or invalid settings: ${latest.issue.message}`);
|
|
794
|
+
}
|
|
795
|
+
const document = { ...latest.document, ...canonicalPatch };
|
|
796
|
+
const normalized = normalizeSwarmSettingsDocument(document);
|
|
797
|
+
if (!normalized) throw new Error("Refusing to publish invalid Pi Agent Swarm settings.");
|
|
798
|
+
await publishSettingsDocument(document, getPath(), operations);
|
|
799
|
+
state = { ...normalized, canSave: true };
|
|
800
|
+
return freezeState(state);
|
|
801
|
+
});
|
|
802
|
+
},
|
|
803
|
+
async flush() {
|
|
804
|
+
await queue;
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
function normalizePatch(patch) {
|
|
809
|
+
if (!isRecord2(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
|
|
810
|
+
throw new Error("Refusing to update unknown Pi Agent Swarm settings.");
|
|
811
|
+
}
|
|
812
|
+
const normalized = normalizeSwarmSettingsDocument(patch);
|
|
813
|
+
if (!normalized) throw new Error("Refusing to update invalid Pi Agent Swarm settings.");
|
|
814
|
+
const canonical = {};
|
|
815
|
+
for (const field of SETTING_FIELDS) {
|
|
816
|
+
if (Object.hasOwn(patch, field)) assignSetting(canonical, field, normalized.settings[field]);
|
|
817
|
+
}
|
|
818
|
+
return canonical;
|
|
819
|
+
}
|
|
820
|
+
function assignSetting(settings, field, value) {
|
|
821
|
+
settings[field] = value;
|
|
822
|
+
}
|
|
823
|
+
async function publishSettingsDocument(document, path2, operations) {
|
|
824
|
+
const contents = `${JSON.stringify(document, null, " ")}
|
|
825
|
+
`;
|
|
826
|
+
if (Buffer.byteLength(contents, "utf8") > MAX_SWARM_SETTINGS_BYTES) {
|
|
827
|
+
throw new Error(`settings document exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
|
|
828
|
+
}
|
|
829
|
+
await mkdir(dirname(path2), { recursive: true });
|
|
830
|
+
const temporaryPath = join(dirname(path2), `.${basename(path2)}.${process.pid}.${randomUUID()}.tmp`);
|
|
831
|
+
try {
|
|
832
|
+
await operations.writeFile(temporaryPath, contents, {
|
|
833
|
+
encoding: "utf8",
|
|
834
|
+
flag: "wx",
|
|
835
|
+
mode: 384
|
|
836
|
+
});
|
|
837
|
+
await operations.rename(temporaryPath, path2);
|
|
838
|
+
} finally {
|
|
839
|
+
await rm(temporaryPath, { force: true }).catch(() => void 0);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
async function readSettingsDocument(path2, signal) {
|
|
843
|
+
throwIfAborted(signal);
|
|
844
|
+
const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
|
|
845
|
+
const handle = await open(path2, flags);
|
|
846
|
+
try {
|
|
847
|
+
throwIfAborted(signal);
|
|
848
|
+
const [descriptorStats, pathStats] = await Promise.all([handle.stat(), lstat(path2)]);
|
|
849
|
+
throwIfAborted(signal);
|
|
850
|
+
if (pathStats.isSymbolicLink()) throw new Error("symbolic links are not accepted");
|
|
851
|
+
if (!descriptorStats.isFile() || !pathStats.isFile()) {
|
|
852
|
+
throw new Error("settings path is not a regular file");
|
|
853
|
+
}
|
|
854
|
+
if (descriptorStats.dev !== pathStats.dev || descriptorStats.ino !== pathStats.ino) {
|
|
855
|
+
throw new Error("settings path changed while it was being opened");
|
|
856
|
+
}
|
|
857
|
+
if (descriptorStats.size > MAX_SWARM_SETTINGS_BYTES) {
|
|
858
|
+
throw new Error(`settings file exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
|
|
859
|
+
}
|
|
860
|
+
const buffer = Buffer.alloc(MAX_SWARM_SETTINGS_BYTES + 1);
|
|
861
|
+
let offset = 0;
|
|
862
|
+
while (offset < buffer.length) {
|
|
863
|
+
const result = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
864
|
+
throwIfAborted(signal);
|
|
865
|
+
if (result.bytesRead === 0) break;
|
|
866
|
+
offset += result.bytesRead;
|
|
867
|
+
}
|
|
868
|
+
if (offset > MAX_SWARM_SETTINGS_BYTES) {
|
|
869
|
+
throw new Error(`settings file exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
|
|
870
|
+
}
|
|
871
|
+
try {
|
|
872
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));
|
|
873
|
+
} catch {
|
|
874
|
+
throw new Error("settings file is not valid UTF-8");
|
|
875
|
+
}
|
|
876
|
+
} finally {
|
|
877
|
+
await handle.close();
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
function throwIfAborted(signal) {
|
|
881
|
+
if (signal?.aborted) throw signal.reason;
|
|
882
|
+
}
|
|
883
|
+
function invalidLoad(path2, reason) {
|
|
884
|
+
return {
|
|
885
|
+
kind: "invalid",
|
|
886
|
+
path: path2,
|
|
887
|
+
settings: { ...DEFAULT_SWARM_SETTINGS },
|
|
888
|
+
sources: builtInSources(),
|
|
889
|
+
issue: { kind: "invalid", message: `${SWARM_SETTINGS_FILE} ignored (${path2}: ${reason})` }
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
function builtInSources() {
|
|
893
|
+
return {
|
|
894
|
+
colorPalette: "built-in",
|
|
895
|
+
confirmSessionLaunch: "built-in",
|
|
896
|
+
externalCommand: "built-in",
|
|
897
|
+
pinToLeadWorkspace: "built-in"
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
function freezeState(state) {
|
|
901
|
+
return Object.freeze({
|
|
902
|
+
...state,
|
|
903
|
+
settings: Object.freeze({ ...state.settings }),
|
|
904
|
+
sources: Object.freeze({ ...state.sources })
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
function isRecord2(value) {
|
|
908
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
909
|
+
}
|
|
910
|
+
function isNodeError(error) {
|
|
911
|
+
return error instanceof Error && "code" in error;
|
|
912
|
+
}
|
|
913
|
+
function formatError(error) {
|
|
914
|
+
return error instanceof Error ? error.message : String(error);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// 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";
|
|
921
|
+
|
|
922
|
+
// src/external.ts
|
|
923
|
+
import { spawn } from "node:child_process";
|
|
924
|
+
import { existsSync } from "node:fs";
|
|
925
|
+
import { join as join2 } from "node:path";
|
|
926
|
+
var ExternalLaunchError = class extends Error {
|
|
927
|
+
constructor(message, splitCreated = false, terminalId) {
|
|
928
|
+
super(message);
|
|
929
|
+
this.splitCreated = splitCreated;
|
|
930
|
+
this.terminalId = terminalId;
|
|
931
|
+
this.name = "ExternalLaunchError";
|
|
932
|
+
}
|
|
933
|
+
splitCreated;
|
|
934
|
+
terminalId;
|
|
935
|
+
};
|
|
936
|
+
function parseExternalCommand(value) {
|
|
937
|
+
return value.trim().split(/\s+/u).filter(Boolean);
|
|
938
|
+
}
|
|
939
|
+
var ExternalTerminalAdapter = class {
|
|
940
|
+
constructor(command, i3Pinner) {
|
|
941
|
+
this.command = command;
|
|
942
|
+
this.i3Pinner = i3Pinner;
|
|
943
|
+
}
|
|
944
|
+
command;
|
|
945
|
+
i3Pinner;
|
|
946
|
+
async assertAvailable(signal) {
|
|
947
|
+
throwIfAborted2(signal, "external terminal availability check aborted");
|
|
948
|
+
const binary = this.command[0];
|
|
949
|
+
if (!binary) throw new ExternalLaunchError("Pi Agent Swarm external terminal command is empty");
|
|
950
|
+
if (!isOnPath(binary)) {
|
|
951
|
+
throw new ExternalLaunchError(`Pi Agent Swarm external terminal "${binary}" was not found on PATH`);
|
|
952
|
+
}
|
|
953
|
+
return binary;
|
|
954
|
+
}
|
|
955
|
+
async spawnSplit(options) {
|
|
956
|
+
throwIfAborted2(options.signal, "external window creation aborted");
|
|
957
|
+
validateSpawnOptions(options);
|
|
958
|
+
const binary = await this.assertAvailable(options.signal);
|
|
959
|
+
if (!options.isCurrent()) {
|
|
960
|
+
throw new ExternalLaunchError("Pi Agent Swarm session became stale before window creation");
|
|
961
|
+
}
|
|
962
|
+
throwIfAborted2(options.signal, "external window creation aborted");
|
|
963
|
+
let leadWorkspace;
|
|
964
|
+
if (this.i3Pinner) {
|
|
965
|
+
try {
|
|
966
|
+
leadWorkspace = await this.i3Pinner.captureLeadWorkspace(options.signal);
|
|
967
|
+
} catch {
|
|
968
|
+
leadWorkspace = void 0;
|
|
969
|
+
}
|
|
970
|
+
if (!options.isCurrent()) {
|
|
971
|
+
throw new ExternalLaunchError("Pi Agent Swarm session became stale before window creation");
|
|
972
|
+
}
|
|
973
|
+
throwIfAborted2(options.signal, "external window creation aborted");
|
|
974
|
+
}
|
|
975
|
+
let pid;
|
|
976
|
+
try {
|
|
977
|
+
const child = spawn(binary, [...this.command.slice(1), options.launcherCommand], {
|
|
978
|
+
cwd: options.cwd,
|
|
979
|
+
detached: true,
|
|
980
|
+
stdio: "ignore"
|
|
981
|
+
});
|
|
982
|
+
pid = child.pid;
|
|
983
|
+
child.on("error", () => void 0);
|
|
984
|
+
child.unref();
|
|
985
|
+
} catch (error) {
|
|
986
|
+
if (options.signal?.aborted) {
|
|
987
|
+
throw new ExternalLaunchError("external window creation was cancelled", true);
|
|
988
|
+
}
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
if (this.i3Pinner && leadWorkspace !== void 0) {
|
|
992
|
+
try {
|
|
993
|
+
await this.i3Pinner.pinNewWindowToLeadWorkspace(leadWorkspace, options.signal);
|
|
994
|
+
} catch {
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (options.signal?.aborted) {
|
|
998
|
+
throw new ExternalLaunchError(
|
|
999
|
+
"external window was created after cancellation",
|
|
1000
|
+
true,
|
|
1001
|
+
pid ? String(pid) : void 0
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
if (!options.isCurrent()) {
|
|
1005
|
+
throw new ExternalLaunchError(
|
|
1006
|
+
"Pi Agent Swarm session became stale after window creation",
|
|
1007
|
+
true,
|
|
1008
|
+
pid ? String(pid) : void 0
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
return { terminalId: pid ? String(pid) : "unknown", version: binary };
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
function validateSpawnOptions(options) {
|
|
1015
|
+
for (const [label, value, maxBytes] of [
|
|
1016
|
+
["working directory", options.cwd, 4096],
|
|
1017
|
+
["launcher command", options.launcherCommand, 4096]
|
|
1018
|
+
]) {
|
|
1019
|
+
if (!value || value.includes("\0") || Buffer.byteLength(value) > maxBytes) {
|
|
1020
|
+
throw new ExternalLaunchError(`Pi Agent Swarm ${label} is invalid`);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
function isOnPath(binary) {
|
|
1025
|
+
if (binary.includes("/")) return existsSync(binary);
|
|
1026
|
+
const path2 = process.env.PATH ?? "";
|
|
1027
|
+
for (const dir of path2.split(":")) {
|
|
1028
|
+
if (dir && existsSync(join2(dir, binary))) return true;
|
|
1029
|
+
}
|
|
1030
|
+
return false;
|
|
1031
|
+
}
|
|
1032
|
+
function throwIfAborted2(signal, message) {
|
|
1033
|
+
if (!signal?.aborted) return;
|
|
1034
|
+
const error = new Error(message);
|
|
1035
|
+
error.name = "AbortError";
|
|
1036
|
+
throw error;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// src/footer.ts
|
|
1040
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
1041
|
+
var ROLE_BADGE_BACKGROUND = "#ffc85a";
|
|
1042
|
+
var FOOTER_WIDTH_FRACTION = 0.55;
|
|
1043
|
+
var SHORT_ID_LENGTH = 8;
|
|
1044
|
+
var DEFAULT_TERMINAL_COLUMNS = 80;
|
|
1045
|
+
var MIN_NAME_BUDGET = 8;
|
|
1046
|
+
var NAME_BADGE_OVERHEAD = 4;
|
|
1047
|
+
function buildRosterBadge(input) {
|
|
1048
|
+
const name = input.name ? safeTerminalLine(input.name) : "";
|
|
1049
|
+
const sessionId = safeTerminalLine(input.sessionId);
|
|
1050
|
+
const roleBadge = badge(` ${input.role} `, ROLE_BADGE_BACKGROUND, "#000000");
|
|
1051
|
+
const nameBadge = (value) => badge(value ? ` \u25CF ${value} ` : " \u25CF ", input.color, contrastTextColor(input.color));
|
|
1052
|
+
const available = Math.max(0, Math.floor(input.columns * FOOTER_WIDTH_FRACTION));
|
|
1053
|
+
const full = `${nameBadge(name)}${badge(` ${sessionId} `, "#ffffff", "#000000")}${roleBadge}`;
|
|
1054
|
+
if (visibleWidth(full) <= available) return full;
|
|
1055
|
+
const shortId = [...sessionId].slice(0, SHORT_ID_LENGTH).join("");
|
|
1056
|
+
const shortIdBadge = badge(` ${shortId} `, "#ffffff", "#000000");
|
|
1057
|
+
const nameBudget = available - visibleWidth(roleBadge) - visibleWidth(shortIdBadge) - NAME_BADGE_OVERHEAD;
|
|
1058
|
+
if (nameBudget >= MIN_NAME_BUDGET) {
|
|
1059
|
+
const truncated = visibleWidth(name) > nameBudget ? truncateToWidth(name, nameBudget, "\u2026") : name;
|
|
1060
|
+
return `${nameBadge(truncated)}${shortIdBadge}${roleBadge}`;
|
|
1061
|
+
}
|
|
1062
|
+
return `${nameBadge("")}${roleBadge}`;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// src/launch-envelope.ts
|
|
1066
|
+
var SWARM_LAUNCH_ENV_KEYS = [
|
|
1067
|
+
"PI_SWARM_INVITE",
|
|
1068
|
+
"PI_SWARM_PARENT_SESSION_ID",
|
|
1069
|
+
"PI_SWARM_LAUNCH_ID",
|
|
1070
|
+
"PI_SWARM_KICKOFF_CAPABILITY",
|
|
1071
|
+
"PI_SWARM_CHILD_NAME",
|
|
1072
|
+
"PI_SWARM_COLOR",
|
|
1073
|
+
"PI_SWARM_ACCEPT_REQUESTS",
|
|
1074
|
+
"PI_SWARM_MODEL_PROVIDER",
|
|
1075
|
+
"PI_SWARM_MODEL_ID",
|
|
1076
|
+
"PI_SWARM_THINKING"
|
|
1077
|
+
];
|
|
1078
|
+
var THINKING_LEVELS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
1079
|
+
var SAFE_ID2 = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
1080
|
+
function consumeLaunchEnvelope(environment = process.env) {
|
|
1081
|
+
const values = Object.fromEntries(SWARM_LAUNCH_ENV_KEYS.map((key) => [key, environment[key]]));
|
|
1082
|
+
for (const key of SWARM_LAUNCH_ENV_KEYS) delete environment[key];
|
|
1083
|
+
if (values.PI_SWARM_INVITE === void 0) {
|
|
1084
|
+
if (Object.values(values).some((value) => value !== void 0)) {
|
|
1085
|
+
throw new Error("Pi Agent Swarm launch envelope is incomplete");
|
|
1086
|
+
}
|
|
1087
|
+
return void 0;
|
|
1088
|
+
}
|
|
1089
|
+
const invite = bounded(values.PI_SWARM_INVITE, "invite", 256);
|
|
1090
|
+
const parentSessionId = safeId(values.PI_SWARM_PARENT_SESSION_ID, "parent session id");
|
|
1091
|
+
const launchId = safeId(values.PI_SWARM_LAUNCH_ID, "launch id");
|
|
1092
|
+
const kickoffCapability = safeId(values.PI_SWARM_KICKOFF_CAPABILITY, "kickoff capability");
|
|
1093
|
+
const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
|
|
1094
|
+
const childColor = optionalHexColor(values.PI_SWARM_COLOR);
|
|
1095
|
+
const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
|
|
1096
|
+
const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
|
|
1097
|
+
const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
|
|
1098
|
+
if (provider === void 0 !== (id === void 0)) {
|
|
1099
|
+
throw new Error("Pi Agent Swarm launch model identity is incomplete");
|
|
1100
|
+
}
|
|
1101
|
+
const thinking = values.PI_SWARM_THINKING;
|
|
1102
|
+
if (thinking !== void 0 && (!provider || !id)) {
|
|
1103
|
+
throw new Error("Pi Agent Swarm launch model identity is incomplete");
|
|
1104
|
+
}
|
|
1105
|
+
if (thinking !== void 0 && !THINKING_LEVELS.has(thinking)) {
|
|
1106
|
+
throw new Error("Pi Agent Swarm launch thinking level is invalid");
|
|
1107
|
+
}
|
|
1108
|
+
return {
|
|
1109
|
+
invite,
|
|
1110
|
+
parentSessionId,
|
|
1111
|
+
launchId,
|
|
1112
|
+
kickoffCapability,
|
|
1113
|
+
...childName ? { childName } : {},
|
|
1114
|
+
...childColor ? { childColor } : {},
|
|
1115
|
+
acceptsRequests,
|
|
1116
|
+
...provider && id ? {
|
|
1117
|
+
model: {
|
|
1118
|
+
provider,
|
|
1119
|
+
id,
|
|
1120
|
+
...thinking ? { thinkingLevel: thinking } : {}
|
|
1121
|
+
}
|
|
1122
|
+
} : {}
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
function launchEnvelopeEnvironment(envelope) {
|
|
1126
|
+
return {
|
|
1127
|
+
PI_SWARM_INVITE: envelope.invite,
|
|
1128
|
+
PI_SWARM_PARENT_SESSION_ID: envelope.parentSessionId,
|
|
1129
|
+
PI_SWARM_LAUNCH_ID: envelope.launchId,
|
|
1130
|
+
PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
|
|
1131
|
+
PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
|
|
1132
|
+
...envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {},
|
|
1133
|
+
...envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {},
|
|
1134
|
+
...envelope.model ? {
|
|
1135
|
+
PI_SWARM_MODEL_PROVIDER: envelope.model.provider,
|
|
1136
|
+
PI_SWARM_MODEL_ID: envelope.model.id,
|
|
1137
|
+
...envelope.model.thinkingLevel ? { PI_SWARM_THINKING: envelope.model.thinkingLevel } : {}
|
|
1138
|
+
} : {}
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
function parseBoolean(value) {
|
|
1142
|
+
if (value === void 0 || value === "0") return false;
|
|
1143
|
+
if (value === "1") return true;
|
|
1144
|
+
throw new Error("Pi Agent Swarm launch request policy is invalid");
|
|
1145
|
+
}
|
|
1146
|
+
function safeId(value, label) {
|
|
1147
|
+
if (!value || !SAFE_ID2.test(value)) throw new Error(`Pi Agent Swarm launch ${label} is invalid`);
|
|
1148
|
+
return value;
|
|
1149
|
+
}
|
|
1150
|
+
function bounded(value, label, maxBytes) {
|
|
1151
|
+
if (!value || value.includes("\0") || Buffer.byteLength(value) > maxBytes) {
|
|
1152
|
+
throw new Error(`Pi Agent Swarm launch ${label} is invalid`);
|
|
1153
|
+
}
|
|
1154
|
+
return value;
|
|
1155
|
+
}
|
|
1156
|
+
function optionalBounded(value, label, maxBytes) {
|
|
1157
|
+
return value === void 0 ? void 0 : bounded(value, label, maxBytes);
|
|
1158
|
+
}
|
|
1159
|
+
function optionalHexColor(value) {
|
|
1160
|
+
if (value === void 0) return void 0;
|
|
1161
|
+
const lower = value.toLowerCase();
|
|
1162
|
+
if (!/^#[0-9a-f]{6}$/u.test(lower)) throw new Error("Pi Agent Swarm launch color is invalid");
|
|
1163
|
+
return lower;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// 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";
|
|
1170
|
+
async function createPiLauncher(invocation, directory, embeddedEnvironment) {
|
|
1171
|
+
await assertPrivateDirectory(directory);
|
|
1172
|
+
const launcherPath = join3(directory, `launch-${randomBytes2(8).toString("hex")}.sh`);
|
|
1173
|
+
assertInside(directory, launcherPath);
|
|
1174
|
+
const command = [invocation.command, ...invocation.args];
|
|
1175
|
+
for (const value of command) {
|
|
1176
|
+
if (value.includes("\0")) throw new Error("Pi Agent Swarm launcher argument contains a NUL byte");
|
|
1177
|
+
}
|
|
1178
|
+
const environment = validateEmbeddedEnvironment(embeddedEnvironment);
|
|
1179
|
+
const setup = environment.length ? [
|
|
1180
|
+
`rm -f ${quoteShell(launcherPath)} || exit 1`,
|
|
1181
|
+
...environment.map(([key, value]) => `export ${key}=${quoteShell(value)}`)
|
|
1182
|
+
] : [];
|
|
1183
|
+
const source = ["#!/bin/sh", ...setup, `exec ${command.map(quoteShell).join(" ")}`, ""].join("\n");
|
|
1184
|
+
const handle = await open2(launcherPath, "wx", 448);
|
|
1185
|
+
try {
|
|
1186
|
+
await handle.writeFile(source, "utf8");
|
|
1187
|
+
await handle.sync();
|
|
1188
|
+
await handle.chmod(448);
|
|
1189
|
+
await handle.close();
|
|
1190
|
+
} catch (error) {
|
|
1191
|
+
await handle.close().catch(() => void 0);
|
|
1192
|
+
await rm2(launcherPath, { force: true }).catch(() => void 0);
|
|
1193
|
+
throw error;
|
|
1194
|
+
}
|
|
1195
|
+
let cleaned = false;
|
|
1196
|
+
return {
|
|
1197
|
+
path: launcherPath,
|
|
1198
|
+
command: launcherPath,
|
|
1199
|
+
async cleanup() {
|
|
1200
|
+
if (cleaned) return;
|
|
1201
|
+
cleaned = true;
|
|
1202
|
+
assertInside(directory, launcherPath);
|
|
1203
|
+
await rm2(launcherPath, { force: true });
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
function validateEmbeddedEnvironment(environment) {
|
|
1208
|
+
const entries = Object.entries(environment ?? {}).sort(([left], [right]) => left.localeCompare(right));
|
|
1209
|
+
let bytes = 0;
|
|
1210
|
+
for (const [key, value] of entries) {
|
|
1211
|
+
if (!/^[A-Z][A-Z0-9_]{0,63}$/u.test(key) || value.includes("\0")) {
|
|
1212
|
+
throw new Error("Pi Agent Swarm launch environment is invalid");
|
|
1213
|
+
}
|
|
1214
|
+
bytes += Buffer.byteLength(key) + Buffer.byteLength(value) + 1;
|
|
1215
|
+
}
|
|
1216
|
+
if (bytes > 24 * 1024) throw new Error("Pi Agent Swarm launch environment is too large");
|
|
1217
|
+
return entries;
|
|
1218
|
+
}
|
|
1219
|
+
function quoteShell(value) {
|
|
1220
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
1221
|
+
}
|
|
1222
|
+
async function assertPrivateDirectory(path2) {
|
|
1223
|
+
const info = await lstat2(path2);
|
|
1224
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
1225
|
+
throw new Error("Pi Agent Swarm launcher directory is invalid");
|
|
1226
|
+
}
|
|
1227
|
+
if (typeof process.getuid === "function" && info.uid !== process.getuid()) {
|
|
1228
|
+
throw new Error("Pi Agent Swarm launcher directory has another owner");
|
|
1229
|
+
}
|
|
1230
|
+
if ((info.mode & 511) !== 448) {
|
|
1231
|
+
throw new Error("Pi Agent Swarm launcher directory permissions are not private");
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
function assertInside(parent, candidate) {
|
|
1235
|
+
const rel = relative(resolve(parent), resolve(candidate));
|
|
1236
|
+
if (!rel || rel === ".." || rel.startsWith("../")) {
|
|
1237
|
+
throw new Error("Pi Agent Swarm launcher path escapes its runtime directory");
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// src/pi-invocation.ts
|
|
1242
|
+
import * as fs from "node:fs";
|
|
1243
|
+
import * as path from "node:path";
|
|
1244
|
+
import { getPackageDir } from "@earendil-works/pi-coding-agent";
|
|
1245
|
+
var CORE_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
|
|
1246
|
+
var MAX_DISPLAY_PATH_BYTES = 500;
|
|
1247
|
+
var PiInvocationError = class extends Error {
|
|
1248
|
+
constructor(message) {
|
|
1249
|
+
super(message);
|
|
1250
|
+
this.name = "PiInvocationError";
|
|
1251
|
+
}
|
|
1252
|
+
};
|
|
1253
|
+
function resolvePiInvocation(args, runtime = currentRuntime()) {
|
|
1254
|
+
const packageDirectory = existingDirectory(runtime.packageDir);
|
|
1255
|
+
const manifest = readManifest(packageDirectory);
|
|
1256
|
+
const declaredBin = resolveDeclaredBin(packageDirectory, manifest);
|
|
1257
|
+
const standalone = resolveStandaloneExecutable(packageDirectory, runtime);
|
|
1258
|
+
if (standalone) return { command: standalone, args: [...args] };
|
|
1259
|
+
if (runtime.runtimeKind !== "node" && runtime.runtimeKind !== "bun") {
|
|
1260
|
+
throw resolutionError(packageDirectory, "the host does not provide Node or Bun");
|
|
1261
|
+
}
|
|
1262
|
+
return {
|
|
1263
|
+
command: runtime.execPath,
|
|
1264
|
+
args: [resolveExistingFile(packageDirectory, declaredBin, "the declared bin.pi target is unavailable"), ...args]
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
function currentRuntime() {
|
|
1268
|
+
let packageDir;
|
|
1269
|
+
try {
|
|
1270
|
+
packageDir = getPackageDir();
|
|
1271
|
+
} catch {
|
|
1272
|
+
throw resolutionError("<unavailable>", "Pi core did not provide its package directory");
|
|
1273
|
+
}
|
|
1274
|
+
return {
|
|
1275
|
+
execPath: process.execPath,
|
|
1276
|
+
packageDir,
|
|
1277
|
+
runtimeKind: process.versions.bun ? "bun" : process.release.name === "node" && !process.versions.electron ? "node" : "unsupported"
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
function existingDirectory(value) {
|
|
1281
|
+
try {
|
|
1282
|
+
const resolved = fs.realpathSync(value);
|
|
1283
|
+
if (!fs.statSync(resolved).isDirectory()) throw new Error("not a directory");
|
|
1284
|
+
return resolved;
|
|
1285
|
+
} catch {
|
|
1286
|
+
throw resolutionError(value, "the package directory is unavailable");
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
function readManifest(packageDirectory) {
|
|
1290
|
+
let value;
|
|
1291
|
+
try {
|
|
1292
|
+
value = JSON.parse(fs.readFileSync(path.join(packageDirectory, "package.json"), "utf8"));
|
|
1293
|
+
} catch {
|
|
1294
|
+
throw resolutionError(packageDirectory, "the package manifest is unavailable or invalid");
|
|
1295
|
+
}
|
|
1296
|
+
if (!isRecord3(value) || value.name !== CORE_PACKAGE_NAME) {
|
|
1297
|
+
throw resolutionError(packageDirectory, "the package manifest has an unexpected package name");
|
|
1298
|
+
}
|
|
1299
|
+
return value;
|
|
1300
|
+
}
|
|
1301
|
+
function resolveDeclaredBin(packageDirectory, manifest) {
|
|
1302
|
+
const bin = manifest.bin;
|
|
1303
|
+
const piBin = isRecord3(bin) ? bin.pi : void 0;
|
|
1304
|
+
if (typeof piBin !== "string" || !piBin.trim()) {
|
|
1305
|
+
throw resolutionError(packageDirectory, "package.json bin.pi must be a non-empty string");
|
|
1306
|
+
}
|
|
1307
|
+
const candidate = path.resolve(packageDirectory, piBin);
|
|
1308
|
+
if (path.isAbsolute(piBin) || !isWithin(packageDirectory, candidate)) {
|
|
1309
|
+
throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
|
|
1310
|
+
}
|
|
1311
|
+
return candidate;
|
|
1312
|
+
}
|
|
1313
|
+
function resolveExistingFile(packageDirectory, candidate, reason) {
|
|
1314
|
+
try {
|
|
1315
|
+
const resolved = fs.realpathSync(candidate);
|
|
1316
|
+
if (!fs.statSync(resolved).isFile()) throw new Error("not a file");
|
|
1317
|
+
if (!isWithin(packageDirectory, resolved)) {
|
|
1318
|
+
throw resolutionError(packageDirectory, "the declared bin.pi target escapes the package");
|
|
1319
|
+
}
|
|
1320
|
+
return resolved;
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
if (error instanceof PiInvocationError) throw error;
|
|
1323
|
+
throw resolutionError(packageDirectory, reason);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
function resolveStandaloneExecutable(packageDirectory, runtime) {
|
|
1327
|
+
if (runtime.runtimeKind !== "bun" || !/^pi(?:\.exe)?$/iu.test(path.basename(runtime.execPath))) {
|
|
1328
|
+
return void 0;
|
|
1329
|
+
}
|
|
1330
|
+
let resolved;
|
|
1331
|
+
let mode;
|
|
1332
|
+
try {
|
|
1333
|
+
resolved = fs.realpathSync(runtime.execPath);
|
|
1334
|
+
const info = fs.statSync(resolved);
|
|
1335
|
+
if (!info.isFile()) throw new Error("not a file");
|
|
1336
|
+
mode = info.mode;
|
|
1337
|
+
} catch {
|
|
1338
|
+
throw resolutionError(packageDirectory, "the standalone Pi executable is unavailable");
|
|
1339
|
+
}
|
|
1340
|
+
if (path.dirname(resolved) !== packageDirectory) return void 0;
|
|
1341
|
+
if (process.platform !== "win32" && (mode & 73) === 0) {
|
|
1342
|
+
throw resolutionError(packageDirectory, "the standalone Pi executable is not executable");
|
|
1343
|
+
}
|
|
1344
|
+
return resolved;
|
|
1345
|
+
}
|
|
1346
|
+
function isWithin(parent, candidate) {
|
|
1347
|
+
const relative4 = path.relative(parent, candidate);
|
|
1348
|
+
return relative4 === "" || !relative4.startsWith(`..${path.sep}`) && relative4 !== ".." && !path.isAbsolute(relative4);
|
|
1349
|
+
}
|
|
1350
|
+
function resolutionError(packageDirectory, reason) {
|
|
1351
|
+
const displayed = Buffer.from(packageDirectory).subarray(0, MAX_DISPLAY_PATH_BYTES).toString();
|
|
1352
|
+
return new PiInvocationError(
|
|
1353
|
+
`Unable to resolve the Pi CLI from ${JSON.stringify(displayed)}: ${reason}. Reinstall the matching Pi core package before spawning a session.`
|
|
1354
|
+
);
|
|
1355
|
+
}
|
|
1356
|
+
function isRecord3(value) {
|
|
1357
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// src/reload-handoff.ts
|
|
1361
|
+
var RELOAD_HANDOFFS = /* @__PURE__ */ Symbol.for("pi-agent-swarm/reload-handoffs");
|
|
1362
|
+
function putReloadHandoff(owner, handoff) {
|
|
1363
|
+
reloadHandoffs().set(owner, handoff);
|
|
1364
|
+
}
|
|
1365
|
+
function takeReloadHandoff(owner, now) {
|
|
1366
|
+
const store = reloadHandoffs();
|
|
1367
|
+
const value = store.get(owner);
|
|
1368
|
+
store.delete(owner);
|
|
1369
|
+
return value && value.expiresAt >= now ? value : void 0;
|
|
1370
|
+
}
|
|
1371
|
+
function reloadHandoffs() {
|
|
1372
|
+
const root = globalThis;
|
|
1373
|
+
const existing = root[RELOAD_HANDOFFS];
|
|
1374
|
+
if (existing instanceof WeakMap) return existing;
|
|
1375
|
+
const created = /* @__PURE__ */ new WeakMap();
|
|
1376
|
+
root[RELOAD_HANDOFFS] = created;
|
|
1377
|
+
return created;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
// src/i3-workspace.ts
|
|
1381
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
1382
|
+
var DEFAULT_TIMEOUT_MS = 3e3;
|
|
1383
|
+
var DEFAULT_POLL_INTERVAL_MS = 100;
|
|
1384
|
+
var MAX_ANCESTOR_DEPTH = 8;
|
|
1385
|
+
function detectI3(environment) {
|
|
1386
|
+
return typeof environment.I3SOCK === "string" && environment.I3SOCK.length > 0 && typeof environment.DISPLAY === "string" && environment.DISPLAY.length > 0;
|
|
1387
|
+
}
|
|
1388
|
+
var I3WorkspacePinner = class {
|
|
1389
|
+
execute;
|
|
1390
|
+
readProcessId;
|
|
1391
|
+
readPpid;
|
|
1392
|
+
sleep;
|
|
1393
|
+
now;
|
|
1394
|
+
timeoutMs;
|
|
1395
|
+
pollIntervalMs;
|
|
1396
|
+
beforeWindowIds;
|
|
1397
|
+
constructor(options) {
|
|
1398
|
+
this.execute = options.execute;
|
|
1399
|
+
this.readProcessId = options.readProcessId ?? (() => process.pid);
|
|
1400
|
+
this.readPpid = options.readPpid ?? readProcPpid;
|
|
1401
|
+
this.sleep = options.sleep ?? abortableSleep;
|
|
1402
|
+
this.now = options.now ?? Date.now;
|
|
1403
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1404
|
+
this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Snapshot the tree before the new window is created and return the workspace
|
|
1408
|
+
* that hosts this Pi session's terminal window, located by `_NET_WM_PID` and the
|
|
1409
|
+
* process tree rather than by the currently focused workspace.
|
|
1410
|
+
*/
|
|
1411
|
+
async captureLeadWorkspace(signal) {
|
|
1412
|
+
const tree = await this.getTree(signal);
|
|
1413
|
+
this.beforeWindowIds = collectWindowIds(tree);
|
|
1414
|
+
const workspace = await this.findSelfWorkspace(tree, signal);
|
|
1415
|
+
if (!workspace) throw new Error("Pi Agent Swarm could not locate the lead session's i3 workspace");
|
|
1416
|
+
return workspace;
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Wait for the one new window to appear and move it onto the captured lead
|
|
1420
|
+
* workspace. Best-effort callers catch failures; the window is already open.
|
|
1421
|
+
*/
|
|
1422
|
+
async pinNewWindowToLeadWorkspace(leadWorkspace, signal) {
|
|
1423
|
+
const before = this.beforeWindowIds;
|
|
1424
|
+
if (!before) throw new Error("Pi Agent Swarm must capture the lead workspace before pinning a window");
|
|
1425
|
+
const deadline = this.now() + this.timeoutMs;
|
|
1426
|
+
while (true) {
|
|
1427
|
+
throwIfAborted3(signal, "Pi Agent Swarm i3 workspace pin was aborted");
|
|
1428
|
+
const tree = await this.getTree(signal);
|
|
1429
|
+
const conId = findNewWindowId(tree, before);
|
|
1430
|
+
if (conId !== void 0) {
|
|
1431
|
+
await this.moveToWorkspace(conId, leadWorkspace, signal);
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
if (this.now() >= deadline) {
|
|
1435
|
+
throw new Error("Pi Agent Swarm timed out waiting for the new window to appear");
|
|
1436
|
+
}
|
|
1437
|
+
await this.sleep(this.pollIntervalMs, signal);
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
async findSelfWorkspace(tree, signal) {
|
|
1441
|
+
const ancestors = collectAncestors(this.readProcessId(), this.readPpid);
|
|
1442
|
+
for (const node of windowNodes(tree)) {
|
|
1443
|
+
const ownerPid = await this.xpropPid(node.window, signal);
|
|
1444
|
+
if (ownerPid !== void 0 && ancestors.includes(ownerPid)) {
|
|
1445
|
+
return workspaceOf(tree, node.id);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
return void 0;
|
|
1449
|
+
}
|
|
1450
|
+
async xpropPid(windowId, signal) {
|
|
1451
|
+
let result;
|
|
1452
|
+
try {
|
|
1453
|
+
result = await this.execute("xprop", ["-id", String(windowId), "_NET_WM_PID"], {
|
|
1454
|
+
...signal ? { signal } : {},
|
|
1455
|
+
timeoutMs: this.timeoutMs
|
|
1456
|
+
});
|
|
1457
|
+
} catch {
|
|
1458
|
+
return void 0;
|
|
1459
|
+
}
|
|
1460
|
+
if (result.code !== 0 || result.killed) return void 0;
|
|
1461
|
+
const match = /_NET_WM_PID[^=]*=\s*(\d+)/u.exec(result.stdout);
|
|
1462
|
+
return match ? Number(match[1]) : void 0;
|
|
1463
|
+
}
|
|
1464
|
+
async getTree(signal) {
|
|
1465
|
+
const result = await this.execute("i3-msg", ["-t", "get_tree"], {
|
|
1466
|
+
...signal ? { signal } : {},
|
|
1467
|
+
timeoutMs: this.timeoutMs
|
|
1468
|
+
});
|
|
1469
|
+
if (result.code !== 0 || result.killed) {
|
|
1470
|
+
throw new Error("Pi Agent Swarm could not query the i3 window tree");
|
|
1471
|
+
}
|
|
1472
|
+
try {
|
|
1473
|
+
return JSON.parse(result.stdout);
|
|
1474
|
+
} catch {
|
|
1475
|
+
throw new Error("Pi Agent Swarm received an invalid i3 window tree");
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
async moveToWorkspace(conId, workspace, signal) {
|
|
1479
|
+
const result = await this.execute(
|
|
1480
|
+
"i3-msg",
|
|
1481
|
+
[`[con_id=${conId}] move container to workspace ${quoteI3Value(workspace)}`],
|
|
1482
|
+
{
|
|
1483
|
+
...signal ? { signal } : {},
|
|
1484
|
+
timeoutMs: this.timeoutMs
|
|
1485
|
+
}
|
|
1486
|
+
);
|
|
1487
|
+
if (result.code !== 0 || result.killed) {
|
|
1488
|
+
throw new Error("Pi Agent Swarm could not move the new window to the lead workspace");
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
};
|
|
1492
|
+
function collectWindowIds(tree) {
|
|
1493
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1494
|
+
visit(tree, (node) => {
|
|
1495
|
+
if (typeof node.window === "number") ids.add(node.window);
|
|
1496
|
+
});
|
|
1497
|
+
return ids;
|
|
1498
|
+
}
|
|
1499
|
+
function windowNodes(tree) {
|
|
1500
|
+
const nodes = [];
|
|
1501
|
+
visit(tree, (node) => {
|
|
1502
|
+
if (typeof node.window === "number") nodes.push(node);
|
|
1503
|
+
});
|
|
1504
|
+
return nodes;
|
|
1505
|
+
}
|
|
1506
|
+
function findNewWindowId(tree, before) {
|
|
1507
|
+
let found;
|
|
1508
|
+
visit(tree, (node) => {
|
|
1509
|
+
if (found !== void 0) return;
|
|
1510
|
+
if (typeof node.window === "number" && !before.has(node.window)) {
|
|
1511
|
+
found = node.id;
|
|
1512
|
+
}
|
|
1513
|
+
});
|
|
1514
|
+
return found;
|
|
1515
|
+
}
|
|
1516
|
+
function workspaceOf(tree, conId) {
|
|
1517
|
+
let found;
|
|
1518
|
+
visit(tree, (node, workspaceName) => {
|
|
1519
|
+
if (found !== void 0) return;
|
|
1520
|
+
const current = node.type === "workspace" && typeof node.name === "string" ? node.name : workspaceName;
|
|
1521
|
+
if (node.id === conId) found = current;
|
|
1522
|
+
});
|
|
1523
|
+
return found;
|
|
1524
|
+
}
|
|
1525
|
+
function visit(node, callback) {
|
|
1526
|
+
const walk = (current, workspaceName) => {
|
|
1527
|
+
const nextWorkspace = current.type === "workspace" && typeof current.name === "string" ? current.name : workspaceName;
|
|
1528
|
+
callback(current, nextWorkspace);
|
|
1529
|
+
for (const child of [...current.nodes ?? [], ...current.floating_nodes ?? []]) {
|
|
1530
|
+
walk(child, nextWorkspace);
|
|
1531
|
+
}
|
|
1532
|
+
};
|
|
1533
|
+
walk(node, void 0);
|
|
1534
|
+
}
|
|
1535
|
+
function collectAncestors(pid, readPpid) {
|
|
1536
|
+
const ancestors = [pid];
|
|
1537
|
+
let current = pid;
|
|
1538
|
+
for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {
|
|
1539
|
+
const parent = readPpid(current);
|
|
1540
|
+
if (parent === void 0 || parent <= 1) break;
|
|
1541
|
+
ancestors.push(parent);
|
|
1542
|
+
current = parent;
|
|
1543
|
+
}
|
|
1544
|
+
return ancestors;
|
|
1545
|
+
}
|
|
1546
|
+
function readProcPpid(pid) {
|
|
1547
|
+
try {
|
|
1548
|
+
const stat3 = readFileSync2(`/proc/${pid}/stat`, "utf8");
|
|
1549
|
+
const close = stat3.lastIndexOf(")");
|
|
1550
|
+
if (close < 0) return void 0;
|
|
1551
|
+
const fields = stat3.slice(close + 2).split(" ");
|
|
1552
|
+
const ppid = Number(fields[1]);
|
|
1553
|
+
return Number.isInteger(ppid) && ppid > 0 ? ppid : void 0;
|
|
1554
|
+
} catch {
|
|
1555
|
+
return void 0;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
function quoteI3Value(value) {
|
|
1559
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
|
1560
|
+
}
|
|
1561
|
+
async function abortableSleep(milliseconds, signal) {
|
|
1562
|
+
throwIfAborted3(signal, "Pi Agent Swarm i3 workspace wait was aborted");
|
|
1563
|
+
await new Promise((resolve6, reject) => {
|
|
1564
|
+
const finish = (error) => {
|
|
1565
|
+
clearTimeout(timer);
|
|
1566
|
+
signal?.removeEventListener("abort", abort);
|
|
1567
|
+
if (error) reject(error);
|
|
1568
|
+
else resolve6();
|
|
1569
|
+
};
|
|
1570
|
+
const timer = setTimeout(() => finish(), milliseconds);
|
|
1571
|
+
const abort = () => finish(abortError("Pi Agent Swarm i3 workspace wait was aborted"));
|
|
1572
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1573
|
+
if (signal?.aborted) abort();
|
|
1574
|
+
});
|
|
1575
|
+
}
|
|
1576
|
+
function throwIfAborted3(signal, message) {
|
|
1577
|
+
if (signal?.aborted) throw abortError(message);
|
|
1578
|
+
}
|
|
1579
|
+
function abortError(message) {
|
|
1580
|
+
const error = new Error(message);
|
|
1581
|
+
error.name = "AbortError";
|
|
1582
|
+
return error;
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
// src/terminal.ts
|
|
1586
|
+
function createDefaultTerminalPort(pi, externalCommand, pinToLeadWorkspace = false) {
|
|
1587
|
+
const options = {
|
|
1588
|
+
execute: async (command, args, execution) => pi.exec(command, args, {
|
|
1589
|
+
...execution.signal ? { signal: execution.signal } : {},
|
|
1590
|
+
timeout: execution.timeoutMs
|
|
1591
|
+
})
|
|
1592
|
+
};
|
|
1593
|
+
return new ExternalTerminalAdapter(
|
|
1594
|
+
externalCommand ?? ["alacritty", "-e"],
|
|
1595
|
+
pinToLeadWorkspace && detectI3(process.env) ? new I3WorkspacePinner(options) : void 0
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
function isTerminalLaunchError(error) {
|
|
1599
|
+
return error instanceof ExternalLaunchError;
|
|
1600
|
+
}
|
|
1601
|
+
function createTerminalLaunchError(message, splitCreated, terminalId) {
|
|
1602
|
+
return new ExternalLaunchError(message, splitCreated, terminalId);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
// src/transport.ts
|
|
1606
|
+
import { randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
1607
|
+
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";
|
|
1609
|
+
import { createServer } from "node:net";
|
|
1610
|
+
import { basename as basename4, dirname as dirname4, join as join6, resolve as resolve4 } from "node:path";
|
|
1611
|
+
|
|
1612
|
+
// 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";
|
|
1615
|
+
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";
|
|
1617
|
+
var MAX_UNIX_SOCKET_PATH_BYTES = 103;
|
|
1618
|
+
var MAX_MANIFEST_BYTES = 8 * 1024;
|
|
1619
|
+
var ORPHAN_GRACE_MS = 6e4;
|
|
1620
|
+
var MAX_RUNTIME_SCAN_ENTRIES = 512;
|
|
1621
|
+
var SAFE_GROUP_ID = /^[a-f0-9]{32}$/u;
|
|
1622
|
+
var SAFE_ENDPOINT_ID = /^[a-f0-9]{24}$/u;
|
|
1623
|
+
var SAFE_SOCKET_NAME = /^([a-f0-9]{24})\.sock$/u;
|
|
1624
|
+
var SAFE_MANIFEST_NAME = /^([a-f0-9]{24})\.json$/u;
|
|
1625
|
+
var SAFE_TEMPORARY_NAME = /^\.([a-f0-9]{24})\.json\.[a-f0-9]{16}\.tmp$/u;
|
|
1626
|
+
var SAFE_LAUNCHER_NAME = /^launch-[a-f0-9]{16}\.sh$/u;
|
|
1627
|
+
function defaultRuntimeBaseDirectory() {
|
|
1628
|
+
if (process.platform === "win32") {
|
|
1629
|
+
throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
|
|
1630
|
+
}
|
|
1631
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
1632
|
+
if (process.platform === "darwin") return join5("/tmp", `pi-swarm-${uid}`);
|
|
1633
|
+
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");
|
|
1636
|
+
}
|
|
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}`);
|
|
1641
|
+
}
|
|
1642
|
+
async function ensureGroupRuntimeDirectory(groupId, options = {}) {
|
|
1643
|
+
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`);
|
|
1647
|
+
if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
1648
|
+
throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
|
|
1649
|
+
}
|
|
1650
|
+
await ensurePrivateDirectory(baseDirectory);
|
|
1651
|
+
await ensurePrivateDirectory(directory);
|
|
1652
|
+
return directory;
|
|
1653
|
+
}
|
|
1654
|
+
function createEndpointPaths(directory, endpointId) {
|
|
1655
|
+
if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
|
|
1656
|
+
const socketPath = join5(directory, `${endpointId}.sock`);
|
|
1657
|
+
if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
|
|
1658
|
+
throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
|
|
1659
|
+
}
|
|
1660
|
+
return {
|
|
1661
|
+
directory,
|
|
1662
|
+
endpointId,
|
|
1663
|
+
socketPath,
|
|
1664
|
+
manifestPath: join5(directory, `${endpointId}.json`)
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
function randomEndpointId() {
|
|
1668
|
+
return randomBytes3(12).toString("hex");
|
|
1669
|
+
}
|
|
1670
|
+
async function publishManifest(manifestPath, manifest) {
|
|
1671
|
+
const parent = dirname3(manifestPath);
|
|
1672
|
+
await assertPrivateDirectory2(parent);
|
|
1673
|
+
assertOwnedPath(parent, manifestPath, ".json");
|
|
1674
|
+
const body = `${JSON.stringify(manifest)}
|
|
1675
|
+
`;
|
|
1676
|
+
if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
|
|
1677
|
+
throw new Error("Pi Agent Swarm endpoint manifest is too large");
|
|
1678
|
+
}
|
|
1679
|
+
const temporaryPath = join5(parent, `.${basename3(manifestPath)}.${randomBytes3(8).toString("hex")}.tmp`);
|
|
1680
|
+
let handle;
|
|
1681
|
+
try {
|
|
1682
|
+
handle = await open3(temporaryPath, "wx", 384);
|
|
1683
|
+
await handle.writeFile(body, "utf8");
|
|
1684
|
+
await handle.sync();
|
|
1685
|
+
await handle.close();
|
|
1686
|
+
handle = void 0;
|
|
1687
|
+
await rename2(temporaryPath, manifestPath);
|
|
1688
|
+
await chmod(manifestPath, 384);
|
|
1689
|
+
} finally {
|
|
1690
|
+
await handle?.close().catch(() => void 0);
|
|
1691
|
+
await rm3(temporaryPath, { force: true }).catch(() => void 0);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
async function cleanupStaleRuntimeEntries(directory, now = Date.now()) {
|
|
1695
|
+
await assertPrivateDirectory2(directory);
|
|
1696
|
+
const names = /* @__PURE__ */ new Set();
|
|
1697
|
+
let scanned = 0;
|
|
1698
|
+
let saturated = false;
|
|
1699
|
+
const handle = await opendir(directory);
|
|
1700
|
+
try {
|
|
1701
|
+
for await (const entry of handle) {
|
|
1702
|
+
if (scanned >= MAX_RUNTIME_SCAN_ENTRIES) {
|
|
1703
|
+
saturated = true;
|
|
1704
|
+
break;
|
|
1705
|
+
}
|
|
1706
|
+
scanned += 1;
|
|
1707
|
+
names.add(entry.name);
|
|
1708
|
+
}
|
|
1709
|
+
} finally {
|
|
1710
|
+
await handle.close().catch(() => void 0);
|
|
1711
|
+
}
|
|
1712
|
+
let removedSockets = 0;
|
|
1713
|
+
let removedTemporaryFiles = 0;
|
|
1714
|
+
for (const name of names) {
|
|
1715
|
+
const socketMatch = SAFE_SOCKET_NAME.exec(name);
|
|
1716
|
+
if (socketMatch) {
|
|
1717
|
+
const manifestPath = join5(directory, `${socketMatch[1]}.json`);
|
|
1718
|
+
if (!await pathExists(manifestPath)) {
|
|
1719
|
+
if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
|
|
1720
|
+
}
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
if (SAFE_TEMPORARY_NAME.test(name) || SAFE_LAUNCHER_NAME.test(name)) {
|
|
1724
|
+
if (await removeStaleOwnedEntry(directory, name, "file", now)) {
|
|
1725
|
+
removedTemporaryFiles += 1;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
return { removedSockets, removedTemporaryFiles, saturated };
|
|
1730
|
+
}
|
|
1731
|
+
async function removeOwnedEndpoint(paths) {
|
|
1732
|
+
for (const path2 of [paths.manifestPath, paths.socketPath]) {
|
|
1733
|
+
assertOwnedPath(paths.directory, path2);
|
|
1734
|
+
await rm3(path2, { force: true }).catch(() => void 0);
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
function endpointIdFromManifestName(name) {
|
|
1738
|
+
return SAFE_MANIFEST_NAME.exec(name)?.[1];
|
|
1739
|
+
}
|
|
1740
|
+
function assertOwnedPath(parent, candidate, suffix) {
|
|
1741
|
+
const resolvedParent = resolve3(parent);
|
|
1742
|
+
const resolvedCandidate = resolve3(candidate);
|
|
1743
|
+
const rel = relative3(resolvedParent, resolvedCandidate);
|
|
1744
|
+
if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
|
|
1745
|
+
throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
|
|
1746
|
+
}
|
|
1747
|
+
if (suffix && !basename3(resolvedCandidate).endsWith(suffix)) {
|
|
1748
|
+
throw new Error("Pi Agent Swarm runtime path has an invalid suffix");
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
async function removeStaleOwnedEntry(directory, name, kind, now) {
|
|
1752
|
+
const path2 = join5(directory, name);
|
|
1753
|
+
assertOwnedPath(directory, path2);
|
|
1754
|
+
try {
|
|
1755
|
+
const first = await lstat3(path2, { bigint: true });
|
|
1756
|
+
assertOwner(Number(first.uid));
|
|
1757
|
+
if (kind === "file" ? !first.isFile() : !first.isSocket()) return false;
|
|
1758
|
+
if (now - Number(first.mtimeMs) < ORPHAN_GRACE_MS) return false;
|
|
1759
|
+
const current = await lstat3(path2, { bigint: true });
|
|
1760
|
+
if (current.dev !== first.dev || current.ino !== first.ino || current.mtimeMs !== first.mtimeMs || (kind === "file" ? !current.isFile() : !current.isSocket())) {
|
|
1761
|
+
return false;
|
|
1762
|
+
}
|
|
1763
|
+
await rm3(path2);
|
|
1764
|
+
return true;
|
|
1765
|
+
} catch (error) {
|
|
1766
|
+
if (isMissing(error)) return false;
|
|
1767
|
+
throw error;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
async function ensurePrivateDirectory(path2) {
|
|
1771
|
+
try {
|
|
1772
|
+
const info = await lstat3(path2);
|
|
1773
|
+
if (info.isSymbolicLink()) throw new Error("Pi Agent Swarm runtime directory is a symbolic link");
|
|
1774
|
+
if (!info.isDirectory()) throw new Error("Pi Agent Swarm runtime path is not a directory");
|
|
1775
|
+
assertOwner(info.uid);
|
|
1776
|
+
if ((info.mode & 511) !== 448) await chmod(path2, 448);
|
|
1777
|
+
await assertPrivateDirectory2(path2);
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
if (!isMissing(error)) throw error;
|
|
1780
|
+
await mkdir2(path2, { recursive: true, mode: 448 });
|
|
1781
|
+
await chmod(path2, 448);
|
|
1782
|
+
await assertPrivateDirectory2(path2);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
async function assertPrivateDirectory2(path2) {
|
|
1786
|
+
const info = await lstat3(path2);
|
|
1787
|
+
if (info.isSymbolicLink()) throw new Error("Pi Agent Swarm runtime directory is a symbolic link");
|
|
1788
|
+
if (!info.isDirectory()) throw new Error("Pi Agent Swarm runtime path is not a directory");
|
|
1789
|
+
assertOwner(info.uid);
|
|
1790
|
+
if ((info.mode & 511) !== 448) {
|
|
1791
|
+
throw new Error("Pi Agent Swarm runtime directory permissions are not private");
|
|
1792
|
+
}
|
|
1793
|
+
const resolved = await realpath(path2);
|
|
1794
|
+
const resolvedInfo = await stat(resolved);
|
|
1795
|
+
assertOwner(resolvedInfo.uid);
|
|
1796
|
+
}
|
|
1797
|
+
function assertOwner(uid) {
|
|
1798
|
+
if (typeof process.getuid !== "function") return;
|
|
1799
|
+
if (uid !== process.getuid()) throw new Error("Pi Agent Swarm runtime path is owned by another user");
|
|
1800
|
+
}
|
|
1801
|
+
async function pathExists(path2) {
|
|
1802
|
+
try {
|
|
1803
|
+
await lstat3(path2);
|
|
1804
|
+
return true;
|
|
1805
|
+
} catch (error) {
|
|
1806
|
+
if (isMissing(error)) return false;
|
|
1807
|
+
throw error;
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
function isMissing(error) {
|
|
1811
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// src/transport-io.ts
|
|
1815
|
+
import { constants as constants2 } from "node:fs";
|
|
1816
|
+
import { open as open4 } from "node:fs/promises";
|
|
1817
|
+
import { createConnection } from "node:net";
|
|
1818
|
+
import { TextDecoder as TextDecoder3 } from "node:util";
|
|
1819
|
+
function requestFrame(endpointPath, frame, signal, timeoutMs) {
|
|
1820
|
+
assertPositiveDuration(timeoutMs, "Pi Agent Swarm request timeout");
|
|
1821
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1822
|
+
let settled = false;
|
|
1823
|
+
let received = false;
|
|
1824
|
+
const socket = createConnection(endpointPath);
|
|
1825
|
+
const finish = (error, value) => {
|
|
1826
|
+
if (settled) return;
|
|
1827
|
+
settled = true;
|
|
1828
|
+
clearTimeout(timer);
|
|
1829
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1830
|
+
socket.destroy();
|
|
1831
|
+
if (error) rejectPromise(error);
|
|
1832
|
+
else resolvePromise(value);
|
|
1833
|
+
};
|
|
1834
|
+
const decoder = new JsonLineDecoder({
|
|
1835
|
+
onValue: (value) => {
|
|
1836
|
+
if (received) {
|
|
1837
|
+
finish(new Error("Pi Agent Swarm peer returned multiple response frames"));
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
received = true;
|
|
1841
|
+
finish(void 0, value);
|
|
1842
|
+
},
|
|
1843
|
+
onError: (error) => finish(error)
|
|
1844
|
+
});
|
|
1845
|
+
const timer = setTimeout(
|
|
1846
|
+
() => finish(new SwarmEndpointError("ETIMEDOUT", "Pi Agent Swarm request timed out")),
|
|
1847
|
+
timeoutMs
|
|
1848
|
+
);
|
|
1849
|
+
timer.unref();
|
|
1850
|
+
const onAbort = () => finish(abortError2("Pi Agent Swarm request aborted"));
|
|
1851
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1852
|
+
socket.once("connect", () => {
|
|
1853
|
+
void writeFrame(socket, frame).catch(
|
|
1854
|
+
(error) => finish(error instanceof Error ? error : new Error(String(error)))
|
|
1855
|
+
);
|
|
1856
|
+
});
|
|
1857
|
+
socket.on("data", (chunk) => decoder.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
|
|
1858
|
+
socket.once("error", (error) => {
|
|
1859
|
+
finish(
|
|
1860
|
+
new SwarmEndpointError(error.code ?? "EIO", `Pi Agent Swarm endpoint failed: ${error.code ?? "I/O error"}`)
|
|
1861
|
+
);
|
|
1862
|
+
});
|
|
1863
|
+
socket.once("close", () => {
|
|
1864
|
+
if (!settled) {
|
|
1865
|
+
finish(new SwarmEndpointError("ECONNRESET", "Pi Agent Swarm endpoint closed without a response"));
|
|
1866
|
+
}
|
|
1867
|
+
});
|
|
1868
|
+
if (signal?.aborted) onAbort();
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
async function writeFrame(socket, frame) {
|
|
1872
|
+
const data = Buffer.from(`${JSON.stringify(frame)}
|
|
1873
|
+
`, "utf8");
|
|
1874
|
+
if (data.length > MAX_FRAME_BYTES) throw new Error("Pi Agent Swarm frame is too large");
|
|
1875
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
1876
|
+
socket.write(data, (error) => error ? rejectPromise(error) : resolvePromise());
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1879
|
+
function listenSocketServer(server, path2, signal) {
|
|
1880
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1881
|
+
let settled = false;
|
|
1882
|
+
const finish = (error) => {
|
|
1883
|
+
if (settled) return;
|
|
1884
|
+
settled = true;
|
|
1885
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1886
|
+
server.off("error", onError);
|
|
1887
|
+
if (error) rejectPromise(error);
|
|
1888
|
+
else resolvePromise();
|
|
1889
|
+
};
|
|
1890
|
+
const onError = (error) => finish(error);
|
|
1891
|
+
const onAbort = () => {
|
|
1892
|
+
server.close();
|
|
1893
|
+
finish(abortError2("Pi Agent Swarm transport start aborted"));
|
|
1894
|
+
};
|
|
1895
|
+
server.once("error", onError);
|
|
1896
|
+
server.listen(path2, () => finish());
|
|
1897
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1898
|
+
if (signal?.aborted) onAbort();
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
function closeSocketServer(server) {
|
|
1902
|
+
return new Promise((resolvePromise) => {
|
|
1903
|
+
try {
|
|
1904
|
+
server.close(() => resolvePromise());
|
|
1905
|
+
} catch {
|
|
1906
|
+
resolvePromise();
|
|
1907
|
+
}
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
async function readBoundedUtf8(path2, maximum) {
|
|
1911
|
+
const handle = await open4(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
1912
|
+
try {
|
|
1913
|
+
return await readBoundedHandleUtf8(handle, maximum);
|
|
1914
|
+
} finally {
|
|
1915
|
+
await handle.close();
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
async function readBoundedHandleUtf8(handle, maximum) {
|
|
1919
|
+
const buffer = Buffer.alloc(maximum + 1);
|
|
1920
|
+
let offset = 0;
|
|
1921
|
+
while (offset < buffer.length) {
|
|
1922
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
1923
|
+
if (bytesRead === 0) break;
|
|
1924
|
+
offset += bytesRead;
|
|
1925
|
+
}
|
|
1926
|
+
if (offset > maximum) throw new Error("Pi Agent Swarm endpoint manifest is too large");
|
|
1927
|
+
return new TextDecoder3("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));
|
|
1928
|
+
}
|
|
1929
|
+
var SwarmEndpointError = class extends Error {
|
|
1930
|
+
constructor(code, message) {
|
|
1931
|
+
super(message);
|
|
1932
|
+
this.code = code;
|
|
1933
|
+
this.name = "SwarmEndpointError";
|
|
1934
|
+
}
|
|
1935
|
+
code;
|
|
1936
|
+
};
|
|
1937
|
+
function isDeadEndpointError(error) {
|
|
1938
|
+
return error instanceof SwarmEndpointError && (error.code === "ENOENT" || error.code === "ECONNREFUSED" || error.code === "ECONNRESET" || error.code === "ETIMEDOUT");
|
|
1939
|
+
}
|
|
1940
|
+
function abortError2(message) {
|
|
1941
|
+
const error = new Error(message);
|
|
1942
|
+
error.name = "AbortError";
|
|
1943
|
+
return error;
|
|
1944
|
+
}
|
|
1945
|
+
function assertPositiveDuration(value, label) {
|
|
1946
|
+
if (!Number.isFinite(value) || value < 1) throw new Error(`${label} is invalid`);
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
// src/transport.ts
|
|
1950
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 2e3;
|
|
1951
|
+
var DEFAULT_DISCOVERY_DEADLINE_MS = 2e3;
|
|
1952
|
+
var DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS = 500;
|
|
1953
|
+
var MAX_DISCOVERY_MANIFESTS = 64;
|
|
1954
|
+
var MAX_DISCOVERY_CONCURRENCY = 16;
|
|
1955
|
+
var MAX_DISCOVERY_ISSUES = 32;
|
|
1956
|
+
var MAX_PENDING_CONNECTIONS = 32;
|
|
1957
|
+
var MAX_INFLIGHT_DELIVERIES = 8;
|
|
1958
|
+
var MESSAGE_DEDUP_CAPACITY = 1024;
|
|
1959
|
+
var MESSAGE_DEDUP_TTL_MS = 10 * 6e4;
|
|
1960
|
+
var FRAME_REPLAY_CAPACITY = 2048;
|
|
1961
|
+
var FRAME_REPLAY_TTL_MS = 2 * 6e4;
|
|
1962
|
+
var MAX_REQUESTS_PER_MINUTE = 60;
|
|
1963
|
+
var MAX_TOTAL_REQUESTS_PER_MINUTE = 240;
|
|
1964
|
+
var RATE_WINDOW_MS = 6e4;
|
|
1965
|
+
var SAFE_SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
1966
|
+
var SwarmTransport = class {
|
|
1967
|
+
constructor(options) {
|
|
1968
|
+
this.options = options;
|
|
1969
|
+
if (process.platform === "win32") {
|
|
1970
|
+
throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
|
|
1971
|
+
}
|
|
1972
|
+
if (options.group.secret.length !== 32) throw new Error("Pi Agent Swarm group secret is invalid");
|
|
1973
|
+
if (options.requestTimeoutMs !== void 0) {
|
|
1974
|
+
assertPositiveDuration2(options.requestTimeoutMs, "Pi Agent Swarm request timeout");
|
|
1975
|
+
}
|
|
1976
|
+
if (options.discoveryDeadlineMs !== void 0) {
|
|
1977
|
+
assertPositiveDuration2(options.discoveryDeadlineMs, "Pi Agent Swarm discovery deadline");
|
|
1978
|
+
}
|
|
1979
|
+
if (options.discoveryProbeTimeoutMs !== void 0) {
|
|
1980
|
+
assertPositiveDuration2(options.discoveryProbeTimeoutMs, "Pi Agent Swarm discovery probe timeout");
|
|
1981
|
+
}
|
|
1982
|
+
if (!SAFE_SESSION_ID.test(options.peer.sessionId)) {
|
|
1983
|
+
throw new Error("Pi Agent Swarm local session id is invalid");
|
|
1984
|
+
}
|
|
1985
|
+
if (options.peer.protocolVersion !== SWARM_PROTOCOL_VERSION) {
|
|
1986
|
+
throw new Error("Pi Agent Swarm local protocol version is invalid");
|
|
1987
|
+
}
|
|
1988
|
+
const endpointId = options.endpointId ?? randomEndpointId();
|
|
1989
|
+
this.peer = validatePeerDescription({ ...options.peer, endpointId });
|
|
1990
|
+
if (options.kickoffCapability !== void 0 && !SAFE_SESSION_ID.test(options.kickoffCapability) || Boolean(this.peer.launchId) !== Boolean(options.kickoffCapability)) {
|
|
1991
|
+
throw new Error("Pi Agent Swarm local kickoff capability is invalid");
|
|
1992
|
+
}
|
|
1993
|
+
this.now = options.now ?? Date.now;
|
|
1994
|
+
this.kickoffConsumed = options.kickoffConsumed === true;
|
|
1995
|
+
for (const id of options.seenMessageIds ?? []) {
|
|
1996
|
+
if (SAFE_SESSION_ID.test(id)) this.messageDedup.accept(id, this.now());
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
options;
|
|
2000
|
+
server;
|
|
2001
|
+
paths;
|
|
2002
|
+
startPromise;
|
|
2003
|
+
stopPromise;
|
|
2004
|
+
stopped = false;
|
|
2005
|
+
ownsEndpointFiles = false;
|
|
2006
|
+
lifecycle = new AbortController();
|
|
2007
|
+
sockets = /* @__PURE__ */ new Set();
|
|
2008
|
+
pendingTasks = /* @__PURE__ */ new Set();
|
|
2009
|
+
frameReplay = new ReplayWindow(FRAME_REPLAY_CAPACITY, FRAME_REPLAY_TTL_MS);
|
|
2010
|
+
responseReplay = new ReplayWindow(FRAME_REPLAY_CAPACITY, FRAME_REPLAY_TTL_MS);
|
|
2011
|
+
messageDedup = new ReplayWindow(MESSAGE_DEDUP_CAPACITY, MESSAGE_DEDUP_TTL_MS);
|
|
2012
|
+
senderRateLimiter = new FixedWindowRateLimiter(
|
|
2013
|
+
MAX_REQUESTS_PER_MINUTE,
|
|
2014
|
+
RATE_WINDOW_MS,
|
|
2015
|
+
MAX_DISCOVERY_MANIFESTS
|
|
2016
|
+
);
|
|
2017
|
+
totalRateLimiter = new FixedWindowRateLimiter(MAX_TOTAL_REQUESTS_PER_MINUTE, RATE_WINDOW_MS, 1);
|
|
2018
|
+
peer;
|
|
2019
|
+
kickoffConsumed = false;
|
|
2020
|
+
kickoffPending = false;
|
|
2021
|
+
inflightDeliveries = 0;
|
|
2022
|
+
pendingMessageIds = /* @__PURE__ */ new Set();
|
|
2023
|
+
now;
|
|
2024
|
+
setAcceptsRequests(value) {
|
|
2025
|
+
this.peer.acceptsRequests = value;
|
|
2026
|
+
}
|
|
2027
|
+
setColor(color) {
|
|
2028
|
+
this.peer.color = color;
|
|
2029
|
+
}
|
|
2030
|
+
setName(name) {
|
|
2031
|
+
this.peer.name = name;
|
|
2032
|
+
}
|
|
2033
|
+
get peerDescription() {
|
|
2034
|
+
return { ...this.peer };
|
|
2035
|
+
}
|
|
2036
|
+
get endpointManifest() {
|
|
2037
|
+
return this.paths ? { ...this.paths, peer: { ...this.peer } } : void 0;
|
|
2038
|
+
}
|
|
2039
|
+
async start(signal) {
|
|
2040
|
+
if (this.stopped) throw new Error("Pi Agent Swarm transport has already stopped");
|
|
2041
|
+
if (this.startPromise) return this.startPromise;
|
|
2042
|
+
throwIfAborted4(signal, "Pi Agent Swarm transport start aborted");
|
|
2043
|
+
const operationSignal = combineSignals(signal, this.lifecycle.signal);
|
|
2044
|
+
this.startPromise = this.startOwned(operationSignal).catch(async (error) => {
|
|
2045
|
+
await this.cleanup();
|
|
2046
|
+
this.startPromise = void 0;
|
|
2047
|
+
throw error;
|
|
2048
|
+
});
|
|
2049
|
+
return this.startPromise;
|
|
2050
|
+
}
|
|
2051
|
+
async discover(signal, deadlineMs = this.options.discoveryDeadlineMs ?? DEFAULT_DISCOVERY_DEADLINE_MS) {
|
|
2052
|
+
this.assertStarted();
|
|
2053
|
+
throwIfAborted4(signal, "Pi Agent Swarm peer discovery aborted");
|
|
2054
|
+
assertPositiveDuration2(deadlineMs, "Pi Agent Swarm discovery deadline");
|
|
2055
|
+
const deadline = deadlineSignal(deadlineMs, "Pi Agent Swarm peer discovery deadline exceeded");
|
|
2056
|
+
const operationSignal = combineSignals(signal, this.lifecycle.signal, deadline.signal);
|
|
2057
|
+
try {
|
|
2058
|
+
const manifestResult = await this.readManifests(operationSignal);
|
|
2059
|
+
const issues = [...manifestResult.issues];
|
|
2060
|
+
const discovered = [];
|
|
2061
|
+
let cursor = 0;
|
|
2062
|
+
const worker = async () => {
|
|
2063
|
+
while (cursor < manifestResult.records.length && !operationSignal.aborted) {
|
|
2064
|
+
const index = cursor;
|
|
2065
|
+
cursor += 1;
|
|
2066
|
+
const record = manifestResult.records[index];
|
|
2067
|
+
if (!record || record.manifest.endpointId === this.peer.endpointId) continue;
|
|
2068
|
+
try {
|
|
2069
|
+
const response = await this.request(
|
|
2070
|
+
record,
|
|
2071
|
+
{ kind: "describe" },
|
|
2072
|
+
operationSignal,
|
|
2073
|
+
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
|
|
2074
|
+
);
|
|
2075
|
+
if (response.payload.kind !== "description") {
|
|
2076
|
+
throw new Error("Pi Agent Swarm peer returned an invalid description response");
|
|
2077
|
+
}
|
|
2078
|
+
assertDescriptionMatchesManifest(response.payload.peer, record);
|
|
2079
|
+
if (response.payload.peer.sessionId === this.peer.sessionId) {
|
|
2080
|
+
addIssue(issues, {
|
|
2081
|
+
code: "identity_conflict",
|
|
2082
|
+
sessionId: this.peer.sessionId,
|
|
2083
|
+
endpointId: response.payload.peer.endpointId
|
|
2084
|
+
});
|
|
2085
|
+
continue;
|
|
2086
|
+
}
|
|
2087
|
+
discovered.push({ peer: response.payload.peer, record });
|
|
2088
|
+
} catch (error) {
|
|
2089
|
+
if (signal?.aborted || this.lifecycle.signal.aborted) throw error;
|
|
2090
|
+
if (deadline.signal.aborted) break;
|
|
2091
|
+
if (isDeadEndpointError(error)) {
|
|
2092
|
+
addIssue(issues, {
|
|
2093
|
+
code: "peer_unreachable",
|
|
2094
|
+
sessionId: record.manifest.sessionId,
|
|
2095
|
+
endpointId: record.manifest.endpointId
|
|
2096
|
+
});
|
|
2097
|
+
await this.removeStaleRecord(record);
|
|
2098
|
+
} else if (!isAbortError(error)) {
|
|
2099
|
+
addIssue(issues, {
|
|
2100
|
+
code: "protocol_error",
|
|
2101
|
+
sessionId: record.manifest.sessionId,
|
|
2102
|
+
endpointId: record.manifest.endpointId
|
|
2103
|
+
});
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
};
|
|
2108
|
+
await Promise.all(
|
|
2109
|
+
Array.from(
|
|
2110
|
+
{
|
|
2111
|
+
length: Math.min(MAX_DISCOVERY_CONCURRENCY, manifestResult.records.length)
|
|
2112
|
+
},
|
|
2113
|
+
() => worker()
|
|
2114
|
+
)
|
|
2115
|
+
);
|
|
2116
|
+
if (signal?.aborted || this.lifecycle.signal.aborted) {
|
|
2117
|
+
throw abortError3("Pi Agent Swarm peer discovery aborted");
|
|
2118
|
+
}
|
|
2119
|
+
if (deadline.signal.aborted) addIssue(issues, { code: "deadline_exceeded" });
|
|
2120
|
+
const peers = [];
|
|
2121
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
2122
|
+
for (const item of discovered) {
|
|
2123
|
+
const matches = bySession.get(item.peer.sessionId) ?? [];
|
|
2124
|
+
matches.push(item);
|
|
2125
|
+
bySession.set(item.peer.sessionId, matches);
|
|
2126
|
+
}
|
|
2127
|
+
for (const [sessionId, matches] of bySession) {
|
|
2128
|
+
if (matches.length === 1 && matches[0]) {
|
|
2129
|
+
peers.push(matches[0].peer);
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
addIssue(issues, { code: "identity_conflict", sessionId });
|
|
2133
|
+
}
|
|
2134
|
+
return {
|
|
2135
|
+
peers: peers.sort((left, right) => left.sessionId.localeCompare(right.sessionId)),
|
|
2136
|
+
issues,
|
|
2137
|
+
scannedEntries: manifestResult.scannedEntries,
|
|
2138
|
+
saturated: manifestResult.saturated
|
|
2139
|
+
};
|
|
2140
|
+
} finally {
|
|
2141
|
+
deadline.dispose();
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
async listPeers(signal, deadlineMs) {
|
|
2145
|
+
return (await this.discover(signal, deadlineMs)).peers;
|
|
2146
|
+
}
|
|
2147
|
+
async send(targetSessionId, value, signal, authorization) {
|
|
2148
|
+
this.assertStarted();
|
|
2149
|
+
throwIfAborted4(signal, "Pi Agent Swarm message send aborted");
|
|
2150
|
+
if (!SAFE_SESSION_ID.test(targetSessionId)) {
|
|
2151
|
+
throw new Error("Pi Agent Swarm target session id is invalid");
|
|
2152
|
+
}
|
|
2153
|
+
const message = validateMessage(value);
|
|
2154
|
+
validateMessageTiming(message, this.now());
|
|
2155
|
+
if (message.fromSessionId !== this.peer.sessionId) {
|
|
2156
|
+
throw new Error("Pi Agent Swarm message sender does not match the local session");
|
|
2157
|
+
}
|
|
2158
|
+
if (message.toSessionId !== targetSessionId) {
|
|
2159
|
+
throw new Error("Pi Agent Swarm message target does not match the selected session");
|
|
2160
|
+
}
|
|
2161
|
+
if (authorization && message.mode !== "kickoff") {
|
|
2162
|
+
throw new Error("Pi Agent Swarm kickoff authorization is invalid for this message mode");
|
|
2163
|
+
}
|
|
2164
|
+
if (authorization && !SAFE_SESSION_ID.test(authorization.kickoffCapability)) {
|
|
2165
|
+
throw new Error("Pi Agent Swarm kickoff authorization is invalid");
|
|
2166
|
+
}
|
|
2167
|
+
const manifestResult = await this.readManifests(signal);
|
|
2168
|
+
throwIfAborted4(signal, "Pi Agent Swarm message send aborted");
|
|
2169
|
+
const candidates = manifestResult.records.filter(({ manifest }) => manifest.sessionId === targetSessionId);
|
|
2170
|
+
if (candidates.length === 0) {
|
|
2171
|
+
throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
|
|
2172
|
+
}
|
|
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`);
|
|
2175
|
+
let response;
|
|
2176
|
+
try {
|
|
2177
|
+
response = await this.request(
|
|
2178
|
+
record,
|
|
2179
|
+
{
|
|
2180
|
+
kind: "message",
|
|
2181
|
+
message,
|
|
2182
|
+
...authorization ? { kickoffCapability: authorization.kickoffCapability } : {}
|
|
2183
|
+
},
|
|
2184
|
+
signal
|
|
2185
|
+
);
|
|
2186
|
+
} catch (error) {
|
|
2187
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
|
|
2188
|
+
throw error;
|
|
2189
|
+
}
|
|
2190
|
+
if (response.payload.kind !== "ack") {
|
|
2191
|
+
throw new Error("Pi Agent Swarm peer returned an invalid delivery acknowledgement");
|
|
2192
|
+
}
|
|
2193
|
+
return deliveryAck(response.payload);
|
|
2194
|
+
}
|
|
2195
|
+
async stop() {
|
|
2196
|
+
if (this.stopPromise) return this.stopPromise;
|
|
2197
|
+
this.stopped = true;
|
|
2198
|
+
this.lifecycle.abort();
|
|
2199
|
+
const start = this.startPromise;
|
|
2200
|
+
this.stopPromise = (async () => {
|
|
2201
|
+
await start?.catch(() => void 0);
|
|
2202
|
+
await this.cleanup();
|
|
2203
|
+
})();
|
|
2204
|
+
return this.stopPromise;
|
|
2205
|
+
}
|
|
2206
|
+
async startOwned(signal) {
|
|
2207
|
+
const directory = await ensureGroupRuntimeDirectory(this.options.group.id, {
|
|
2208
|
+
...this.options.baseDirectory ? { baseDirectory: this.options.baseDirectory } : {}
|
|
2209
|
+
});
|
|
2210
|
+
await cleanupStaleRuntimeEntries(directory, this.now());
|
|
2211
|
+
throwIfAborted4(signal, "Pi Agent Swarm transport start aborted");
|
|
2212
|
+
const paths = createEndpointPaths(directory, this.peer.endpointId);
|
|
2213
|
+
await assertEndpointPathsAvailable(paths);
|
|
2214
|
+
const server = createServer((socket) => this.acceptSocket(socket));
|
|
2215
|
+
this.server = server;
|
|
2216
|
+
this.paths = paths;
|
|
2217
|
+
await listenSocketServer(server, paths.socketPath, signal);
|
|
2218
|
+
this.ownsEndpointFiles = true;
|
|
2219
|
+
await chmod2(paths.socketPath, 384);
|
|
2220
|
+
throwIfAborted4(signal, "Pi Agent Swarm transport start aborted");
|
|
2221
|
+
await publishManifest(
|
|
2222
|
+
paths.manifestPath,
|
|
2223
|
+
createSignedEndpointManifest(
|
|
2224
|
+
{
|
|
2225
|
+
groupId: this.options.group.id,
|
|
2226
|
+
endpointId: this.peer.endpointId,
|
|
2227
|
+
sessionId: this.peer.sessionId,
|
|
2228
|
+
socketName: basename4(paths.socketPath),
|
|
2229
|
+
pid: this.peer.pid,
|
|
2230
|
+
publishedAt: this.now()
|
|
2231
|
+
},
|
|
2232
|
+
this.options.group.secret
|
|
2233
|
+
)
|
|
2234
|
+
);
|
|
2235
|
+
throwIfAborted4(signal, "Pi Agent Swarm transport start aborted");
|
|
2236
|
+
}
|
|
2237
|
+
acceptSocket(socket) {
|
|
2238
|
+
if (this.stopped || this.sockets.size >= MAX_PENDING_CONNECTIONS || this.pendingTasks.size >= MAX_PENDING_CONNECTIONS) {
|
|
2239
|
+
socket.destroy();
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
this.sockets.add(socket);
|
|
2243
|
+
const connection = new AbortController();
|
|
2244
|
+
const timer = setTimeout(() => {
|
|
2245
|
+
connection.abort();
|
|
2246
|
+
socket.destroy();
|
|
2247
|
+
}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
|
|
2248
|
+
timer.unref();
|
|
2249
|
+
let handled = false;
|
|
2250
|
+
const decoder = new JsonLineDecoder({
|
|
2251
|
+
onValue: (value) => {
|
|
2252
|
+
if (handled) {
|
|
2253
|
+
socket.destroy();
|
|
2254
|
+
return;
|
|
2255
|
+
}
|
|
2256
|
+
handled = true;
|
|
2257
|
+
const task = this.handleIncoming(socket, value, connection.signal);
|
|
2258
|
+
this.pendingTasks.add(task);
|
|
2259
|
+
void task.then(
|
|
2260
|
+
() => this.pendingTasks.delete(task),
|
|
2261
|
+
() => this.pendingTasks.delete(task)
|
|
2262
|
+
);
|
|
2263
|
+
},
|
|
2264
|
+
onError: () => socket.destroy()
|
|
2265
|
+
});
|
|
2266
|
+
socket.on("data", (chunk) => decoder.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
|
|
2267
|
+
socket.on("end", () => decoder.finish());
|
|
2268
|
+
socket.on("error", () => void 0);
|
|
2269
|
+
socket.on("close", () => {
|
|
2270
|
+
clearTimeout(timer);
|
|
2271
|
+
connection.abort();
|
|
2272
|
+
this.sockets.delete(socket);
|
|
2273
|
+
});
|
|
2274
|
+
}
|
|
2275
|
+
async handleIncoming(socket, value, signal) {
|
|
2276
|
+
try {
|
|
2277
|
+
const now = this.now();
|
|
2278
|
+
const frame = verifySignedFrame(value, this.options.group.secret, {
|
|
2279
|
+
expectedGroupId: this.options.group.id,
|
|
2280
|
+
expectedTargetSessionId: this.peer.sessionId,
|
|
2281
|
+
expectedTargetEndpointId: this.peer.endpointId,
|
|
2282
|
+
now,
|
|
2283
|
+
replay: this.frameReplay
|
|
2284
|
+
});
|
|
2285
|
+
const totalAccepted = this.totalRateLimiter.accept("all", now);
|
|
2286
|
+
const senderAccepted = this.senderRateLimiter.accept(frame.senderSessionId, now);
|
|
2287
|
+
if (!totalAccepted || !senderAccepted) {
|
|
2288
|
+
const retryAfterMs = Math.max(
|
|
2289
|
+
totalAccepted ? 0 : this.totalRateLimiter.retryAfterMs("all", now),
|
|
2290
|
+
senderAccepted ? 0 : this.senderRateLimiter.retryAfterMs(frame.senderSessionId, now)
|
|
2291
|
+
);
|
|
2292
|
+
await this.respond(socket, frame, {
|
|
2293
|
+
kind: "ack",
|
|
2294
|
+
status: "busy",
|
|
2295
|
+
code: "rate_limited",
|
|
2296
|
+
error: "Target session rate limit exceeded",
|
|
2297
|
+
retryAfterMs
|
|
2298
|
+
});
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
if (frame.payload.kind === "describe") {
|
|
2302
|
+
await this.respond(socket, frame, { kind: "description", peer: this.peer });
|
|
2303
|
+
return;
|
|
2304
|
+
}
|
|
2305
|
+
if (frame.payload.kind !== "message") throw new Error("Unsupported Pi Agent Swarm request payload");
|
|
2306
|
+
const message = frame.payload.message;
|
|
2307
|
+
validateMessageTiming(message, now);
|
|
2308
|
+
if (message.fromSessionId !== frame.senderSessionId || message.toSessionId !== this.peer.sessionId) {
|
|
2309
|
+
throw new Error("Pi Agent Swarm message identity does not match its authenticated frame");
|
|
2310
|
+
}
|
|
2311
|
+
if (this.messageDedup.has(message.id, now)) {
|
|
2312
|
+
await this.respond(socket, frame, { kind: "ack", status: "duplicate" });
|
|
2313
|
+
return;
|
|
2314
|
+
}
|
|
2315
|
+
const policyError = this.messagePolicyError(message, frame.payload.kickoffCapability);
|
|
2316
|
+
if (policyError) {
|
|
2317
|
+
await this.respond(socket, frame, policyError);
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
if (this.pendingMessageIds.has(message.id) || this.inflightDeliveries >= MAX_INFLIGHT_DELIVERIES) {
|
|
2321
|
+
await this.respond(socket, frame, {
|
|
2322
|
+
kind: "ack",
|
|
2323
|
+
status: "busy",
|
|
2324
|
+
code: "target_busy",
|
|
2325
|
+
error: this.pendingMessageIds.has(message.id) ? "Target session is still delivering this message" : "Target session has too many in-flight deliveries"
|
|
2326
|
+
});
|
|
2327
|
+
return;
|
|
2328
|
+
}
|
|
2329
|
+
this.pendingMessageIds.add(message.id);
|
|
2330
|
+
this.inflightDeliveries += 1;
|
|
2331
|
+
if (message.mode === "kickoff") this.kickoffPending = true;
|
|
2332
|
+
try {
|
|
2333
|
+
const deliverySignal = combineSignals(signal, this.lifecycle.signal);
|
|
2334
|
+
await raceWithSignal(
|
|
2335
|
+
Promise.resolve(this.options.onMessage(message, deliverySignal)),
|
|
2336
|
+
deliverySignal,
|
|
2337
|
+
"Pi Agent Swarm message delivery aborted"
|
|
2338
|
+
);
|
|
2339
|
+
this.messageDedup.record(message.id, this.now());
|
|
2340
|
+
if (message.mode === "kickoff") this.kickoffConsumed = true;
|
|
2341
|
+
} catch {
|
|
2342
|
+
if (signal.aborted || this.lifecycle.signal.aborted) throw abortError3("Delivery aborted");
|
|
2343
|
+
await this.respond(socket, frame, {
|
|
2344
|
+
kind: "ack",
|
|
2345
|
+
status: "rejected",
|
|
2346
|
+
code: "delivery_failed",
|
|
2347
|
+
error: "Target session rejected the message"
|
|
2348
|
+
});
|
|
2349
|
+
return;
|
|
2350
|
+
} finally {
|
|
2351
|
+
this.pendingMessageIds.delete(message.id);
|
|
2352
|
+
this.inflightDeliveries -= 1;
|
|
2353
|
+
if (message.mode === "kickoff") this.kickoffPending = false;
|
|
2354
|
+
}
|
|
2355
|
+
await this.respond(socket, frame, { kind: "ack", status: "accepted" });
|
|
2356
|
+
} catch {
|
|
2357
|
+
socket.destroy();
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
messagePolicyError(message, kickoffCapability) {
|
|
2361
|
+
if (message.kind === "shutdown" && !(this.options.authorizeShutdown?.(message) ?? false)) {
|
|
2362
|
+
return {
|
|
2363
|
+
kind: "ack",
|
|
2364
|
+
status: "rejected",
|
|
2365
|
+
code: "shutdown_unauthorized",
|
|
2366
|
+
error: "Sender is not authorized to shut down this session"
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
if (message.mode === "request" && !this.peer.acceptsRequests) {
|
|
2370
|
+
return {
|
|
2371
|
+
kind: "ack",
|
|
2372
|
+
status: "rejected",
|
|
2373
|
+
code: "requests_disabled",
|
|
2374
|
+
error: "Target session does not allow agent requests"
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
if (message.mode === "kickoff") {
|
|
2378
|
+
if (!this.peer.launchId || message.launchId !== this.peer.launchId || !secretEqual(kickoffCapability, this.options.kickoffCapability)) {
|
|
2379
|
+
return {
|
|
2380
|
+
kind: "ack",
|
|
2381
|
+
status: "rejected",
|
|
2382
|
+
code: "launch_mismatch",
|
|
2383
|
+
error: "Launch kickoff does not match the target session"
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
if (this.kickoffConsumed || this.kickoffPending) {
|
|
2387
|
+
return {
|
|
2388
|
+
kind: "ack",
|
|
2389
|
+
status: "rejected",
|
|
2390
|
+
code: "kickoff_consumed",
|
|
2391
|
+
error: "Launch kickoff has already been consumed"
|
|
2392
|
+
};
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
return void 0;
|
|
2396
|
+
}
|
|
2397
|
+
async respond(socket, request, payload) {
|
|
2398
|
+
const response = createSignedFrame(
|
|
2399
|
+
{
|
|
2400
|
+
groupId: this.options.group.id,
|
|
2401
|
+
requestId: request.requestId,
|
|
2402
|
+
targetSessionId: request.senderSessionId,
|
|
2403
|
+
targetEndpointId: request.senderEndpointId,
|
|
2404
|
+
senderSessionId: this.peer.sessionId,
|
|
2405
|
+
senderEndpointId: this.peer.endpointId,
|
|
2406
|
+
issuedAt: this.now(),
|
|
2407
|
+
nonce: randomId("nonce"),
|
|
2408
|
+
payload
|
|
2409
|
+
},
|
|
2410
|
+
this.options.group.secret
|
|
2411
|
+
);
|
|
2412
|
+
await writeFrame(socket, response);
|
|
2413
|
+
socket.end();
|
|
2414
|
+
}
|
|
2415
|
+
async readManifests(signal) {
|
|
2416
|
+
const paths = this.paths;
|
|
2417
|
+
if (!paths) throw new Error("Pi Agent Swarm transport is not started");
|
|
2418
|
+
throwIfAborted4(signal, "Pi Agent Swarm peer discovery aborted");
|
|
2419
|
+
const records = [];
|
|
2420
|
+
const issues = [];
|
|
2421
|
+
let scannedEntries = 0;
|
|
2422
|
+
let saturated = false;
|
|
2423
|
+
const directory = await opendir2(paths.directory);
|
|
2424
|
+
try {
|
|
2425
|
+
for await (const entry of directory) {
|
|
2426
|
+
throwIfAborted4(signal, "Pi Agent Swarm peer discovery aborted");
|
|
2427
|
+
if (scannedEntries >= MAX_RUNTIME_SCAN_ENTRIES) {
|
|
2428
|
+
saturated = true;
|
|
2429
|
+
addIssue(issues, { code: "scan_saturated" });
|
|
2430
|
+
break;
|
|
2431
|
+
}
|
|
2432
|
+
scannedEntries += 1;
|
|
2433
|
+
if (!entry.isFile()) continue;
|
|
2434
|
+
const endpointId = endpointIdFromManifestName(entry.name);
|
|
2435
|
+
if (!endpointId) {
|
|
2436
|
+
if (entry.name.endsWith(".json")) addIssue(issues, { code: "invalid_manifest" });
|
|
2437
|
+
continue;
|
|
2438
|
+
}
|
|
2439
|
+
if (records.length >= MAX_DISCOVERY_MANIFESTS) {
|
|
2440
|
+
saturated = true;
|
|
2441
|
+
addIssue(issues, { code: "scan_saturated" });
|
|
2442
|
+
continue;
|
|
2443
|
+
}
|
|
2444
|
+
try {
|
|
2445
|
+
records.push(
|
|
2446
|
+
await readManifest2(paths.directory, resolve4(paths.directory, entry.name), endpointId, this.options.group)
|
|
2447
|
+
);
|
|
2448
|
+
} catch {
|
|
2449
|
+
addIssue(issues, { code: "invalid_manifest", endpointId });
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
} finally {
|
|
2453
|
+
await directory.close().catch(() => void 0);
|
|
2454
|
+
}
|
|
2455
|
+
throwIfAborted4(signal, "Pi Agent Swarm peer discovery aborted");
|
|
2456
|
+
records.sort((left, right) => left.manifest.endpointId.localeCompare(right.manifest.endpointId));
|
|
2457
|
+
return { records, issues, scannedEntries, saturated };
|
|
2458
|
+
}
|
|
2459
|
+
async request(record, payload, signal, timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) {
|
|
2460
|
+
throwIfAborted4(signal, "Pi Agent Swarm request aborted");
|
|
2461
|
+
const requestId = randomId("req");
|
|
2462
|
+
const frame = createSignedFrame(
|
|
2463
|
+
{
|
|
2464
|
+
groupId: this.options.group.id,
|
|
2465
|
+
requestId,
|
|
2466
|
+
targetSessionId: record.manifest.sessionId,
|
|
2467
|
+
targetEndpointId: record.manifest.endpointId,
|
|
2468
|
+
senderSessionId: this.peer.sessionId,
|
|
2469
|
+
senderEndpointId: this.peer.endpointId,
|
|
2470
|
+
issuedAt: this.now(),
|
|
2471
|
+
nonce: randomId("nonce"),
|
|
2472
|
+
payload
|
|
2473
|
+
},
|
|
2474
|
+
this.options.group.secret
|
|
2475
|
+
);
|
|
2476
|
+
const value = await requestFrame(record.socketPath, frame, signal, timeoutMs);
|
|
2477
|
+
throwIfAborted4(signal, "Pi Agent Swarm request aborted");
|
|
2478
|
+
const response = verifySignedFrame(value, this.options.group.secret, {
|
|
2479
|
+
expectedGroupId: this.options.group.id,
|
|
2480
|
+
expectedTargetSessionId: this.peer.sessionId,
|
|
2481
|
+
expectedTargetEndpointId: this.peer.endpointId,
|
|
2482
|
+
now: this.now(),
|
|
2483
|
+
replay: this.responseReplay
|
|
2484
|
+
});
|
|
2485
|
+
if (response.requestId !== requestId || response.senderSessionId !== record.manifest.sessionId || response.senderEndpointId !== record.manifest.endpointId) {
|
|
2486
|
+
throw new Error("Pi Agent Swarm response identity does not match its request");
|
|
2487
|
+
}
|
|
2488
|
+
return response;
|
|
2489
|
+
}
|
|
2490
|
+
async resolveUniqueTarget(targetSessionId, candidates, signal) {
|
|
2491
|
+
const live = [];
|
|
2492
|
+
await Promise.all(
|
|
2493
|
+
candidates.map(async (record) => {
|
|
2494
|
+
try {
|
|
2495
|
+
const response = await this.request(
|
|
2496
|
+
record,
|
|
2497
|
+
{ kind: "describe" },
|
|
2498
|
+
signal,
|
|
2499
|
+
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS
|
|
2500
|
+
);
|
|
2501
|
+
if (response.payload.kind !== "description") return;
|
|
2502
|
+
assertDescriptionMatchesManifest(response.payload.peer, record);
|
|
2503
|
+
live.push(record);
|
|
2504
|
+
} catch (error) {
|
|
2505
|
+
if (isAbortError(error)) throw error;
|
|
2506
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
|
|
2507
|
+
}
|
|
2508
|
+
})
|
|
2509
|
+
);
|
|
2510
|
+
if (live.length > 1) {
|
|
2511
|
+
throw new Error(`Pi Agent Swarm session ${targetSessionId} has conflicting live endpoints`);
|
|
2512
|
+
}
|
|
2513
|
+
return live[0];
|
|
2514
|
+
}
|
|
2515
|
+
async removeStaleRecord(record) {
|
|
2516
|
+
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 });
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
} catch {
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
assertStarted() {
|
|
2530
|
+
if (!this.startPromise || !this.paths || this.stopped) {
|
|
2531
|
+
throw new Error("Pi Agent Swarm transport is not started");
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
async cleanup() {
|
|
2535
|
+
const server = this.server;
|
|
2536
|
+
this.server = void 0;
|
|
2537
|
+
for (const socket of this.sockets) socket.destroy();
|
|
2538
|
+
this.sockets.clear();
|
|
2539
|
+
if (server) await closeSocketServer(server);
|
|
2540
|
+
await Promise.allSettled([...this.pendingTasks]);
|
|
2541
|
+
this.pendingTasks.clear();
|
|
2542
|
+
this.pendingMessageIds.clear();
|
|
2543
|
+
this.kickoffPending = false;
|
|
2544
|
+
this.inflightDeliveries = 0;
|
|
2545
|
+
const paths = this.paths;
|
|
2546
|
+
if (paths && this.ownsEndpointFiles) await removeOwnedEndpoint(paths);
|
|
2547
|
+
this.ownsEndpointFiles = false;
|
|
2548
|
+
this.paths = void 0;
|
|
2549
|
+
}
|
|
2550
|
+
};
|
|
2551
|
+
async function assertEndpointPathsAvailable(paths) {
|
|
2552
|
+
for (const path2 of [paths.manifestPath, paths.socketPath]) {
|
|
2553
|
+
try {
|
|
2554
|
+
await lstat4(path2);
|
|
2555
|
+
throw new Error("Pi Agent Swarm endpoint identity is already in use");
|
|
2556
|
+
} catch (error) {
|
|
2557
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
2558
|
+
continue;
|
|
2559
|
+
}
|
|
2560
|
+
throw error;
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
async function readManifest2(directory, manifestPath, endpointId, group) {
|
|
2565
|
+
assertOwnedPath(directory, manifestPath, ".json");
|
|
2566
|
+
const handle = await open5(manifestPath, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
2567
|
+
try {
|
|
2568
|
+
const info = await handle.stat({ bigint: true });
|
|
2569
|
+
if (!info.isFile() || info.size > BigInt(MAX_MANIFEST_BYTES)) {
|
|
2570
|
+
throw new Error("Pi Agent Swarm endpoint manifest is invalid");
|
|
2571
|
+
}
|
|
2572
|
+
if (typeof process.getuid === "function" && Number(info.uid) !== process.getuid()) {
|
|
2573
|
+
throw new Error("Pi Agent Swarm endpoint manifest has another owner");
|
|
2574
|
+
}
|
|
2575
|
+
if ((Number(info.mode) & 511) !== 384) {
|
|
2576
|
+
throw new Error("Pi Agent Swarm endpoint manifest permissions are not private");
|
|
2577
|
+
}
|
|
2578
|
+
const raw = await readBoundedHandleUtf8(handle, MAX_MANIFEST_BYTES);
|
|
2579
|
+
const manifest = verifySignedEndpointManifest(JSON.parse(raw), group.secret, {
|
|
2580
|
+
expectedGroupId: group.id,
|
|
2581
|
+
expectedEndpointId: endpointId
|
|
2582
|
+
});
|
|
2583
|
+
const socketPath = join6(directory, manifest.socketName);
|
|
2584
|
+
if (dirname4(resolve4(socketPath)) !== resolve4(directory)) {
|
|
2585
|
+
throw new Error("Pi Agent Swarm endpoint socket path is invalid");
|
|
2586
|
+
}
|
|
2587
|
+
const socketInfo = await lstat4(socketPath, { bigint: true }).catch(() => void 0);
|
|
2588
|
+
if (socketInfo) {
|
|
2589
|
+
if (!socketInfo.isSocket()) throw new Error("Pi Agent Swarm endpoint path is not a Unix socket");
|
|
2590
|
+
if (typeof process.getuid === "function" && Number(socketInfo.uid) !== process.getuid()) {
|
|
2591
|
+
throw new Error("Pi Agent Swarm endpoint socket has another owner");
|
|
2592
|
+
}
|
|
2593
|
+
if ((Number(socketInfo.mode) & 511) !== 384) {
|
|
2594
|
+
throw new Error("Pi Agent Swarm endpoint socket permissions are not private");
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
return {
|
|
2598
|
+
manifest,
|
|
2599
|
+
manifestPath,
|
|
2600
|
+
socketPath,
|
|
2601
|
+
raw,
|
|
2602
|
+
...socketInfo ? { socketIdentity: { dev: socketInfo.dev, ino: socketInfo.ino } } : {}
|
|
2603
|
+
};
|
|
2604
|
+
} finally {
|
|
2605
|
+
await handle.close();
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
function assertDescriptionMatchesManifest(peer, record) {
|
|
2609
|
+
if (peer.sessionId !== record.manifest.sessionId || peer.endpointId !== record.manifest.endpointId || peer.pid !== record.manifest.pid) {
|
|
2610
|
+
throw new Error("Pi Agent Swarm peer identity does not match its endpoint manifest");
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
function deliveryAck(payload) {
|
|
2614
|
+
return {
|
|
2615
|
+
accepted: payload.status === "accepted" || payload.status === "duplicate",
|
|
2616
|
+
duplicate: payload.status === "duplicate",
|
|
2617
|
+
...payload.code ? { code: payload.code } : {},
|
|
2618
|
+
...payload.error ? { error: payload.error } : {},
|
|
2619
|
+
...payload.retryAfterMs !== void 0 ? { retryAfterMs: payload.retryAfterMs } : {}
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
function addIssue(issues, issue) {
|
|
2623
|
+
if (issues.length >= MAX_DISCOVERY_ISSUES) return;
|
|
2624
|
+
if (issues.some(
|
|
2625
|
+
(existing) => existing.code === issue.code && existing.sessionId === issue.sessionId && existing.endpointId === issue.endpointId
|
|
2626
|
+
)) {
|
|
2627
|
+
return;
|
|
2628
|
+
}
|
|
2629
|
+
issues.push(issue);
|
|
2630
|
+
}
|
|
2631
|
+
function randomId(prefix) {
|
|
2632
|
+
return `${prefix}_${randomBytes4(12).toString("hex")}`;
|
|
2633
|
+
}
|
|
2634
|
+
function combineSignals(...signals) {
|
|
2635
|
+
const concrete = signals.filter((signal) => signal !== void 0);
|
|
2636
|
+
return concrete.length === 0 ? new AbortController().signal : concrete.length === 1 ? concrete[0] : AbortSignal.any(concrete);
|
|
2637
|
+
}
|
|
2638
|
+
function deadlineSignal(milliseconds, message) {
|
|
2639
|
+
const controller = new AbortController();
|
|
2640
|
+
const timer = setTimeout(() => controller.abort(abortError3(message)), milliseconds);
|
|
2641
|
+
timer.unref();
|
|
2642
|
+
return { signal: controller.signal, dispose: () => clearTimeout(timer) };
|
|
2643
|
+
}
|
|
2644
|
+
function secretEqual(actual, expected) {
|
|
2645
|
+
if (!actual || !expected) return false;
|
|
2646
|
+
const actualBytes = Buffer.from(actual);
|
|
2647
|
+
const expectedBytes = Buffer.from(expected);
|
|
2648
|
+
return actualBytes.length === expectedBytes.length && timingSafeEqual2(actualBytes, expectedBytes);
|
|
2649
|
+
}
|
|
2650
|
+
function raceWithSignal(task, signal, message) {
|
|
2651
|
+
if (signal.aborted) return Promise.reject(abortError3(message));
|
|
2652
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
2653
|
+
let settled = false;
|
|
2654
|
+
const settle = (operation) => {
|
|
2655
|
+
if (settled) return;
|
|
2656
|
+
settled = true;
|
|
2657
|
+
signal.removeEventListener("abort", onAbort);
|
|
2658
|
+
operation();
|
|
2659
|
+
};
|
|
2660
|
+
const onAbort = () => settle(() => rejectPromise(abortError3(message)));
|
|
2661
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2662
|
+
void task.then(
|
|
2663
|
+
(value) => settle(() => resolvePromise(value)),
|
|
2664
|
+
(error) => settle(() => rejectPromise(error instanceof Error ? error : new Error(String(error))))
|
|
2665
|
+
);
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
function throwIfAborted4(signal, message) {
|
|
2669
|
+
if (signal?.aborted) throw abortError3(message);
|
|
2670
|
+
}
|
|
2671
|
+
function abortError3(message) {
|
|
2672
|
+
const error = new Error(message);
|
|
2673
|
+
error.name = "AbortError";
|
|
2674
|
+
return error;
|
|
2675
|
+
}
|
|
2676
|
+
function isAbortError(error) {
|
|
2677
|
+
return error instanceof Error && error.name === "AbortError";
|
|
2678
|
+
}
|
|
2679
|
+
function assertPositiveDuration2(value, label) {
|
|
2680
|
+
if (!Number.isFinite(value) || value < 1) throw new Error(`${label} is invalid`);
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
// src/swarm-controller.ts
|
|
2684
|
+
var STATUS_KEY = "swarm";
|
|
2685
|
+
var ROSTER_STATUS_KEY = "swarm-roster";
|
|
2686
|
+
var DEFAULT_LAUNCH_TIMEOUT_MS = 15e3;
|
|
2687
|
+
var DEFAULT_POLL_INTERVAL_MS2 = 100;
|
|
2688
|
+
var RELOAD_HANDOFF_TTL_MS = 3e4;
|
|
2689
|
+
function defaultSwarmControllerDependencies(pi) {
|
|
2690
|
+
return {
|
|
2691
|
+
createTransport: (options) => new SwarmTransport(options),
|
|
2692
|
+
createExternal: (command, pinToLeadWorkspace) => createDefaultTerminalPort(pi, command, pinToLeadWorkspace),
|
|
2693
|
+
resolveInvocation: (args) => resolvePiInvocation(args),
|
|
2694
|
+
createLauncher: (invocation, directory, embeddedEnvironment) => createPiLauncher(invocation, directory, embeddedEnvironment),
|
|
2695
|
+
realpath: realpath2,
|
|
2696
|
+
isDirectory: async (value) => (await stat2(value)).isDirectory(),
|
|
2697
|
+
now: Date.now,
|
|
2698
|
+
randomId: (prefix) => `${prefix}_${randomBytes5(16).toString("hex")}`,
|
|
2699
|
+
sleep: abortableSleep2,
|
|
2700
|
+
launchTimeoutMs: DEFAULT_LAUNCH_TIMEOUT_MS,
|
|
2701
|
+
environment: process.env,
|
|
2702
|
+
terminalColumns: () => process.stdout.isTTY ? process.stdout.columns : void 0
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
2705
|
+
var SwarmController = class {
|
|
2706
|
+
constructor(pi, deps = defaultSwarmControllerDependencies(pi), settings = createInMemorySwarmSettingsRuntime()) {
|
|
2707
|
+
this.pi = pi;
|
|
2708
|
+
this.deps = deps;
|
|
2709
|
+
this.settings = settings;
|
|
2710
|
+
}
|
|
2711
|
+
pi;
|
|
2712
|
+
deps;
|
|
2713
|
+
settings;
|
|
2714
|
+
generation = 0;
|
|
2715
|
+
activeSessionManager;
|
|
2716
|
+
activeContext;
|
|
2717
|
+
controller = new AbortController();
|
|
2718
|
+
membership;
|
|
2719
|
+
membershipMutation = Promise.resolve();
|
|
2720
|
+
ownedTasks = /* @__PURE__ */ new Set();
|
|
2721
|
+
color;
|
|
2722
|
+
parentSessionId;
|
|
2723
|
+
leadSessionId;
|
|
2724
|
+
/** A human-started session is the default lead of its own (not yet started) group. */
|
|
2725
|
+
defaultLead = false;
|
|
2726
|
+
leadWatcher;
|
|
2727
|
+
resizeListener = () => this.onTerminalResize();
|
|
2728
|
+
resizeWatching = false;
|
|
2729
|
+
pendingKickoffIds = /* @__PURE__ */ new Set();
|
|
2730
|
+
relayChain = Promise.resolve();
|
|
2731
|
+
async sessionStart(event, ctx) {
|
|
2732
|
+
if (this.activeSessionManager && this.activeSessionManager !== ctx.sessionManager) {
|
|
2733
|
+
await this.cleanupActive(false);
|
|
2734
|
+
}
|
|
2735
|
+
this.generation += 1;
|
|
2736
|
+
this.controller = new AbortController();
|
|
2737
|
+
this.activeSessionManager = ctx.sessionManager;
|
|
2738
|
+
this.activeContext = ctx;
|
|
2739
|
+
this.color = void 0;
|
|
2740
|
+
this.parentSessionId = void 0;
|
|
2741
|
+
this.leadSessionId = void 0;
|
|
2742
|
+
this.defaultLead = false;
|
|
2743
|
+
this.pendingKickoffIds.clear();
|
|
2744
|
+
this.relayChain = Promise.resolve();
|
|
2745
|
+
this.startLeadWatcher();
|
|
2746
|
+
this.startResizeWatcher();
|
|
2747
|
+
const owner = ctx.sessionManager;
|
|
2748
|
+
const ownerGeneration = this.generation;
|
|
2749
|
+
let envelope;
|
|
2750
|
+
try {
|
|
2751
|
+
envelope = consumeLaunchEnvelope(this.deps.environment);
|
|
2752
|
+
} catch (error) {
|
|
2753
|
+
this.notify(ctx, `Pi Agent Swarm ignored an invalid launch envelope: ${safeError(error)}`, "error");
|
|
2754
|
+
}
|
|
2755
|
+
try {
|
|
2756
|
+
const settings = await this.settings.reload(this.controller.signal);
|
|
2757
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
2758
|
+
if (settings.issue) this.notify(ctx, settings.issue.message, "warning");
|
|
2759
|
+
} catch (error) {
|
|
2760
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
2761
|
+
this.notify(ctx, `Pi Agent Swarm could not load settings: ${safeError(error)}`, "error");
|
|
2762
|
+
}
|
|
2763
|
+
const handoff = event.reason === "reload" ? takeReloadHandoff(owner, this.deps.now()) : void 0;
|
|
2764
|
+
this.parentSessionId = envelope?.parentSessionId ?? handoff?.parentSessionId;
|
|
2765
|
+
if (!envelope && !handoff) {
|
|
2766
|
+
if (!this.pi.getSessionName()) {
|
|
2767
|
+
this.pi.setSessionName(`MANAGER-${ctx.sessionManager.getSessionId().slice(0, 8)}`);
|
|
2768
|
+
}
|
|
2769
|
+
this.defaultLead = true;
|
|
2770
|
+
await this.renderFooterStatus(ctx);
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
try {
|
|
2774
|
+
if (envelope?.childName) this.pi.setSessionName(envelope.childName);
|
|
2775
|
+
if (envelope?.childColor) this.color = envelope.childColor;
|
|
2776
|
+
if (!envelope?.childColor && handoff?.color) this.color = handoff.color;
|
|
2777
|
+
if (handoff?.name && !this.pi.getSessionName()) this.pi.setSessionName(handoff.name);
|
|
2778
|
+
if (envelope?.model) {
|
|
2779
|
+
const model = ctx.modelRegistry.find(envelope.model.provider, envelope.model.id);
|
|
2780
|
+
if (!model) throw new Error("The requested parent model is unavailable in the child");
|
|
2781
|
+
if (!await this.pi.setModel(model)) {
|
|
2782
|
+
throw new Error("The requested parent model could not be activated in the child");
|
|
2783
|
+
}
|
|
2784
|
+
if (!this.isCurrent(owner, ownerGeneration)) return;
|
|
2785
|
+
if (envelope.model.thinkingLevel) {
|
|
2786
|
+
this.pi.setThinkingLevel(envelope.model.thinkingLevel);
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
const invite = envelope?.invite ?? handoff?.invite;
|
|
2790
|
+
if (!invite) return;
|
|
2791
|
+
await this.mutateMembership(
|
|
2792
|
+
() => this.startGroupOwned(
|
|
2793
|
+
parseInvite(invite),
|
|
2794
|
+
invite,
|
|
2795
|
+
envelope?.acceptsRequests ?? handoff?.acceptsRequests ?? false,
|
|
2796
|
+
ctx,
|
|
2797
|
+
this.controller.signal,
|
|
2798
|
+
envelope?.launchId ?? handoff?.launchId,
|
|
2799
|
+
envelope?.kickoffCapability ?? handoff?.kickoffCapability,
|
|
2800
|
+
handoff?.kickoffConsumed ?? false
|
|
2801
|
+
)
|
|
2802
|
+
);
|
|
2803
|
+
} catch (error) {
|
|
2804
|
+
if (this.isCurrent(owner, ownerGeneration)) {
|
|
2805
|
+
this.notify(ctx, `Pi Agent Swarm could not join the launch group: ${safeError(error)}`, "error");
|
|
2806
|
+
await this.leaveGroupInternal();
|
|
2807
|
+
if (envelope && this.isCurrent(owner, ownerGeneration)) {
|
|
2808
|
+
ctx.shutdown();
|
|
2809
|
+
this.pi.sendMessage(
|
|
2810
|
+
{ customType: SWARM_MESSAGE_TYPE, content: "", display: false, details: {} },
|
|
2811
|
+
{ deliverAs: "followUp", triggerTurn: true }
|
|
2812
|
+
);
|
|
2813
|
+
ctx.abort();
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2818
|
+
async sessionShutdown(event, ctx) {
|
|
2819
|
+
if (ctx.sessionManager !== this.activeSessionManager) return;
|
|
2820
|
+
this.stopLeadWatcher();
|
|
2821
|
+
this.stopResizeWatcher();
|
|
2822
|
+
if (event.reason === "reload" && this.membership) {
|
|
2823
|
+
const membership = this.membership;
|
|
2824
|
+
const peerName = this.pi.getSessionName() ?? membership.transport.peerDescription.name;
|
|
2825
|
+
const peerColor = this.color ?? membership.transport.peerDescription.color;
|
|
2826
|
+
putReloadHandoff(ctx.sessionManager, {
|
|
2827
|
+
invite: membership.invite,
|
|
2828
|
+
acceptsRequests: membership.acceptsRequests,
|
|
2829
|
+
...membership.launchId ? { launchId: membership.launchId } : {},
|
|
2830
|
+
...membership.kickoffCapability ? { kickoffCapability: membership.kickoffCapability } : {},
|
|
2831
|
+
kickoffConsumed: membership.kickoffConsumed,
|
|
2832
|
+
...peerName ? { name: peerName } : {},
|
|
2833
|
+
...peerColor ? { color: peerColor } : {},
|
|
2834
|
+
...this.parentSessionId ? { parentSessionId: this.parentSessionId } : {},
|
|
2835
|
+
expiresAt: this.deps.now() + RELOAD_HANDOFF_TTL_MS
|
|
2836
|
+
});
|
|
2837
|
+
}
|
|
2838
|
+
try {
|
|
2839
|
+
await this.cleanupActive(event.reason === "reload");
|
|
2840
|
+
} finally {
|
|
2841
|
+
this.clearStatus(ctx);
|
|
2842
|
+
this.clearRosterStatus(ctx);
|
|
2843
|
+
await this.settings.flush();
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
get sessionSignal() {
|
|
2847
|
+
return this.controller.signal;
|
|
2848
|
+
}
|
|
2849
|
+
async startNewGroup(ctx, acceptsRequests, signal) {
|
|
2850
|
+
this.assertCurrentContext(ctx);
|
|
2851
|
+
return this.mutateMembership(async () => {
|
|
2852
|
+
this.assertCurrentContext(ctx);
|
|
2853
|
+
if (this.membership) this.membership.rollbackLaunch = void 0;
|
|
2854
|
+
if (!this.membership) {
|
|
2855
|
+
const group = createGroup();
|
|
2856
|
+
await this.startGroupOwned(
|
|
2857
|
+
group,
|
|
2858
|
+
formatInvite(group.secret),
|
|
2859
|
+
acceptsRequests,
|
|
2860
|
+
ctx,
|
|
2861
|
+
combineSignals2(signal, this.controller.signal)
|
|
2862
|
+
);
|
|
2863
|
+
}
|
|
2864
|
+
const self = this.membership?.transport.peerDescription;
|
|
2865
|
+
if (self) {
|
|
2866
|
+
try {
|
|
2867
|
+
await this.setLead(ctx, self, combineSignals2(signal, this.controller.signal));
|
|
2868
|
+
} catch {
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
return this.snapshot(signal);
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
async joinInvite(ctx, invite, acceptsRequests, signal) {
|
|
2875
|
+
this.assertCurrentContext(ctx);
|
|
2876
|
+
const group = parseInvite(invite);
|
|
2877
|
+
return this.mutateMembership(async () => {
|
|
2878
|
+
this.assertCurrentContext(ctx);
|
|
2879
|
+
if (this.membership) {
|
|
2880
|
+
const membership = this.membership;
|
|
2881
|
+
this.membership = void 0;
|
|
2882
|
+
this.pendingKickoffIds.clear();
|
|
2883
|
+
try {
|
|
2884
|
+
await membership.transport.stop();
|
|
2885
|
+
} finally {
|
|
2886
|
+
membership.group.secret.fill(0);
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
await this.startGroupOwned(group, invite, acceptsRequests, ctx, combineSignals2(signal, this.controller.signal));
|
|
2890
|
+
return this.snapshot(signal);
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
async leave(ctx) {
|
|
2894
|
+
this.assertCurrentContext(ctx);
|
|
2895
|
+
await this.leaveGroupInternal();
|
|
2896
|
+
this.defaultLead = false;
|
|
2897
|
+
this.clearRosterStatus(ctx);
|
|
2898
|
+
}
|
|
2899
|
+
setAcceptsRequests(ctx, value) {
|
|
2900
|
+
this.assertCurrentContext(ctx);
|
|
2901
|
+
if (!this.membership) throw new Error("Pi Agent Swarm is not connected");
|
|
2902
|
+
this.membership.rollbackLaunch = void 0;
|
|
2903
|
+
this.membership.acceptsRequests = value;
|
|
2904
|
+
this.membership.transport.setAcceptsRequests(value);
|
|
2905
|
+
}
|
|
2906
|
+
async snapshot(signal) {
|
|
2907
|
+
if (!this.activeSessionManager || this.controller.signal.aborted) throw staleError();
|
|
2908
|
+
const membership = this.membership;
|
|
2909
|
+
if (!membership) return { connected: false, acceptsRequests: false, peers: [] };
|
|
2910
|
+
membership.rollbackLaunch = void 0;
|
|
2911
|
+
const owner = this.activeSessionManager;
|
|
2912
|
+
const ownerGeneration = this.generation;
|
|
2913
|
+
const operationSignal = combineSignals2(signal, this.controller.signal);
|
|
2914
|
+
const discovery = membership.transport.discover ? await membership.transport.discover(operationSignal) : {
|
|
2915
|
+
peers: await membership.transport.listPeers(operationSignal),
|
|
2916
|
+
issues: [],
|
|
2917
|
+
scannedEntries: 0,
|
|
2918
|
+
saturated: false
|
|
2919
|
+
};
|
|
2920
|
+
if (operationSignal.aborted || this.membership !== membership || !owner || !this.isCurrent(owner, ownerGeneration)) {
|
|
2921
|
+
throw staleError();
|
|
2922
|
+
}
|
|
2923
|
+
return {
|
|
2924
|
+
connected: true,
|
|
2925
|
+
groupId: membership.group.id,
|
|
2926
|
+
invite: membership.invite,
|
|
2927
|
+
acceptsRequests: membership.acceptsRequests,
|
|
2928
|
+
self: membership.transport.peerDescription,
|
|
2929
|
+
peers: discovery.peers,
|
|
2930
|
+
...discovery.issues.length > 0 ? { discoveryIssues: discovery.issues } : {},
|
|
2931
|
+
...discovery.saturated ? { discoverySaturated: true } : {}
|
|
2932
|
+
};
|
|
2933
|
+
}
|
|
2934
|
+
async send(ctx, options, signal) {
|
|
2935
|
+
this.assertCurrentContext(ctx);
|
|
2936
|
+
const membership = this.membership;
|
|
2937
|
+
if (!membership) throw new Error("Pi Agent Swarm is not connected");
|
|
2938
|
+
membership.rollbackLaunch = void 0;
|
|
2939
|
+
if (Buffer.byteLength(options.text) > MAX_MESSAGE_BYTES) {
|
|
2940
|
+
throw new Error("Pi Agent Swarm message is too large");
|
|
2941
|
+
}
|
|
2942
|
+
const self = membership.transport.peerDescription;
|
|
2943
|
+
const issuedAt = this.deps.now();
|
|
2944
|
+
const message = {
|
|
2945
|
+
id: this.deps.randomId("msg"),
|
|
2946
|
+
fromSessionId: self.sessionId,
|
|
2947
|
+
...self.name ? { fromName: self.name } : {},
|
|
2948
|
+
fromCwd: self.cwd,
|
|
2949
|
+
toSessionId: options.targetSessionId,
|
|
2950
|
+
mode: options.mode,
|
|
2951
|
+
text: options.text,
|
|
2952
|
+
issuedAt,
|
|
2953
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
|
|
2954
|
+
...options.replyTo ? { replyTo: options.replyTo } : {}
|
|
2955
|
+
};
|
|
2956
|
+
const owner = ctx.sessionManager;
|
|
2957
|
+
const ownerGeneration = this.generation;
|
|
2958
|
+
const operationSignal = combineSignals2(signal, this.controller.signal);
|
|
2959
|
+
const acknowledgement = await membership.transport.send(options.targetSessionId, message, operationSignal);
|
|
2960
|
+
if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
|
|
2961
|
+
throw staleError();
|
|
2962
|
+
}
|
|
2963
|
+
return { message, acknowledgement };
|
|
2964
|
+
}
|
|
2965
|
+
/** Send a control-plane shutdown request asking the target peer to exit gracefully. */
|
|
2966
|
+
async shutdownPeer(ctx, targetSessionId, signal) {
|
|
2967
|
+
this.assertCurrentContext(ctx);
|
|
2968
|
+
const membership = this.membership;
|
|
2969
|
+
if (!membership) throw new Error("Pi Agent Swarm is not connected");
|
|
2970
|
+
membership.rollbackLaunch = void 0;
|
|
2971
|
+
const self = membership.transport.peerDescription;
|
|
2972
|
+
const issuedAt = this.deps.now();
|
|
2973
|
+
const message = {
|
|
2974
|
+
id: this.deps.randomId("msg"),
|
|
2975
|
+
fromSessionId: self.sessionId,
|
|
2976
|
+
...self.name ? { fromName: self.name } : {},
|
|
2977
|
+
fromCwd: self.cwd,
|
|
2978
|
+
toSessionId: targetSessionId,
|
|
2979
|
+
mode: "notify",
|
|
2980
|
+
text: "shutdown request",
|
|
2981
|
+
kind: "shutdown",
|
|
2982
|
+
issuedAt,
|
|
2983
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS
|
|
2984
|
+
};
|
|
2985
|
+
const owner = ctx.sessionManager;
|
|
2986
|
+
const ownerGeneration = this.generation;
|
|
2987
|
+
const operationSignal = combineSignals2(signal, this.controller.signal);
|
|
2988
|
+
const acknowledgement = await membership.transport.send(targetSessionId, message, operationSignal);
|
|
2989
|
+
if (operationSignal.aborted || this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
|
|
2990
|
+
throw staleError();
|
|
2991
|
+
}
|
|
2992
|
+
return { message, acknowledgement };
|
|
2993
|
+
}
|
|
2994
|
+
spawn(ctx, input, signal) {
|
|
2995
|
+
return this.track(this.spawnOwned(ctx, input, signal));
|
|
2996
|
+
}
|
|
2997
|
+
async spawnOwned(ctx, input, signal) {
|
|
2998
|
+
this.assertCurrentContext(ctx);
|
|
2999
|
+
if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
|
|
3000
|
+
throw new Error("session_spawn is supported only in TUI or RPC mode");
|
|
3001
|
+
}
|
|
3002
|
+
const owner = ctx.sessionManager;
|
|
3003
|
+
const ownerGeneration = this.generation;
|
|
3004
|
+
const operationSignal = combineSignals2(signal, this.controller.signal);
|
|
3005
|
+
await this.settings.flush();
|
|
3006
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3007
|
+
const launchSettings = this.settings.get().settings;
|
|
3008
|
+
const direction = input.direction ?? "right";
|
|
3009
|
+
const windowLabel = "window";
|
|
3010
|
+
const launchLayoutLine = "External terminal window (the window manager places it)";
|
|
3011
|
+
const cwd = await this.resolveSpawnCwd(ctx, input.cwd);
|
|
3012
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3013
|
+
const task = normalizeOptionalText(input.task, "task", MAX_MESSAGE_BYTES);
|
|
3014
|
+
const launchId = this.deps.randomId("launch");
|
|
3015
|
+
const kickoffCapability = this.deps.randomId("kickoff");
|
|
3016
|
+
const name = normalizeOptionalText(input.name, "name", 200) ?? `Swarm ${launchId.slice(-6)}`;
|
|
3017
|
+
const palette = this.activePalette();
|
|
3018
|
+
const color = normalizeSwarmColor(input.color, palette) ?? pickSwarmColor(name, palette);
|
|
3019
|
+
const modelSpec = normalizeOptionalText(input.model, "model", 200);
|
|
3020
|
+
let childModel;
|
|
3021
|
+
if (modelSpec) {
|
|
3022
|
+
const slash = modelSpec.indexOf("/");
|
|
3023
|
+
if (slash <= 0 || slash === modelSpec.length - 1) {
|
|
3024
|
+
throw new Error("session_spawn model must be in provider/id form (e.g. deepseek/deepseek-v4-pro)");
|
|
3025
|
+
}
|
|
3026
|
+
const provider = modelSpec.slice(0, slash);
|
|
3027
|
+
const id = modelSpec.slice(slash + 1);
|
|
3028
|
+
if (!ctx.modelRegistry.find(provider, id)) {
|
|
3029
|
+
throw new Error(`session_spawn model "${modelSpec}" is unavailable`);
|
|
3030
|
+
}
|
|
3031
|
+
childModel = {
|
|
3032
|
+
provider,
|
|
3033
|
+
id,
|
|
3034
|
+
...ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}
|
|
3035
|
+
};
|
|
3036
|
+
} else {
|
|
3037
|
+
childModel = ctx.model ? {
|
|
3038
|
+
provider: ctx.model.provider,
|
|
3039
|
+
id: ctx.model.id,
|
|
3040
|
+
...ctx.thinkingLevel ? { thinkingLevel: ctx.thinkingLevel } : {}
|
|
3041
|
+
} : void 0;
|
|
3042
|
+
}
|
|
3043
|
+
const terminalAdapter = this.deps.createExternal(
|
|
3044
|
+
parseExternalCommand(launchSettings.externalCommand),
|
|
3045
|
+
launchSettings.pinToLeadWorkspace
|
|
3046
|
+
);
|
|
3047
|
+
const terminalVersion = await terminalAdapter.assertAvailable(operationSignal);
|
|
3048
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3049
|
+
if (launchSettings.confirmSessionLaunch) {
|
|
3050
|
+
const confirmed = await ctx.ui.confirm(
|
|
3051
|
+
"Create a new Pi session?",
|
|
3052
|
+
[
|
|
3053
|
+
`${launchLayoutLine}`,
|
|
3054
|
+
`Name: ${safeTerminalLine(name)}`,
|
|
3055
|
+
`Color: ${safeTerminalLine(color)}`,
|
|
3056
|
+
`Cwd: ${safeTerminalLine(cwd)}`,
|
|
3057
|
+
`Model: ${safeTerminalLine(childModel ? `${childModel.provider}/${childModel.id}` : "Pi default")}`,
|
|
3058
|
+
"The child may spend model tokens and edit the same workspace concurrently."
|
|
3059
|
+
].join("\n"),
|
|
3060
|
+
{ signal: operationSignal }
|
|
3061
|
+
);
|
|
3062
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3063
|
+
if (!confirmed) throw abortError4("Pi Agent Swarm launch cancelled before creating a split");
|
|
3064
|
+
}
|
|
3065
|
+
const rollbackOwner = {};
|
|
3066
|
+
let claimedMembership;
|
|
3067
|
+
let splitCreated = false;
|
|
3068
|
+
let terminalId;
|
|
3069
|
+
let actualTerminalVersion = terminalVersion;
|
|
3070
|
+
let launcher;
|
|
3071
|
+
const statusToken = this.beginStatus(ctx, `swarm: launching ${windowLabel}`);
|
|
3072
|
+
try {
|
|
3073
|
+
const membership = await this.claimSpawnMembership(ctx, operationSignal, rollbackOwner);
|
|
3074
|
+
claimedMembership = membership;
|
|
3075
|
+
const directory = membership.transport.endpointManifest?.directory;
|
|
3076
|
+
if (!directory) throw new Error("Pi Agent Swarm runtime directory is unavailable");
|
|
3077
|
+
const invocation = this.deps.resolveInvocation(["--name", name]);
|
|
3078
|
+
const envelope = {
|
|
3079
|
+
invite: membership.invite,
|
|
3080
|
+
parentSessionId: ctx.sessionManager.getSessionId(),
|
|
3081
|
+
launchId,
|
|
3082
|
+
kickoffCapability,
|
|
3083
|
+
childName: name,
|
|
3084
|
+
childColor: color,
|
|
3085
|
+
acceptsRequests: false,
|
|
3086
|
+
...childModel ? { model: childModel } : {}
|
|
3087
|
+
};
|
|
3088
|
+
const launchEnvironment = launchEnvelopeEnvironment(envelope);
|
|
3089
|
+
launcher = await this.deps.createLauncher(invocation, directory, launchEnvironment);
|
|
3090
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3091
|
+
const split = await terminalAdapter.spawnSplit({
|
|
3092
|
+
direction,
|
|
3093
|
+
cwd,
|
|
3094
|
+
launcherCommand: launcher.command,
|
|
3095
|
+
environment: {},
|
|
3096
|
+
signal: operationSignal,
|
|
3097
|
+
isCurrent: () => this.isCurrent(owner, ownerGeneration)
|
|
3098
|
+
});
|
|
3099
|
+
splitCreated = true;
|
|
3100
|
+
terminalId = split.terminalId;
|
|
3101
|
+
actualTerminalVersion = split.version;
|
|
3102
|
+
this.updateStatus(statusToken, "swarm: waiting for child session");
|
|
3103
|
+
const child = await this.waitForChild(launchId, operationSignal, owner, ownerGeneration);
|
|
3104
|
+
let kickoffAccepted = false;
|
|
3105
|
+
if (task) {
|
|
3106
|
+
const self = membership.transport.peerDescription;
|
|
3107
|
+
const issuedAt = this.deps.now();
|
|
3108
|
+
const kickoff = {
|
|
3109
|
+
id: this.deps.randomId("msg"),
|
|
3110
|
+
fromSessionId: self.sessionId,
|
|
3111
|
+
...self.name ? { fromName: self.name } : {},
|
|
3112
|
+
fromCwd: self.cwd,
|
|
3113
|
+
toSessionId: child.sessionId,
|
|
3114
|
+
mode: "kickoff",
|
|
3115
|
+
text: task,
|
|
3116
|
+
issuedAt,
|
|
3117
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS,
|
|
3118
|
+
launchId
|
|
3119
|
+
};
|
|
3120
|
+
this.pendingKickoffIds.add(kickoff.id);
|
|
3121
|
+
try {
|
|
3122
|
+
const acknowledgement = await membership.transport.send(child.sessionId, kickoff, operationSignal, {
|
|
3123
|
+
kickoffCapability
|
|
3124
|
+
});
|
|
3125
|
+
if (this.membership !== membership || !this.isCurrent(owner, ownerGeneration) || operationSignal.aborted) {
|
|
3126
|
+
throw staleError();
|
|
3127
|
+
}
|
|
3128
|
+
if (!acknowledgement.accepted) {
|
|
3129
|
+
throw createTerminalLaunchError(
|
|
3130
|
+
`The external window started, but the child rejected its first task: ${safeTerminalLine(acknowledgement.error ?? "unknown reason")}`,
|
|
3131
|
+
true,
|
|
3132
|
+
terminalId
|
|
3133
|
+
);
|
|
3134
|
+
}
|
|
3135
|
+
kickoffAccepted = true;
|
|
3136
|
+
} catch (error) {
|
|
3137
|
+
this.pendingKickoffIds.delete(kickoff.id);
|
|
3138
|
+
throw error;
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
void this.primeFooter(ctx);
|
|
3142
|
+
return {
|
|
3143
|
+
sessionId: child.sessionId,
|
|
3144
|
+
...child.name ? { name: child.name } : {},
|
|
3145
|
+
color,
|
|
3146
|
+
cwd: child.cwd,
|
|
3147
|
+
terminalId,
|
|
3148
|
+
terminalVersion: actualTerminalVersion,
|
|
3149
|
+
kickoffAccepted
|
|
3150
|
+
};
|
|
3151
|
+
} catch (error) {
|
|
3152
|
+
const partial = splitCreated || isTerminalLaunchError(error) && error.splitCreated;
|
|
3153
|
+
if (!partial && claimedMembership?.rollbackLaunch === rollbackOwner && this.membership === claimedMembership) {
|
|
3154
|
+
await this.leaveGroupInternal();
|
|
3155
|
+
}
|
|
3156
|
+
if (partial && !isTerminalLaunchError(error)) {
|
|
3157
|
+
throw createTerminalLaunchError(
|
|
3158
|
+
`The external window started, but the child session did not become ready: ${safeError(error)}`,
|
|
3159
|
+
true,
|
|
3160
|
+
terminalId
|
|
3161
|
+
);
|
|
3162
|
+
}
|
|
3163
|
+
throw error;
|
|
3164
|
+
} finally {
|
|
3165
|
+
if (claimedMembership?.rollbackLaunch === rollbackOwner) {
|
|
3166
|
+
claimedMembership.rollbackLaunch = void 0;
|
|
3167
|
+
}
|
|
3168
|
+
try {
|
|
3169
|
+
await launcher?.cleanup();
|
|
3170
|
+
} catch (error) {
|
|
3171
|
+
if (this.isCurrent(owner, ownerGeneration)) {
|
|
3172
|
+
this.notify(ctx, `Pi Agent Swarm could not remove its temporary launcher: ${safeError(error)}`, "warning");
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
this.endStatus(statusToken);
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
isCurrent(owner, generation) {
|
|
3179
|
+
const sessionManager = "sessionManager" in owner ? owner.sessionManager : owner;
|
|
3180
|
+
return this.activeSessionManager === sessionManager && (generation === void 0 || this.generation === generation) && !this.controller.signal.aborted;
|
|
3181
|
+
}
|
|
3182
|
+
claimSpawnMembership(ctx, signal, rollbackOwner) {
|
|
3183
|
+
return this.mutateMembership(async () => {
|
|
3184
|
+
this.assertCurrentContext(ctx);
|
|
3185
|
+
if (this.membership) {
|
|
3186
|
+
this.membership.rollbackLaunch = void 0;
|
|
3187
|
+
return this.membership;
|
|
3188
|
+
}
|
|
3189
|
+
const group = createGroup();
|
|
3190
|
+
const membership = await this.startGroupOwned(group, formatInvite(group.secret), false, ctx, signal);
|
|
3191
|
+
membership.rollbackLaunch = rollbackOwner;
|
|
3192
|
+
try {
|
|
3193
|
+
await this.setLead(ctx, membership.transport.peerDescription, signal);
|
|
3194
|
+
} catch {
|
|
3195
|
+
}
|
|
3196
|
+
return membership;
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
3199
|
+
async startGroupOwned(group, invite, acceptsRequests, ctx, signal, launchId, kickoffCapability, kickoffConsumed = false) {
|
|
3200
|
+
this.assertCurrentContext(ctx);
|
|
3201
|
+
if (this.membership) {
|
|
3202
|
+
if (this.membership.group.id === group.id) return this.membership;
|
|
3203
|
+
throw new Error("Pi Agent Swarm is already connected to another group");
|
|
3204
|
+
}
|
|
3205
|
+
const owner = ctx.sessionManager;
|
|
3206
|
+
const ownerGeneration = this.generation;
|
|
3207
|
+
const peer = {
|
|
3208
|
+
protocolVersion: SWARM_PROTOCOL_VERSION,
|
|
3209
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
3210
|
+
...this.pi.getSessionName() ? { name: this.pi.getSessionName() } : {},
|
|
3211
|
+
color: this.color ?? pickSwarmColor(ctx.sessionManager.getSessionId(), this.activePalette()),
|
|
3212
|
+
cwd: ctx.cwd,
|
|
3213
|
+
pid: process.pid,
|
|
3214
|
+
...launchId ? { launchId } : {},
|
|
3215
|
+
acceptsRequests
|
|
3216
|
+
};
|
|
3217
|
+
const recent = recentSwarmState(ctx);
|
|
3218
|
+
let transport;
|
|
3219
|
+
let acceptedKickoff = kickoffConsumed || (launchId ? recent.consumedLaunchIds.has(launchId) : false);
|
|
3220
|
+
transport = this.deps.createTransport({
|
|
3221
|
+
group,
|
|
3222
|
+
peer,
|
|
3223
|
+
...this.deps.runtimeBaseDirectory ? { baseDirectory: this.deps.runtimeBaseDirectory } : {},
|
|
3224
|
+
seenMessageIds: recent.messageIds,
|
|
3225
|
+
...kickoffCapability ? { kickoffCapability } : {},
|
|
3226
|
+
kickoffConsumed: acceptedKickoff,
|
|
3227
|
+
authorizeShutdown: (message) => message.fromSessionId === this.parentSessionId || this.leadSessionId !== void 0 && message.fromSessionId === this.leadSessionId,
|
|
3228
|
+
onMessage: async (message, deliverySignal) => {
|
|
3229
|
+
if (deliverySignal?.aborted || !this.isCurrent(owner, ownerGeneration)) return;
|
|
3230
|
+
const activeContext = this.activeContext;
|
|
3231
|
+
if (message.kind === "shutdown") {
|
|
3232
|
+
const idle = activeContext?.isIdle() ?? false;
|
|
3233
|
+
activeContext?.shutdown();
|
|
3234
|
+
if (idle && activeContext) {
|
|
3235
|
+
const details = { message };
|
|
3236
|
+
this.pi.sendMessage(
|
|
3237
|
+
{ customType: SWARM_MESSAGE_TYPE, content: "", display: false, details },
|
|
3238
|
+
{ deliverAs: "followUp", triggerTurn: true }
|
|
3239
|
+
);
|
|
3240
|
+
activeContext.abort();
|
|
3241
|
+
}
|
|
3242
|
+
return;
|
|
3243
|
+
}
|
|
3244
|
+
if (message.kind === "lead") {
|
|
3245
|
+
} else {
|
|
3246
|
+
this.receiveMessage(message);
|
|
3247
|
+
}
|
|
3248
|
+
void this.refreshLead().then((changed) => {
|
|
3249
|
+
if (changed && activeContext && this.isCurrent(owner, ownerGeneration)) {
|
|
3250
|
+
void this.renderFooterStatus(activeContext);
|
|
3251
|
+
}
|
|
3252
|
+
});
|
|
3253
|
+
if (message.mode === "kickoff") {
|
|
3254
|
+
acceptedKickoff = true;
|
|
3255
|
+
if (this.membership?.transport === transport) {
|
|
3256
|
+
this.membership.kickoffConsumed = true;
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
},
|
|
3260
|
+
now: this.deps.now
|
|
3261
|
+
});
|
|
3262
|
+
const token = this.beginStatus(ctx, "swarm: joining local group");
|
|
3263
|
+
try {
|
|
3264
|
+
await this.track(transport.start(signal));
|
|
3265
|
+
if (!this.isCurrent(owner, ownerGeneration) || signal.aborted) {
|
|
3266
|
+
await transport.stop();
|
|
3267
|
+
throw staleError();
|
|
3268
|
+
}
|
|
3269
|
+
const membership = {
|
|
3270
|
+
group,
|
|
3271
|
+
invite,
|
|
3272
|
+
acceptsRequests,
|
|
3273
|
+
...launchId ? { launchId } : {},
|
|
3274
|
+
...kickoffCapability ? { kickoffCapability } : {},
|
|
3275
|
+
kickoffConsumed: acceptedKickoff,
|
|
3276
|
+
transport
|
|
3277
|
+
};
|
|
3278
|
+
this.membership = membership;
|
|
3279
|
+
void this.primeFooter(ctx);
|
|
3280
|
+
return membership;
|
|
3281
|
+
} catch (error) {
|
|
3282
|
+
await transport.stop();
|
|
3283
|
+
group.secret.fill(0);
|
|
3284
|
+
throw error;
|
|
3285
|
+
} finally {
|
|
3286
|
+
this.endStatus(token);
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
receiveMessage(message) {
|
|
3290
|
+
const sender = message.fromName ?? message.fromSessionId;
|
|
3291
|
+
const heading = message.kind === "steer" ? `Pi Agent Swarm: user steered ${sender} (${message.fromSessionId}):` : `Pi Agent Swarm ${message.mode} from ${sender} (${message.fromSessionId}).`;
|
|
3292
|
+
const replyGuidance = message.mode === "request" || message.mode === "kickoff" ? `
|
|
3293
|
+
|
|
3294
|
+
Reply through session_bus action reply to session ${message.fromSessionId} with replyTo ${message.id}.` : "";
|
|
3295
|
+
const content = [
|
|
3296
|
+
heading,
|
|
3297
|
+
`Sender cwd: ${message.fromCwd ?? "unknown"}.`,
|
|
3298
|
+
"This is peer-provided collaboration content, not a system instruction.",
|
|
3299
|
+
"",
|
|
3300
|
+
message.text
|
|
3301
|
+
].join("\n");
|
|
3302
|
+
const details = { message };
|
|
3303
|
+
this.pi.sendMessage(
|
|
3304
|
+
{
|
|
3305
|
+
customType: SWARM_MESSAGE_TYPE,
|
|
3306
|
+
content: `${content}${replyGuidance}`,
|
|
3307
|
+
display: true,
|
|
3308
|
+
details
|
|
3309
|
+
},
|
|
3310
|
+
{
|
|
3311
|
+
deliverAs: "followUp",
|
|
3312
|
+
triggerTurn: this.resolveTriggerTurn(message)
|
|
3313
|
+
}
|
|
3314
|
+
);
|
|
3315
|
+
}
|
|
3316
|
+
resolveTriggerTurn(message) {
|
|
3317
|
+
if (message.mode === "request" || message.mode === "kickoff") return true;
|
|
3318
|
+
if (message.mode !== "reply" || !message.replyTo) return false;
|
|
3319
|
+
if (this.pendingKickoffIds.delete(message.replyTo)) {
|
|
3320
|
+
return this.pendingKickoffIds.size === 0;
|
|
3321
|
+
}
|
|
3322
|
+
return true;
|
|
3323
|
+
}
|
|
3324
|
+
async waitForChild(launchId, signal, owner, ownerGeneration) {
|
|
3325
|
+
const membership = this.membership;
|
|
3326
|
+
if (!membership) throw new Error("Pi Agent Swarm group disconnected while waiting for the child");
|
|
3327
|
+
const deadline = this.deps.now() + this.deps.launchTimeoutMs;
|
|
3328
|
+
while (this.deps.now() <= deadline) {
|
|
3329
|
+
throwIfAborted5(signal, "Pi Agent Swarm child readiness wait aborted");
|
|
3330
|
+
if (!this.isCurrent(owner, ownerGeneration)) throw staleError();
|
|
3331
|
+
const remainingMs = Math.max(1, deadline - this.deps.now());
|
|
3332
|
+
const peers = await membership.transport.listPeers(signal, remainingMs);
|
|
3333
|
+
if (this.membership !== membership || !this.isCurrent(owner, ownerGeneration)) {
|
|
3334
|
+
throw staleError();
|
|
3335
|
+
}
|
|
3336
|
+
const child = peers.find((peer) => peer.launchId === launchId);
|
|
3337
|
+
if (child) return child;
|
|
3338
|
+
await this.deps.sleep(DEFAULT_POLL_INTERVAL_MS2, signal);
|
|
3339
|
+
}
|
|
3340
|
+
throw new Error(`Pi Agent Swarm child readiness timed out after ${this.deps.launchTimeoutMs}ms`);
|
|
3341
|
+
}
|
|
3342
|
+
async resolveSpawnCwd(ctx, value) {
|
|
3343
|
+
const requested = value?.trim() ? resolve5(ctx.cwd, value) : ctx.cwd;
|
|
3344
|
+
const canonical = await this.deps.realpath(requested);
|
|
3345
|
+
if (canonical.includes("\0") || Buffer.byteLength(canonical) > 4096) {
|
|
3346
|
+
throw new Error("Pi Agent Swarm child cwd is invalid or too large");
|
|
3347
|
+
}
|
|
3348
|
+
if (!await this.deps.isDirectory(canonical)) {
|
|
3349
|
+
throw new Error("Pi Agent Swarm child cwd must be an existing directory");
|
|
3350
|
+
}
|
|
3351
|
+
return canonical;
|
|
3352
|
+
}
|
|
3353
|
+
assertCurrentContext(ctx) {
|
|
3354
|
+
if (!this.isCurrent(ctx)) throw staleError();
|
|
3355
|
+
}
|
|
3356
|
+
async cleanupActive(reloading) {
|
|
3357
|
+
this.generation += 1;
|
|
3358
|
+
this.controller.abort();
|
|
3359
|
+
let cleanupError;
|
|
3360
|
+
try {
|
|
3361
|
+
await this.leaveGroupInternal(reloading);
|
|
3362
|
+
} catch (error) {
|
|
3363
|
+
cleanupError = error;
|
|
3364
|
+
}
|
|
3365
|
+
while (this.ownedTasks.size > 0) await Promise.allSettled([...this.ownedTasks]);
|
|
3366
|
+
if (this.activeContext) this.clearStatus(this.activeContext);
|
|
3367
|
+
this.activeContext = void 0;
|
|
3368
|
+
this.activeSessionManager = void 0;
|
|
3369
|
+
if (cleanupError) throw cleanupError;
|
|
3370
|
+
}
|
|
3371
|
+
leaveGroupInternal(reloading = false) {
|
|
3372
|
+
return this.mutateMembership(async () => {
|
|
3373
|
+
const membership = this.membership;
|
|
3374
|
+
const directory = membership?.transport.endpointManifest?.directory;
|
|
3375
|
+
const self = membership?.transport.peerDescription;
|
|
3376
|
+
this.membership = void 0;
|
|
3377
|
+
this.pendingKickoffIds.clear();
|
|
3378
|
+
try {
|
|
3379
|
+
await membership?.transport.stop();
|
|
3380
|
+
} finally {
|
|
3381
|
+
membership?.group.secret.fill(0);
|
|
3382
|
+
}
|
|
3383
|
+
if (!reloading && directory && self && this.leadSessionId === self.sessionId) {
|
|
3384
|
+
await rm5(join7(directory, "lead.json"), { force: true }).catch(() => void 0);
|
|
3385
|
+
}
|
|
3386
|
+
this.leadSessionId = void 0;
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
mutateMembership(operation) {
|
|
3390
|
+
const result = this.membershipMutation.then(operation, operation);
|
|
3391
|
+
this.membershipMutation = result.then(
|
|
3392
|
+
() => void 0,
|
|
3393
|
+
() => void 0
|
|
3394
|
+
);
|
|
3395
|
+
return result;
|
|
3396
|
+
}
|
|
3397
|
+
track(task) {
|
|
3398
|
+
this.ownedTasks.add(task);
|
|
3399
|
+
void task.then(
|
|
3400
|
+
() => this.ownedTasks.delete(task),
|
|
3401
|
+
() => this.ownedTasks.delete(task)
|
|
3402
|
+
);
|
|
3403
|
+
return task;
|
|
3404
|
+
}
|
|
3405
|
+
beginStatus(ctx, text) {
|
|
3406
|
+
const token = { ctx, text };
|
|
3407
|
+
try {
|
|
3408
|
+
ctx.ui.setStatus(STATUS_KEY, text);
|
|
3409
|
+
} catch {
|
|
3410
|
+
}
|
|
3411
|
+
return token;
|
|
3412
|
+
}
|
|
3413
|
+
updateStatus(token, text) {
|
|
3414
|
+
token.text = text;
|
|
3415
|
+
try {
|
|
3416
|
+
token.ctx.ui.setStatus(STATUS_KEY, text);
|
|
3417
|
+
} catch {
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
endStatus(token) {
|
|
3421
|
+
try {
|
|
3422
|
+
token.ctx.ui.setStatus(STATUS_KEY, void 0);
|
|
3423
|
+
} catch {
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
clearStatus(ctx) {
|
|
3427
|
+
try {
|
|
3428
|
+
ctx.ui.setStatus(STATUS_KEY, void 0);
|
|
3429
|
+
} catch {
|
|
3430
|
+
}
|
|
3431
|
+
}
|
|
3432
|
+
clearRosterStatus(ctx) {
|
|
3433
|
+
try {
|
|
3434
|
+
ctx.ui.setStatus(ROSTER_STATUS_KEY, void 0);
|
|
3435
|
+
} catch {
|
|
3436
|
+
}
|
|
3437
|
+
}
|
|
3438
|
+
leadPath() {
|
|
3439
|
+
const directory = this.membership?.transport.endpointManifest?.directory;
|
|
3440
|
+
return directory ? join7(directory, "lead.json") : void 0;
|
|
3441
|
+
}
|
|
3442
|
+
async refreshLead() {
|
|
3443
|
+
const path2 = this.leadPath();
|
|
3444
|
+
if (!path2) {
|
|
3445
|
+
const changed = this.leadSessionId !== void 0;
|
|
3446
|
+
this.leadSessionId = void 0;
|
|
3447
|
+
return changed;
|
|
3448
|
+
}
|
|
3449
|
+
try {
|
|
3450
|
+
const raw = JSON.parse(await readFile(path2, "utf8"));
|
|
3451
|
+
const next = typeof raw.sessionId === "string" ? raw.sessionId : void 0;
|
|
3452
|
+
const changed = next !== this.leadSessionId;
|
|
3453
|
+
this.leadSessionId = next;
|
|
3454
|
+
return changed;
|
|
3455
|
+
} catch {
|
|
3456
|
+
const changed = this.leadSessionId !== void 0;
|
|
3457
|
+
this.leadSessionId = void 0;
|
|
3458
|
+
return changed;
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
async primeFooter(ctx) {
|
|
3462
|
+
await this.refreshLead();
|
|
3463
|
+
await this.renderFooterStatus(ctx);
|
|
3464
|
+
}
|
|
3465
|
+
async renderFooterStatus(ctx) {
|
|
3466
|
+
const self = this.membership?.transport.peerDescription;
|
|
3467
|
+
if (!self && !this.defaultLead) {
|
|
3468
|
+
this.clearRosterStatus(ctx);
|
|
3469
|
+
return;
|
|
3470
|
+
}
|
|
3471
|
+
const sessionId = self?.sessionId ?? ctx.sessionManager.getSessionId();
|
|
3472
|
+
const name = self?.name ?? this.pi.getSessionName();
|
|
3473
|
+
const color = this.color ?? self?.color ?? pickSwarmColor(sessionId, this.activePalette());
|
|
3474
|
+
const role = this.leadSessionId === sessionId || !self && this.defaultLead ? "LEADER" : "WORKER";
|
|
3475
|
+
const columns = this.deps.terminalColumns?.() ?? DEFAULT_TERMINAL_COLUMNS;
|
|
3476
|
+
const status = buildRosterBadge({ name, sessionId, color, role, columns });
|
|
3477
|
+
try {
|
|
3478
|
+
ctx.ui.setStatus(ROSTER_STATUS_KEY, status);
|
|
3479
|
+
} catch {
|
|
3480
|
+
}
|
|
3481
|
+
}
|
|
3482
|
+
/** Resolve a peer by name or session id from the current snapshot. */
|
|
3483
|
+
async resolvePeer(target, signal) {
|
|
3484
|
+
const snapshot = await this.snapshot(signal);
|
|
3485
|
+
const candidates = snapshot.self ? [snapshot.self, ...snapshot.peers] : snapshot.peers;
|
|
3486
|
+
const byId = candidates.find((p) => p.sessionId === target);
|
|
3487
|
+
if (byId) return byId;
|
|
3488
|
+
return candidates.find((p) => p.name === target);
|
|
3489
|
+
}
|
|
3490
|
+
async setLead(ctx, target, signal) {
|
|
3491
|
+
this.assertCurrentContext(ctx);
|
|
3492
|
+
throwIfAborted5(signal, "Pi Agent Swarm lead change aborted");
|
|
3493
|
+
const path2 = this.leadPath();
|
|
3494
|
+
if (!path2) throw new Error("Pi Agent Swarm runtime directory is unavailable");
|
|
3495
|
+
const record = {
|
|
3496
|
+
sessionId: target.sessionId,
|
|
3497
|
+
...target.name ? { name: target.name } : {},
|
|
3498
|
+
at: this.deps.now()
|
|
3499
|
+
};
|
|
3500
|
+
const temporary = `${path2}.tmp-${process.pid}`;
|
|
3501
|
+
try {
|
|
3502
|
+
await writeFile2(temporary, `${JSON.stringify(record)}
|
|
3503
|
+
`, { encoding: "utf8", flag: "wx" });
|
|
3504
|
+
await rename3(temporary, path2);
|
|
3505
|
+
} finally {
|
|
3506
|
+
await rm5(temporary, { force: true }).catch(() => void 0);
|
|
3507
|
+
}
|
|
3508
|
+
this.leadSessionId = target.sessionId;
|
|
3509
|
+
await this.broadcastLeadChange(target);
|
|
3510
|
+
await this.renderFooterStatus(ctx);
|
|
3511
|
+
}
|
|
3512
|
+
/** Resolve a palette name or #rrggbb hex against the active `colorPalette` setting. */
|
|
3513
|
+
normalizeColor(value) {
|
|
3514
|
+
return normalizeSwarmColor(value, this.activePalette());
|
|
3515
|
+
}
|
|
3516
|
+
activePalette() {
|
|
3517
|
+
return swarmColorPalette(this.settings.get().settings.colorPalette);
|
|
3518
|
+
}
|
|
3519
|
+
/**
|
|
3520
|
+
* Persist the roster palette and keep this session on the same hue slot under
|
|
3521
|
+
* the new palette. Peers keep their announced colors; their own sessions decide
|
|
3522
|
+
* locally whether to follow a palette change.
|
|
3523
|
+
*/
|
|
3524
|
+
async setColorPalette(ctx, palette, signal) {
|
|
3525
|
+
this.assertCurrentContext(ctx);
|
|
3526
|
+
throwIfAborted5(signal, "Pi Agent Swarm palette change aborted");
|
|
3527
|
+
await this.settings.update({ colorPalette: palette });
|
|
3528
|
+
this.assertCurrentContext(ctx);
|
|
3529
|
+
throwIfAborted5(signal, "Pi Agent Swarm palette change aborted");
|
|
3530
|
+
const slot = this.color ? swarmColorName(this.color) : void 0;
|
|
3531
|
+
if (slot) {
|
|
3532
|
+
const next = this.activePalette().find((color) => color.name === slot);
|
|
3533
|
+
if (next && next.hex !== this.color) {
|
|
3534
|
+
this.color = next.hex;
|
|
3535
|
+
this.membership?.transport.setColor(next.hex);
|
|
3536
|
+
}
|
|
3537
|
+
}
|
|
3538
|
+
await this.renderFooterStatus(ctx);
|
|
3539
|
+
}
|
|
3540
|
+
async setOwnColor(ctx, color, signal) {
|
|
3541
|
+
this.assertCurrentContext(ctx);
|
|
3542
|
+
throwIfAborted5(signal, "Pi Agent Swarm color change aborted");
|
|
3543
|
+
this.color = color;
|
|
3544
|
+
this.membership?.transport.setColor(color);
|
|
3545
|
+
await this.renderFooterStatus(ctx);
|
|
3546
|
+
}
|
|
3547
|
+
async setOwnName(ctx, name, signal) {
|
|
3548
|
+
this.assertCurrentContext(ctx);
|
|
3549
|
+
throwIfAborted5(signal, "Pi Agent Swarm rename aborted");
|
|
3550
|
+
const normalized = normalizeOptionalText(name, "name", 200);
|
|
3551
|
+
if (!normalized) throw new Error("Pi Agent Swarm session name must not be empty");
|
|
3552
|
+
this.pi.setSessionName(normalized);
|
|
3553
|
+
this.membership?.transport.setName(normalized);
|
|
3554
|
+
await this.renderFooterStatus(ctx);
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
3557
|
+
* Best-effort, ordered relay of a direct user steer to the parent session so it
|
|
3558
|
+
* stays aligned. This returns immediately: sends are chained so ordering is
|
|
3559
|
+
* preserved while the input event path is never blocked by a slow parent.
|
|
3560
|
+
*/
|
|
3561
|
+
relaySteerInput(text, ctx) {
|
|
3562
|
+
if (!this.isCurrent(ctx)) return;
|
|
3563
|
+
const membership = this.membership;
|
|
3564
|
+
const parentSessionId = this.parentSessionId;
|
|
3565
|
+
if (!membership || !parentSessionId) return;
|
|
3566
|
+
const self = membership.transport.peerDescription;
|
|
3567
|
+
if (parentSessionId === self.sessionId) return;
|
|
3568
|
+
const issuedAt = this.deps.now();
|
|
3569
|
+
const message = {
|
|
3570
|
+
id: this.deps.randomId("msg"),
|
|
3571
|
+
fromSessionId: self.sessionId,
|
|
3572
|
+
...self.name ? { fromName: self.name } : {},
|
|
3573
|
+
fromCwd: self.cwd,
|
|
3574
|
+
toSessionId: parentSessionId,
|
|
3575
|
+
mode: "notify",
|
|
3576
|
+
text: truncateToBytes(text, MAX_MESSAGE_BYTES),
|
|
3577
|
+
kind: "steer",
|
|
3578
|
+
issuedAt,
|
|
3579
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS
|
|
3580
|
+
};
|
|
3581
|
+
this.relayChain = this.relayChain.then(() => membership.transport.send(parentSessionId, message, this.controller.signal)).then(
|
|
3582
|
+
() => void 0,
|
|
3583
|
+
() => void 0
|
|
3584
|
+
);
|
|
3585
|
+
}
|
|
3586
|
+
async broadcastLeadChange(target) {
|
|
3587
|
+
const membership = this.membership;
|
|
3588
|
+
if (!membership) return;
|
|
3589
|
+
const self = membership.transport.peerDescription;
|
|
3590
|
+
let peers;
|
|
3591
|
+
try {
|
|
3592
|
+
peers = await membership.transport.listPeers();
|
|
3593
|
+
} catch {
|
|
3594
|
+
return;
|
|
3595
|
+
}
|
|
3596
|
+
const issuedAt = this.deps.now();
|
|
3597
|
+
const text = `lead changed to ${target.name ?? target.sessionId}`;
|
|
3598
|
+
for (const peer of peers) {
|
|
3599
|
+
if (peer.sessionId === self.sessionId) continue;
|
|
3600
|
+
const message = {
|
|
3601
|
+
id: this.deps.randomId("msg"),
|
|
3602
|
+
fromSessionId: self.sessionId,
|
|
3603
|
+
...self.name ? { fromName: self.name } : {},
|
|
3604
|
+
fromCwd: self.cwd,
|
|
3605
|
+
toSessionId: peer.sessionId,
|
|
3606
|
+
mode: "notify",
|
|
3607
|
+
text,
|
|
3608
|
+
kind: "lead",
|
|
3609
|
+
issuedAt,
|
|
3610
|
+
expiresAt: issuedAt + DEFAULT_MESSAGE_TTL_MS
|
|
3611
|
+
};
|
|
3612
|
+
try {
|
|
3613
|
+
await membership.transport.send(peer.sessionId, message);
|
|
3614
|
+
} catch {
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
startLeadWatcher() {
|
|
3619
|
+
this.stopLeadWatcher();
|
|
3620
|
+
this.leadWatcher = setInterval(() => {
|
|
3621
|
+
if (this.controller.signal.aborted) return;
|
|
3622
|
+
const activeContext = this.activeContext;
|
|
3623
|
+
if (!activeContext) return;
|
|
3624
|
+
void this.refreshLead().then((changed) => {
|
|
3625
|
+
if (changed && !this.controller.signal.aborted) void this.renderFooterStatus(activeContext);
|
|
3626
|
+
});
|
|
3627
|
+
}, 5e3);
|
|
3628
|
+
}
|
|
3629
|
+
stopLeadWatcher() {
|
|
3630
|
+
if (this.leadWatcher !== void 0) {
|
|
3631
|
+
clearInterval(this.leadWatcher);
|
|
3632
|
+
this.leadWatcher = void 0;
|
|
3633
|
+
}
|
|
3634
|
+
}
|
|
3635
|
+
// A resized terminal can cross a footer tier boundary, so re-render the badge with
|
|
3636
|
+
// the new width. The listener is TTY-only and session-owned: attached at session
|
|
3637
|
+
// start, detached at shutdown, and idempotent against repeated calls.
|
|
3638
|
+
startResizeWatcher() {
|
|
3639
|
+
this.stopResizeWatcher();
|
|
3640
|
+
if (!process.stdout.isTTY || typeof process.stdout.on !== "function") return;
|
|
3641
|
+
process.stdout.on("resize", this.resizeListener);
|
|
3642
|
+
this.resizeWatching = true;
|
|
3643
|
+
}
|
|
3644
|
+
stopResizeWatcher() {
|
|
3645
|
+
if (this.resizeWatching) {
|
|
3646
|
+
process.stdout.off("resize", this.resizeListener);
|
|
3647
|
+
this.resizeWatching = false;
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
onTerminalResize() {
|
|
3651
|
+
if (this.controller.signal.aborted) return;
|
|
3652
|
+
const activeContext = this.activeContext;
|
|
3653
|
+
if (!activeContext) return;
|
|
3654
|
+
void this.renderFooterStatus(activeContext);
|
|
3655
|
+
}
|
|
3656
|
+
notify(ctx, message, level) {
|
|
3657
|
+
if (!ctx.hasUI) return;
|
|
3658
|
+
try {
|
|
3659
|
+
ctx.ui.notify(message, level);
|
|
3660
|
+
} catch {
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
};
|
|
3664
|
+
function recentSwarmState(ctx) {
|
|
3665
|
+
const messageIds = [];
|
|
3666
|
+
const consumedLaunchIds = /* @__PURE__ */ new Set();
|
|
3667
|
+
for (const entry of ctx.sessionManager.getBranch().slice(-1024)) {
|
|
3668
|
+
if (!isRecord4(entry) || entry.type !== "custom_message" || entry.customType !== SWARM_MESSAGE_TYPE) {
|
|
3669
|
+
continue;
|
|
3670
|
+
}
|
|
3671
|
+
const details = entry.details;
|
|
3672
|
+
if (!isRecord4(details) || !isRecord4(details.message) || typeof details.message.id !== "string") {
|
|
3673
|
+
continue;
|
|
3674
|
+
}
|
|
3675
|
+
messageIds.push(details.message.id);
|
|
3676
|
+
if (details.message.mode === "kickoff" && typeof details.message.launchId === "string") {
|
|
3677
|
+
consumedLaunchIds.add(details.message.launchId);
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
return { messageIds, consumedLaunchIds };
|
|
3681
|
+
}
|
|
3682
|
+
function combineSignals2(...signals) {
|
|
3683
|
+
const concrete = signals.filter((signal) => signal !== void 0);
|
|
3684
|
+
return concrete.length === 0 ? new AbortController().signal : concrete.length === 1 ? concrete[0] : AbortSignal.any(concrete);
|
|
3685
|
+
}
|
|
3686
|
+
async function abortableSleep2(milliseconds, signal) {
|
|
3687
|
+
throwIfAborted5(signal, "Pi Agent Swarm wait aborted");
|
|
3688
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
3689
|
+
const finish = (error) => {
|
|
3690
|
+
clearTimeout(timer);
|
|
3691
|
+
signal?.removeEventListener("abort", abort);
|
|
3692
|
+
if (error) rejectPromise(error);
|
|
3693
|
+
else resolvePromise();
|
|
3694
|
+
};
|
|
3695
|
+
const timer = setTimeout(() => finish(), milliseconds);
|
|
3696
|
+
const abort = () => finish(abortError4("Pi Agent Swarm wait aborted"));
|
|
3697
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
3698
|
+
if (signal?.aborted) abort();
|
|
3699
|
+
});
|
|
3700
|
+
}
|
|
3701
|
+
function throwIfAborted5(signal, message) {
|
|
3702
|
+
if (signal?.aborted) throw abortError4(message);
|
|
3703
|
+
}
|
|
3704
|
+
function abortError4(message) {
|
|
3705
|
+
const error = new Error(message);
|
|
3706
|
+
error.name = "AbortError";
|
|
3707
|
+
return error;
|
|
3708
|
+
}
|
|
3709
|
+
function staleError() {
|
|
3710
|
+
return new Error("Pi Agent Swarm session is stale");
|
|
3711
|
+
}
|
|
3712
|
+
function truncateToBytes(value, maxBytes) {
|
|
3713
|
+
if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
|
|
3714
|
+
return Buffer.from(value, "utf8").subarray(0, maxBytes).toString("utf8");
|
|
3715
|
+
}
|
|
3716
|
+
function isRecord4(value) {
|
|
3717
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3718
|
+
}
|
|
3719
|
+
|
|
3720
|
+
// src/tools.ts
|
|
3721
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
3722
|
+
import { Type } from "typebox";
|
|
3723
|
+
var DIRECTIONS = ["right", "down", "left", "up"];
|
|
3724
|
+
var BUS_ACTIONS = ["list", "send", "reply", "shutdown"];
|
|
3725
|
+
var SEND_MODES = ["notify", "request"];
|
|
3726
|
+
var MAX_LISTED_PEERS = 64;
|
|
3727
|
+
var MAX_LIST_RESULT_BYTES = 40 * 1024;
|
|
3728
|
+
var spawnSchema = Type.Object(
|
|
3729
|
+
{
|
|
3730
|
+
direction: Type.Optional(StringEnum(DIRECTIONS, { description: "Terminal window direction" })),
|
|
3731
|
+
task: Type.Optional(
|
|
3732
|
+
Type.String({
|
|
3733
|
+
description: "Optional first task sent after child readiness",
|
|
3734
|
+
maxLength: 16384
|
|
3735
|
+
})
|
|
3736
|
+
),
|
|
3737
|
+
name: Type.Optional(Type.String({ description: "Optional child Pi session name", maxLength: 200 })),
|
|
3738
|
+
color: Type.Optional(
|
|
3739
|
+
Type.String({
|
|
3740
|
+
description: "Optional child color: a palette name (red, orange, yellow, green, cyan, blue, magenta, purple) or a #rrggbb hex",
|
|
3741
|
+
maxLength: 32
|
|
3742
|
+
})
|
|
3743
|
+
),
|
|
3744
|
+
model: Type.Optional(
|
|
3745
|
+
Type.String({
|
|
3746
|
+
description: "Optional child model as provider/id (e.g. deepseek/deepseek-v4-pro, kimi-coding/k3); defaults to inheriting the current session model",
|
|
3747
|
+
maxLength: 200
|
|
3748
|
+
})
|
|
3749
|
+
),
|
|
3750
|
+
cwd: Type.Optional(
|
|
3751
|
+
Type.String({
|
|
3752
|
+
description: "Existing child working directory, defaulting to the current cwd",
|
|
3753
|
+
maxLength: 4096
|
|
3754
|
+
})
|
|
3755
|
+
)
|
|
3756
|
+
},
|
|
3757
|
+
{ additionalProperties: false }
|
|
3758
|
+
);
|
|
3759
|
+
var busSchema = Type.Object(
|
|
3760
|
+
{
|
|
3761
|
+
action: StringEnum(BUS_ACTIONS, {
|
|
3762
|
+
description: "List sessions, send a message, reply, or request a graceful shutdown"
|
|
3763
|
+
}),
|
|
3764
|
+
targetSessionId: Type.Optional(
|
|
3765
|
+
Type.String({ description: "Destination Pi session id", minLength: 1, maxLength: 128 })
|
|
3766
|
+
),
|
|
3767
|
+
message: Type.Optional(Type.String({ description: "Message or request body", maxLength: 16384 })),
|
|
3768
|
+
mode: Type.Optional(StringEnum(SEND_MODES, { description: "Notify without a turn or request one turn" })),
|
|
3769
|
+
replyTo: Type.Optional(
|
|
3770
|
+
Type.String({ description: "Original message id for a reply", minLength: 1, maxLength: 128 })
|
|
3771
|
+
)
|
|
3772
|
+
},
|
|
3773
|
+
{ additionalProperties: false }
|
|
3774
|
+
);
|
|
3775
|
+
function registerSwarmTools(pi, controller) {
|
|
3776
|
+
pi.registerTool({
|
|
3777
|
+
name: "session_spawn",
|
|
3778
|
+
label: "Spawn Pi Session",
|
|
3779
|
+
description: "Create a separate Pi process in an external terminal window, wait for authenticated readiness, and optionally send its first task. This preserves the current session and follows the configured launch-confirmation policy.",
|
|
3780
|
+
promptSnippet: "Start a collaborating Pi session in an external terminal window",
|
|
3781
|
+
promptGuidelines: [
|
|
3782
|
+
"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."
|
|
3784
|
+
],
|
|
3785
|
+
parameters: spawnSchema,
|
|
3786
|
+
executionMode: "sequential",
|
|
3787
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
3788
|
+
onUpdate?.({
|
|
3789
|
+
content: [
|
|
3790
|
+
{
|
|
3791
|
+
type: "text",
|
|
3792
|
+
text: "Preparing a Pi session launch in an external terminal window\u2026"
|
|
3793
|
+
}
|
|
3794
|
+
],
|
|
3795
|
+
details: { phase: "preparing" }
|
|
3796
|
+
});
|
|
3797
|
+
const result = await controller.spawn(ctx, params, signal);
|
|
3798
|
+
return {
|
|
3799
|
+
content: [
|
|
3800
|
+
{
|
|
3801
|
+
type: "text",
|
|
3802
|
+
text: `Pi session ${safeTerminalLine(result.name ?? result.sessionId)} is ready in an external window (${safeTerminalLine(result.cwd)}).${result.kickoffAccepted ? " Its first task was accepted." : " No first task was sent."}`
|
|
3803
|
+
}
|
|
3804
|
+
],
|
|
3805
|
+
details: result
|
|
3806
|
+
};
|
|
3807
|
+
}
|
|
3808
|
+
});
|
|
3809
|
+
pi.registerTool({
|
|
3810
|
+
name: "session_bus",
|
|
3811
|
+
label: "Pi Session Bus",
|
|
3812
|
+
description: "List authenticated Pi Agent Swarm sessions, send a notify or one-turn request, or correlate a non-triggering reply. Delivery acknowledgement means accepted by the extension, not task completion.",
|
|
3813
|
+
promptSnippet: "List or message Pi Agent Swarm sessions on this machine",
|
|
3814
|
+
promptGuidelines: [
|
|
3815
|
+
"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."
|
|
3817
|
+
],
|
|
3818
|
+
parameters: busSchema,
|
|
3819
|
+
executionMode: "sequential",
|
|
3820
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
3821
|
+
if (params.action === "list") {
|
|
3822
|
+
assertAbsent(params.targetSessionId, "targetSessionId", "list");
|
|
3823
|
+
assertAbsent(params.message, "message", "list");
|
|
3824
|
+
assertAbsent(params.mode, "mode", "list");
|
|
3825
|
+
assertAbsent(params.replyTo, "replyTo", "list");
|
|
3826
|
+
const snapshot = await controller.snapshot(signal);
|
|
3827
|
+
if (!snapshot.connected) {
|
|
3828
|
+
return {
|
|
3829
|
+
content: [{ type: "text", text: "Pi Agent Swarm is not connected to a local group." }],
|
|
3830
|
+
details: { connected: false, peers: [] }
|
|
3831
|
+
};
|
|
3832
|
+
}
|
|
3833
|
+
return peerListResult(snapshot);
|
|
3834
|
+
}
|
|
3835
|
+
if (params.action === "shutdown") {
|
|
3836
|
+
assertAbsent(params.message, "message", "shutdown");
|
|
3837
|
+
assertAbsent(params.mode, "mode", "shutdown");
|
|
3838
|
+
assertAbsent(params.replyTo, "replyTo", "shutdown");
|
|
3839
|
+
const shutdownTarget = required(params.targetSessionId, "targetSessionId");
|
|
3840
|
+
const result2 = await controller.shutdownPeer(ctx, shutdownTarget, signal);
|
|
3841
|
+
return shutdownResult(result2, shutdownTarget);
|
|
3842
|
+
}
|
|
3843
|
+
const targetSessionId = required(params.targetSessionId, "targetSessionId");
|
|
3844
|
+
const message = required(params.message, "message");
|
|
3845
|
+
if (params.action === "send") {
|
|
3846
|
+
assertAbsent(params.replyTo, "replyTo", "send");
|
|
3847
|
+
const mode = params.mode ?? "notify";
|
|
3848
|
+
const result2 = await controller.send(ctx, { targetSessionId, text: message, mode }, signal);
|
|
3849
|
+
return deliveryResult(result2, targetSessionId);
|
|
3850
|
+
}
|
|
3851
|
+
assertAbsent(params.mode, "mode", "reply");
|
|
3852
|
+
const replyTo = required(params.replyTo, "replyTo");
|
|
3853
|
+
const result = await controller.send(ctx, { targetSessionId, text: message, mode: "reply", replyTo }, signal);
|
|
3854
|
+
return deliveryResult(result, targetSessionId);
|
|
3855
|
+
}
|
|
3856
|
+
});
|
|
3857
|
+
}
|
|
3858
|
+
function peerListResult(snapshot) {
|
|
3859
|
+
const peers = [];
|
|
3860
|
+
const lines = [];
|
|
3861
|
+
for (const peer of snapshot.peers.slice(0, MAX_LISTED_PEERS)) {
|
|
3862
|
+
const listedPeer = {
|
|
3863
|
+
...peer,
|
|
3864
|
+
...peer.name ? { name: safeTerminalLine(peer.name) } : {},
|
|
3865
|
+
cwd: safeTerminalLine(peer.cwd)
|
|
3866
|
+
};
|
|
3867
|
+
const colorLabel = listedPeer.color ? swarmColorName(listedPeer.color) ?? listedPeer.color : "no-color";
|
|
3868
|
+
const line = `${listedPeer.name ?? listedPeer.sessionId} \xB7 ${listedPeer.sessionId} \xB7 ${colorLabel} \xB7 ${listedPeer.cwd} \xB7 requests ${listedPeer.acceptsRequests ? "allowed" : "blocked"}`;
|
|
3869
|
+
const candidate = createPeerListResult(snapshot, [...peers, listedPeer], [...lines, line]);
|
|
3870
|
+
if (Buffer.byteLength(JSON.stringify(candidate), "utf8") > MAX_LIST_RESULT_BYTES) break;
|
|
3871
|
+
peers.push(listedPeer);
|
|
3872
|
+
lines.push(line);
|
|
3873
|
+
}
|
|
3874
|
+
return createPeerListResult(snapshot, peers, lines);
|
|
3875
|
+
}
|
|
3876
|
+
function createPeerListResult(snapshot, peers, lines) {
|
|
3877
|
+
const peerText = lines.length ? lines.join("\n") : "Pi Agent Swarm is connected, but no other live sessions were found.";
|
|
3878
|
+
const text = snapshot.discoveryIssues?.length ? `${peerText}
|
|
3879
|
+
Discovery reported ${snapshot.discoveryIssues.length} bounded transport issue(s); inspect tool details before retrying.` : peerText;
|
|
3880
|
+
return {
|
|
3881
|
+
content: [{ type: "text", text }],
|
|
3882
|
+
details: {
|
|
3883
|
+
connected: true,
|
|
3884
|
+
peers,
|
|
3885
|
+
truncated: snapshot.peers.length > peers.length,
|
|
3886
|
+
...snapshot.discoveryIssues ? { discoveryIssues: snapshot.discoveryIssues } : {},
|
|
3887
|
+
...snapshot.discoverySaturated ? { discoverySaturated: true } : {}
|
|
3888
|
+
}
|
|
3889
|
+
};
|
|
3890
|
+
}
|
|
3891
|
+
function deliveryResult(result, targetSessionId) {
|
|
3892
|
+
if (!result.acknowledgement.accepted) {
|
|
3893
|
+
const code = result.acknowledgement.code ? ` [${result.acknowledgement.code}]` : "";
|
|
3894
|
+
const retry = result.acknowledgement.retryAfterMs ? ` Retry after about ${result.acknowledgement.retryAfterMs}ms.` : "";
|
|
3895
|
+
throw new Error(
|
|
3896
|
+
`Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} rejected the message${code}: ${safeTerminalLine(result.acknowledgement.error ?? "unknown reason")}.${retry}`
|
|
3897
|
+
);
|
|
3898
|
+
}
|
|
3899
|
+
return {
|
|
3900
|
+
content: [
|
|
3901
|
+
{
|
|
3902
|
+
type: "text",
|
|
3903
|
+
text: `Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} accepted message ${safeTerminalLine(result.message.id)}${result.acknowledgement.duplicate ? " as an already-seen duplicate" : ""}. This does not prove remote task completion.`
|
|
3904
|
+
}
|
|
3905
|
+
],
|
|
3906
|
+
details: {
|
|
3907
|
+
messageId: result.message.id,
|
|
3908
|
+
targetSessionId,
|
|
3909
|
+
accepted: true,
|
|
3910
|
+
duplicate: result.acknowledgement.duplicate
|
|
3911
|
+
}
|
|
3912
|
+
};
|
|
3913
|
+
}
|
|
3914
|
+
function shutdownResult(result, targetSessionId) {
|
|
3915
|
+
if (!result.acknowledgement.accepted) {
|
|
3916
|
+
const code = result.acknowledgement.code ? ` [${result.acknowledgement.code}]` : "";
|
|
3917
|
+
const retry = result.acknowledgement.retryAfterMs ? ` Retry after about ${result.acknowledgement.retryAfterMs}ms.` : "";
|
|
3918
|
+
throw new Error(
|
|
3919
|
+
`Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} rejected the shutdown request${code}: ${safeTerminalLine(result.acknowledgement.error ?? "unknown reason")}.${retry}`
|
|
3920
|
+
);
|
|
3921
|
+
}
|
|
3922
|
+
return {
|
|
3923
|
+
content: [
|
|
3924
|
+
{
|
|
3925
|
+
type: "text",
|
|
3926
|
+
text: `Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} accepted the shutdown request (message ${safeTerminalLine(result.message.id)}). The peer was asked to shut down gracefully; this does not guarantee it has exited yet.`
|
|
3927
|
+
}
|
|
3928
|
+
],
|
|
3929
|
+
details: {
|
|
3930
|
+
messageId: result.message.id,
|
|
3931
|
+
targetSessionId,
|
|
3932
|
+
accepted: true,
|
|
3933
|
+
duplicate: result.acknowledgement.duplicate
|
|
3934
|
+
}
|
|
3935
|
+
};
|
|
3936
|
+
}
|
|
3937
|
+
function required(value, field) {
|
|
3938
|
+
if (value === void 0 || value.length === 0) {
|
|
3939
|
+
throw new Error(`session_bus ${field} is required for this action`);
|
|
3940
|
+
}
|
|
3941
|
+
return value;
|
|
3942
|
+
}
|
|
3943
|
+
function assertAbsent(value, field, action) {
|
|
3944
|
+
if (value !== void 0) throw new Error(`session_bus ${field} is not accepted for action ${action}`);
|
|
3945
|
+
}
|
|
3946
|
+
|
|
3947
|
+
// src/pi-agent-swarm.ts
|
|
3948
|
+
var USAGE = "Usage: /swarm, /swarm start, or /swarm <piagentswarm:v1:invite>";
|
|
3949
|
+
function createPiSwarmExtension(dependencies = {}) {
|
|
3950
|
+
return function piSwarmExtension(pi) {
|
|
3951
|
+
const settings = dependencies.settingsRuntime ?? createSwarmSettingsRuntime();
|
|
3952
|
+
const controller = new SwarmController(pi, dependencies.controllerDependencies, settings);
|
|
3953
|
+
const loadMenu = cachedModuleLoader(dependencies.loadMenu ?? (() => import("./chunks/menu-RH6GY6U4.ts")));
|
|
3954
|
+
pi.registerMessageRenderer(SWARM_MESSAGE_TYPE, renderSwarmMessage);
|
|
3955
|
+
registerSwarmTools(pi, controller);
|
|
3956
|
+
pi.on("session_start", async (event, ctx) => {
|
|
3957
|
+
await controller.sessionStart(event, ctx);
|
|
3958
|
+
});
|
|
3959
|
+
pi.on("session_shutdown", async (event, ctx) => {
|
|
3960
|
+
await controller.sessionShutdown(event, ctx);
|
|
3961
|
+
});
|
|
3962
|
+
pi.on("input", async (event, ctx) => {
|
|
3963
|
+
if (event.source !== "interactive") return;
|
|
3964
|
+
void controller.relaySteerInput(event.text, ctx);
|
|
3965
|
+
});
|
|
3966
|
+
pi.registerCommand("swarm", {
|
|
3967
|
+
description: "Spawn a worker Pi session, or start/join a local group",
|
|
3968
|
+
handler: async (rawArgs, ctx) => {
|
|
3969
|
+
const args = rawArgs.trim();
|
|
3970
|
+
if (ctx.mode !== "tui" && ctx.mode !== "rpc") {
|
|
3971
|
+
throw new Error(`Pi Agent Swarm is unavailable in ${ctx.mode} mode. ${USAGE}`);
|
|
3972
|
+
}
|
|
3973
|
+
if (args === "start") {
|
|
3974
|
+
await startGroupDirectly(controller, ctx);
|
|
3975
|
+
return;
|
|
3976
|
+
}
|
|
3977
|
+
if (args) {
|
|
3978
|
+
await joinDirectInvite(controller, args, ctx);
|
|
3979
|
+
return;
|
|
3980
|
+
}
|
|
3981
|
+
const ownerSignal = controller.sessionSignal;
|
|
3982
|
+
const menuModule = await loadMenu();
|
|
3983
|
+
if (ownerSignal.aborted || !controller.isCurrent(ctx)) return;
|
|
3984
|
+
await menuModule.showSwarmMenu(ctx, menuSource(controller), {
|
|
3985
|
+
signal: ownerSignal,
|
|
3986
|
+
isCurrent: () => controller.isCurrent(ctx) && !ownerSignal.aborted
|
|
3987
|
+
});
|
|
3988
|
+
}
|
|
3989
|
+
});
|
|
3990
|
+
pi.registerCommand("lead", {
|
|
3991
|
+
description: "Set the swarm lead (coordinator) by session name or id",
|
|
3992
|
+
handler: async (rawArgs, ctx) => {
|
|
3993
|
+
const target = rawArgs.trim();
|
|
3994
|
+
if (!target) throw new Error("Usage: /lead <session name or id>");
|
|
3995
|
+
const signal = controller.sessionSignal;
|
|
3996
|
+
const peer = await controller.resolvePeer(target, signal);
|
|
3997
|
+
if (!peer) throw new Error(`No live Pi Agent Swarm session matches "${target}"`);
|
|
3998
|
+
await controller.setLead(ctx, peer, signal);
|
|
3999
|
+
ctx.ui.notify(`Lead is now ${peer.name ?? peer.sessionId}.`, "info");
|
|
4000
|
+
}
|
|
4001
|
+
});
|
|
4002
|
+
pi.registerCommand("color", {
|
|
4003
|
+
description: "Set this session's color (palette name or #rrggbb)",
|
|
4004
|
+
handler: async (rawArgs, ctx) => {
|
|
4005
|
+
const color = controller.normalizeColor(rawArgs.trim());
|
|
4006
|
+
if (!color) {
|
|
4007
|
+
throw new Error("Usage: /color <red|orange|yellow|green|cyan|blue|magenta|purple|#rrggbb>");
|
|
4008
|
+
}
|
|
4009
|
+
await controller.setOwnColor(ctx, color);
|
|
4010
|
+
ctx.ui.notify(`Color set to ${color}.`, "info");
|
|
4011
|
+
}
|
|
4012
|
+
});
|
|
4013
|
+
};
|
|
4014
|
+
}
|
|
4015
|
+
async function joinDirectInvite(controller, invite, ctx) {
|
|
4016
|
+
try {
|
|
4017
|
+
parseInvite(invite);
|
|
4018
|
+
} catch {
|
|
4019
|
+
throw new Error(USAGE);
|
|
4020
|
+
}
|
|
4021
|
+
const signal = controller.sessionSignal;
|
|
4022
|
+
if (signal.aborted) return;
|
|
4023
|
+
const confirmed = await ctx.ui.confirm(
|
|
4024
|
+
"Join local Pi Agent Swarm group?",
|
|
4025
|
+
"The bearer invite permits local peer messages. Incoming agent requests start blocked.",
|
|
4026
|
+
{ signal }
|
|
4027
|
+
);
|
|
4028
|
+
if (!confirmed || signal.aborted || !controller.isCurrent(ctx)) return;
|
|
4029
|
+
await controller.joinInvite(ctx, invite, false, signal);
|
|
4030
|
+
if (controller.isCurrent(ctx)) {
|
|
4031
|
+
ctx.ui.notify("Joined the local Pi Agent Swarm group.", "info");
|
|
4032
|
+
}
|
|
4033
|
+
}
|
|
4034
|
+
async function startGroupDirectly(controller, ctx) {
|
|
4035
|
+
const signal = controller.sessionSignal;
|
|
4036
|
+
if (signal.aborted) return;
|
|
4037
|
+
await controller.startNewGroup(ctx, false, signal);
|
|
4038
|
+
if (controller.isCurrent(ctx)) {
|
|
4039
|
+
ctx.ui.notify("Started a local Pi Agent Swarm group. You are its lead.", "info");
|
|
4040
|
+
}
|
|
4041
|
+
}
|
|
4042
|
+
function menuSource(controller) {
|
|
4043
|
+
return {
|
|
4044
|
+
snapshot: (signal) => controller.snapshot(signal),
|
|
4045
|
+
spawn: async (commandContext, input, signal) => {
|
|
4046
|
+
const result = await controller.spawn(commandContext, input, signal);
|
|
4047
|
+
if (controller.isCurrent(commandContext)) {
|
|
4048
|
+
commandContext.ui.notify(
|
|
4049
|
+
`Pi session ${safeTerminalLine(result.name ?? result.sessionId)} is ready in an external window.`,
|
|
4050
|
+
"info"
|
|
4051
|
+
);
|
|
4052
|
+
}
|
|
4053
|
+
},
|
|
4054
|
+
rename: async (commandContext, name, signal) => {
|
|
4055
|
+
await controller.setOwnName(commandContext, name, signal);
|
|
4056
|
+
if (controller.isCurrent(commandContext)) {
|
|
4057
|
+
commandContext.ui.notify(`Session renamed to ${safeTerminalLine(name)}.`, "info");
|
|
4058
|
+
}
|
|
4059
|
+
},
|
|
4060
|
+
setColor: async (commandContext, color, signal) => {
|
|
4061
|
+
const normalized = controller.normalizeColor(color);
|
|
4062
|
+
if (!normalized) throw new Error("Pi Agent Swarm color is invalid");
|
|
4063
|
+
await controller.setOwnColor(commandContext, normalized, signal);
|
|
4064
|
+
if (controller.isCurrent(commandContext)) {
|
|
4065
|
+
commandContext.ui.notify(`Color set to ${normalized}.`, "info");
|
|
4066
|
+
}
|
|
4067
|
+
},
|
|
4068
|
+
setPalette: async (commandContext, palette, signal) => {
|
|
4069
|
+
await controller.setColorPalette(commandContext, palette, signal);
|
|
4070
|
+
if (controller.isCurrent(commandContext)) {
|
|
4071
|
+
commandContext.ui.notify(`Theme set to ${palette}.`, "info");
|
|
4072
|
+
}
|
|
4073
|
+
}
|
|
4074
|
+
};
|
|
4075
|
+
}
|
|
4076
|
+
function cachedModuleLoader(load) {
|
|
4077
|
+
let cached;
|
|
4078
|
+
return async () => {
|
|
4079
|
+
if (!cached) {
|
|
4080
|
+
cached = load().catch((error) => {
|
|
4081
|
+
cached = void 0;
|
|
4082
|
+
throw error;
|
|
4083
|
+
});
|
|
4084
|
+
}
|
|
4085
|
+
return cached;
|
|
4086
|
+
};
|
|
4087
|
+
}
|
|
4088
|
+
var pi_agent_swarm_default = createPiSwarmExtension();
|
|
4089
|
+
export {
|
|
4090
|
+
pi_agent_swarm_default as default
|
|
4091
|
+
};
|
|
4092
|
+
//# sourceMappingURL=index.ts.map
|