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/src/terminal.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { ExternalLaunchError, ExternalTerminalAdapter } from "./external.js";
|
|
3
|
+
import { detectI3, I3WorkspacePinner } from "./i3-workspace.js";
|
|
4
|
+
|
|
5
|
+
export type TerminalSplitDirection = "right" | "down" | "left" | "up";
|
|
6
|
+
|
|
7
|
+
export interface SwarmTerminalPort {
|
|
8
|
+
assertAvailable(signal?: AbortSignal): Promise<string>;
|
|
9
|
+
spawnSplit(options: {
|
|
10
|
+
direction: TerminalSplitDirection;
|
|
11
|
+
cwd: string;
|
|
12
|
+
launcherCommand: string;
|
|
13
|
+
environment: Readonly<Record<string, string>>;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
isCurrent(): boolean;
|
|
16
|
+
}): Promise<{ terminalId: string; version: string }>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createDefaultTerminalPort(
|
|
20
|
+
pi: ExtensionAPI,
|
|
21
|
+
externalCommand?: readonly string[],
|
|
22
|
+
pinToLeadWorkspace = false,
|
|
23
|
+
): SwarmTerminalPort {
|
|
24
|
+
const options = {
|
|
25
|
+
execute: async (
|
|
26
|
+
command: string,
|
|
27
|
+
args: string[],
|
|
28
|
+
execution: {
|
|
29
|
+
signal?: AbortSignal;
|
|
30
|
+
timeoutMs: number;
|
|
31
|
+
},
|
|
32
|
+
) =>
|
|
33
|
+
pi.exec(command, args, {
|
|
34
|
+
...(execution.signal ? { signal: execution.signal } : {}),
|
|
35
|
+
timeout: execution.timeoutMs,
|
|
36
|
+
}),
|
|
37
|
+
};
|
|
38
|
+
return new ExternalTerminalAdapter(
|
|
39
|
+
externalCommand ?? ["alacritty", "-e"],
|
|
40
|
+
pinToLeadWorkspace && detectI3(process.env) ? new I3WorkspacePinner(options) : undefined,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isTerminalLaunchError(error: unknown): error is ExternalLaunchError {
|
|
45
|
+
return error instanceof ExternalLaunchError;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createTerminalLaunchError(
|
|
49
|
+
message: string,
|
|
50
|
+
splitCreated: boolean,
|
|
51
|
+
terminalId?: string,
|
|
52
|
+
): ExternalLaunchError {
|
|
53
|
+
return new ExternalLaunchError(message, splitCreated, terminalId);
|
|
54
|
+
}
|
package/src/text.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export function safeTerminalText(value: string): string {
|
|
2
|
+
let output = "";
|
|
3
|
+
for (const character of value) {
|
|
4
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
5
|
+
if (isTerminalControl(codePoint)) continue;
|
|
6
|
+
output += character === "\t" ? " " : character;
|
|
7
|
+
}
|
|
8
|
+
return output;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function safeTerminalLine(value: string): string {
|
|
12
|
+
return safeTerminalText(value)
|
|
13
|
+
.replace(/[\r\n]+/gu, " ")
|
|
14
|
+
.trim();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function safeError(error: unknown): string {
|
|
18
|
+
return safeTerminalLine(error instanceof Error ? error.message : String(error));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function normalizeOptionalText(value: string | undefined, label: string, maxBytes: number): string | undefined {
|
|
22
|
+
if (value === undefined) return undefined;
|
|
23
|
+
const normalized = value.trim();
|
|
24
|
+
if (!normalized) return undefined;
|
|
25
|
+
if (normalized.includes("\0") || Buffer.byteLength(normalized) > maxBytes) {
|
|
26
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid or too large`);
|
|
27
|
+
}
|
|
28
|
+
return normalized;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isTerminalControl(codePoint: number): boolean {
|
|
32
|
+
return (
|
|
33
|
+
(codePoint >= 0x00 && codePoint <= 0x08) ||
|
|
34
|
+
codePoint === 0x0b ||
|
|
35
|
+
codePoint === 0x0c ||
|
|
36
|
+
codePoint === 0x0d ||
|
|
37
|
+
(codePoint >= 0x0e && codePoint <= 0x1f) ||
|
|
38
|
+
(codePoint >= 0x7f && codePoint <= 0x9f) ||
|
|
39
|
+
(codePoint >= 0x202a && codePoint <= 0x202e) ||
|
|
40
|
+
(codePoint >= 0x2066 && codePoint <= 0x2069)
|
|
41
|
+
);
|
|
42
|
+
}
|
package/src/tools.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { swarmColorName } from "./color.js";
|
|
5
|
+
import type { SwarmMessage } from "./protocol.js";
|
|
6
|
+
import type { SpawnSessionInput, SpawnSessionResult, SwarmSnapshot } from "./swarm-controller.js";
|
|
7
|
+
import { safeTerminalLine } from "./text.js";
|
|
8
|
+
import type { SwarmDeliveryAck } from "./transport.js";
|
|
9
|
+
|
|
10
|
+
const DIRECTIONS = ["right", "down", "left", "up"] as const;
|
|
11
|
+
const BUS_ACTIONS = ["list", "send", "reply", "shutdown"] as const;
|
|
12
|
+
const SEND_MODES = ["notify", "request"] as const;
|
|
13
|
+
const MAX_LISTED_PEERS = 64;
|
|
14
|
+
const MAX_LIST_RESULT_BYTES = 40 * 1024;
|
|
15
|
+
|
|
16
|
+
export interface SwarmToolController {
|
|
17
|
+
spawn(ctx: ExtensionContext, input: SpawnSessionInput, signal?: AbortSignal): Promise<SpawnSessionResult>;
|
|
18
|
+
snapshot(signal?: AbortSignal): Promise<SwarmSnapshot>;
|
|
19
|
+
send(
|
|
20
|
+
ctx: ExtensionContext,
|
|
21
|
+
options: {
|
|
22
|
+
targetSessionId: string;
|
|
23
|
+
text: string;
|
|
24
|
+
mode: "notify" | "request" | "reply";
|
|
25
|
+
replyTo?: string;
|
|
26
|
+
},
|
|
27
|
+
signal?: AbortSignal,
|
|
28
|
+
): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }>;
|
|
29
|
+
shutdownPeer(
|
|
30
|
+
ctx: ExtensionContext,
|
|
31
|
+
targetSessionId: string,
|
|
32
|
+
signal?: AbortSignal,
|
|
33
|
+
): Promise<{ message: SwarmMessage; acknowledgement: SwarmDeliveryAck }>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const spawnSchema = Type.Object(
|
|
37
|
+
{
|
|
38
|
+
direction: Type.Optional(StringEnum(DIRECTIONS, { description: "Terminal window direction" })),
|
|
39
|
+
task: Type.Optional(
|
|
40
|
+
Type.String({
|
|
41
|
+
description: "Optional first task sent after child readiness",
|
|
42
|
+
maxLength: 16_384,
|
|
43
|
+
}),
|
|
44
|
+
),
|
|
45
|
+
name: Type.Optional(Type.String({ description: "Optional child Pi session name", maxLength: 200 })),
|
|
46
|
+
color: Type.Optional(
|
|
47
|
+
Type.String({
|
|
48
|
+
description:
|
|
49
|
+
"Optional child color: a palette name (red, orange, yellow, green, cyan, blue, magenta, purple) or a #rrggbb hex",
|
|
50
|
+
maxLength: 32,
|
|
51
|
+
}),
|
|
52
|
+
),
|
|
53
|
+
model: Type.Optional(
|
|
54
|
+
Type.String({
|
|
55
|
+
description:
|
|
56
|
+
"Optional child model as provider/id (e.g. deepseek/deepseek-v4-pro, kimi-coding/k3); defaults to inheriting the current session model",
|
|
57
|
+
maxLength: 200,
|
|
58
|
+
}),
|
|
59
|
+
),
|
|
60
|
+
cwd: Type.Optional(
|
|
61
|
+
Type.String({
|
|
62
|
+
description: "Existing child working directory, defaulting to the current cwd",
|
|
63
|
+
maxLength: 4_096,
|
|
64
|
+
}),
|
|
65
|
+
),
|
|
66
|
+
},
|
|
67
|
+
{ additionalProperties: false },
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const busSchema = Type.Object(
|
|
71
|
+
{
|
|
72
|
+
action: StringEnum(BUS_ACTIONS, {
|
|
73
|
+
description: "List sessions, send a message, reply, or request a graceful shutdown",
|
|
74
|
+
}),
|
|
75
|
+
targetSessionId: Type.Optional(
|
|
76
|
+
Type.String({ description: "Destination Pi session id", minLength: 1, maxLength: 128 }),
|
|
77
|
+
),
|
|
78
|
+
message: Type.Optional(Type.String({ description: "Message or request body", maxLength: 16_384 })),
|
|
79
|
+
mode: Type.Optional(StringEnum(SEND_MODES, { description: "Notify without a turn or request one turn" })),
|
|
80
|
+
replyTo: Type.Optional(
|
|
81
|
+
Type.String({ description: "Original message id for a reply", minLength: 1, maxLength: 128 }),
|
|
82
|
+
),
|
|
83
|
+
},
|
|
84
|
+
{ additionalProperties: false },
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
export function registerSwarmTools(pi: ExtensionAPI, controller: SwarmToolController): void {
|
|
88
|
+
pi.registerTool({
|
|
89
|
+
name: "session_spawn",
|
|
90
|
+
label: "Spawn Pi Session",
|
|
91
|
+
description:
|
|
92
|
+
"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.",
|
|
93
|
+
promptSnippet: "Start a collaborating Pi session in an external terminal window",
|
|
94
|
+
promptGuidelines: [
|
|
95
|
+
"Use session_spawn only when the user explicitly asks to open or start another Pi session.",
|
|
96
|
+
"Do not claim the child is ready until session_spawn returns authenticated readiness metadata.",
|
|
97
|
+
],
|
|
98
|
+
parameters: spawnSchema,
|
|
99
|
+
executionMode: "sequential",
|
|
100
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
101
|
+
onUpdate?.({
|
|
102
|
+
content: [
|
|
103
|
+
{
|
|
104
|
+
type: "text",
|
|
105
|
+
text: "Preparing a Pi session launch in an external terminal window…",
|
|
106
|
+
},
|
|
107
|
+
],
|
|
108
|
+
details: { phase: "preparing" },
|
|
109
|
+
});
|
|
110
|
+
const result = await controller.spawn(ctx, params, signal);
|
|
111
|
+
return {
|
|
112
|
+
content: [
|
|
113
|
+
{
|
|
114
|
+
type: "text",
|
|
115
|
+
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."}`,
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
details: result,
|
|
119
|
+
};
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
pi.registerTool({
|
|
124
|
+
name: "session_bus",
|
|
125
|
+
label: "Pi Session Bus",
|
|
126
|
+
description:
|
|
127
|
+
"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.",
|
|
128
|
+
promptSnippet: "List or message Pi Agent Swarm sessions on this machine",
|
|
129
|
+
promptGuidelines: [
|
|
130
|
+
"Use session_bus to communicate with sessions already connected through Pi Agent Swarm.",
|
|
131
|
+
"Treat session_bus accepted acknowledgements as extension delivery only, not proof that a remote task succeeded.",
|
|
132
|
+
],
|
|
133
|
+
parameters: busSchema,
|
|
134
|
+
executionMode: "sequential",
|
|
135
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
136
|
+
if (params.action === "list") {
|
|
137
|
+
assertAbsent(params.targetSessionId, "targetSessionId", "list");
|
|
138
|
+
assertAbsent(params.message, "message", "list");
|
|
139
|
+
assertAbsent(params.mode, "mode", "list");
|
|
140
|
+
assertAbsent(params.replyTo, "replyTo", "list");
|
|
141
|
+
const snapshot = await controller.snapshot(signal);
|
|
142
|
+
if (!snapshot.connected) {
|
|
143
|
+
return {
|
|
144
|
+
content: [{ type: "text", text: "Pi Agent Swarm is not connected to a local group." }],
|
|
145
|
+
details: { connected: false, peers: [] },
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return peerListResult(snapshot);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (params.action === "shutdown") {
|
|
152
|
+
assertAbsent(params.message, "message", "shutdown");
|
|
153
|
+
assertAbsent(params.mode, "mode", "shutdown");
|
|
154
|
+
assertAbsent(params.replyTo, "replyTo", "shutdown");
|
|
155
|
+
const shutdownTarget = required(params.targetSessionId, "targetSessionId");
|
|
156
|
+
const result = await controller.shutdownPeer(ctx, shutdownTarget, signal);
|
|
157
|
+
return shutdownResult(result, shutdownTarget);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const targetSessionId = required(params.targetSessionId, "targetSessionId");
|
|
161
|
+
const message = required(params.message, "message");
|
|
162
|
+
if (params.action === "send") {
|
|
163
|
+
assertAbsent(params.replyTo, "replyTo", "send");
|
|
164
|
+
const mode = params.mode ?? "notify";
|
|
165
|
+
const result = await controller.send(ctx, { targetSessionId, text: message, mode }, signal);
|
|
166
|
+
return deliveryResult(result, targetSessionId);
|
|
167
|
+
}
|
|
168
|
+
assertAbsent(params.mode, "mode", "reply");
|
|
169
|
+
const replyTo = required(params.replyTo, "replyTo");
|
|
170
|
+
const result = await controller.send(ctx, { targetSessionId, text: message, mode: "reply", replyTo }, signal);
|
|
171
|
+
return deliveryResult(result, targetSessionId);
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function peerListResult(snapshot: SwarmSnapshot) {
|
|
177
|
+
const peers: SwarmSnapshot["peers"] = [];
|
|
178
|
+
const lines: string[] = [];
|
|
179
|
+
for (const peer of snapshot.peers.slice(0, MAX_LISTED_PEERS)) {
|
|
180
|
+
const listedPeer = {
|
|
181
|
+
...peer,
|
|
182
|
+
...(peer.name ? { name: safeTerminalLine(peer.name) } : {}),
|
|
183
|
+
cwd: safeTerminalLine(peer.cwd),
|
|
184
|
+
};
|
|
185
|
+
const colorLabel = listedPeer.color ? (swarmColorName(listedPeer.color) ?? listedPeer.color) : "no-color";
|
|
186
|
+
const line = `${listedPeer.name ?? listedPeer.sessionId} · ${listedPeer.sessionId} · ${colorLabel} · ${listedPeer.cwd} · requests ${listedPeer.acceptsRequests ? "allowed" : "blocked"}`;
|
|
187
|
+
const candidate = createPeerListResult(snapshot, [...peers, listedPeer], [...lines, line]);
|
|
188
|
+
if (Buffer.byteLength(JSON.stringify(candidate), "utf8") > MAX_LIST_RESULT_BYTES) break;
|
|
189
|
+
peers.push(listedPeer);
|
|
190
|
+
lines.push(line);
|
|
191
|
+
}
|
|
192
|
+
return createPeerListResult(snapshot, peers, lines);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function createPeerListResult(snapshot: SwarmSnapshot, peers: SwarmSnapshot["peers"], lines: string[]) {
|
|
196
|
+
const peerText = lines.length
|
|
197
|
+
? lines.join("\n")
|
|
198
|
+
: "Pi Agent Swarm is connected, but no other live sessions were found.";
|
|
199
|
+
const text = snapshot.discoveryIssues?.length
|
|
200
|
+
? `${peerText}\nDiscovery reported ${snapshot.discoveryIssues.length} bounded transport issue(s); inspect tool details before retrying.`
|
|
201
|
+
: peerText;
|
|
202
|
+
return {
|
|
203
|
+
content: [{ type: "text" as const, text }],
|
|
204
|
+
details: {
|
|
205
|
+
connected: true,
|
|
206
|
+
peers,
|
|
207
|
+
truncated: snapshot.peers.length > peers.length,
|
|
208
|
+
...(snapshot.discoveryIssues ? { discoveryIssues: snapshot.discoveryIssues } : {}),
|
|
209
|
+
...(snapshot.discoverySaturated ? { discoverySaturated: true } : {}),
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function deliveryResult(result: { message: SwarmMessage; acknowledgement: SwarmDeliveryAck }, targetSessionId: string) {
|
|
215
|
+
if (!result.acknowledgement.accepted) {
|
|
216
|
+
const code = result.acknowledgement.code ? ` [${result.acknowledgement.code}]` : "";
|
|
217
|
+
const retry = result.acknowledgement.retryAfterMs
|
|
218
|
+
? ` Retry after about ${result.acknowledgement.retryAfterMs}ms.`
|
|
219
|
+
: "";
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} rejected the message${code}: ${safeTerminalLine(result.acknowledgement.error ?? "unknown reason")}.${retry}`,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
content: [
|
|
226
|
+
{
|
|
227
|
+
type: "text" as const,
|
|
228
|
+
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.`,
|
|
229
|
+
},
|
|
230
|
+
],
|
|
231
|
+
details: {
|
|
232
|
+
messageId: result.message.id,
|
|
233
|
+
targetSessionId,
|
|
234
|
+
accepted: true,
|
|
235
|
+
duplicate: result.acknowledgement.duplicate,
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function shutdownResult(result: { message: SwarmMessage; acknowledgement: SwarmDeliveryAck }, targetSessionId: string) {
|
|
241
|
+
if (!result.acknowledgement.accepted) {
|
|
242
|
+
const code = result.acknowledgement.code ? ` [${result.acknowledgement.code}]` : "";
|
|
243
|
+
const retry = result.acknowledgement.retryAfterMs
|
|
244
|
+
? ` Retry after about ${result.acknowledgement.retryAfterMs}ms.`
|
|
245
|
+
: "";
|
|
246
|
+
throw new Error(
|
|
247
|
+
`Pi Agent Swarm session ${safeTerminalLine(targetSessionId)} rejected the shutdown request${code}: ${safeTerminalLine(result.acknowledgement.error ?? "unknown reason")}.${retry}`,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
content: [
|
|
252
|
+
{
|
|
253
|
+
type: "text" as const,
|
|
254
|
+
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.`,
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
details: {
|
|
258
|
+
messageId: result.message.id,
|
|
259
|
+
targetSessionId,
|
|
260
|
+
accepted: true,
|
|
261
|
+
duplicate: result.acknowledgement.duplicate,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function required(value: string | undefined, field: string): string {
|
|
267
|
+
if (value === undefined || value.length === 0) {
|
|
268
|
+
throw new Error(`session_bus ${field} is required for this action`);
|
|
269
|
+
}
|
|
270
|
+
return value;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function assertAbsent(value: string | undefined, field: string, action: string): void {
|
|
274
|
+
if (value !== undefined) throw new Error(`session_bus ${field} is not accepted for action ${action}`);
|
|
275
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { type FileHandle, open } from "node:fs/promises";
|
|
3
|
+
import { createConnection, type Server, type Socket } from "node:net";
|
|
4
|
+
import { TextDecoder } from "node:util";
|
|
5
|
+
import { JsonLineDecoder, MAX_FRAME_BYTES, type SignedSwarmFrame } from "./protocol.js";
|
|
6
|
+
|
|
7
|
+
export function requestFrame(
|
|
8
|
+
endpointPath: string,
|
|
9
|
+
frame: SignedSwarmFrame,
|
|
10
|
+
signal: AbortSignal | undefined,
|
|
11
|
+
timeoutMs: number,
|
|
12
|
+
): Promise<unknown> {
|
|
13
|
+
assertPositiveDuration(timeoutMs, "Pi Agent Swarm request timeout");
|
|
14
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
15
|
+
let settled = false;
|
|
16
|
+
let received = false;
|
|
17
|
+
const socket = createConnection(endpointPath);
|
|
18
|
+
const finish = (error?: Error, value?: unknown) => {
|
|
19
|
+
if (settled) return;
|
|
20
|
+
settled = true;
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
signal?.removeEventListener("abort", onAbort);
|
|
23
|
+
socket.destroy();
|
|
24
|
+
if (error) rejectPromise(error);
|
|
25
|
+
else resolvePromise(value);
|
|
26
|
+
};
|
|
27
|
+
const decoder = new JsonLineDecoder({
|
|
28
|
+
onValue: (value) => {
|
|
29
|
+
if (received) {
|
|
30
|
+
finish(new Error("Pi Agent Swarm peer returned multiple response frames"));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
received = true;
|
|
34
|
+
finish(undefined, value);
|
|
35
|
+
},
|
|
36
|
+
onError: (error) => finish(error),
|
|
37
|
+
});
|
|
38
|
+
const timer = setTimeout(
|
|
39
|
+
() => finish(new SwarmEndpointError("ETIMEDOUT", "Pi Agent Swarm request timed out")),
|
|
40
|
+
timeoutMs,
|
|
41
|
+
);
|
|
42
|
+
timer.unref();
|
|
43
|
+
const onAbort = () => finish(abortError("Pi Agent Swarm request aborted"));
|
|
44
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
45
|
+
socket.once("connect", () => {
|
|
46
|
+
void writeFrame(socket, frame).catch((error) =>
|
|
47
|
+
finish(error instanceof Error ? error : new Error(String(error))),
|
|
48
|
+
);
|
|
49
|
+
});
|
|
50
|
+
socket.on("data", (chunk) => decoder.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
|
|
51
|
+
socket.once("error", (error: NodeJS.ErrnoException) => {
|
|
52
|
+
finish(
|
|
53
|
+
new SwarmEndpointError(error.code ?? "EIO", `Pi Agent Swarm endpoint failed: ${error.code ?? "I/O error"}`),
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
socket.once("close", () => {
|
|
57
|
+
if (!settled) {
|
|
58
|
+
finish(new SwarmEndpointError("ECONNRESET", "Pi Agent Swarm endpoint closed without a response"));
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
if (signal?.aborted) onAbort();
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function writeFrame(socket: Socket, frame: SignedSwarmFrame): Promise<void> {
|
|
66
|
+
const data = Buffer.from(`${JSON.stringify(frame)}\n`, "utf8");
|
|
67
|
+
if (data.length > MAX_FRAME_BYTES) throw new Error("Pi Agent Swarm frame is too large");
|
|
68
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
69
|
+
socket.write(data, (error) => (error ? rejectPromise(error) : resolvePromise()));
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function listenSocketServer(server: Server, path: string, signal?: AbortSignal): Promise<void> {
|
|
74
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
75
|
+
let settled = false;
|
|
76
|
+
const finish = (error?: Error) => {
|
|
77
|
+
if (settled) return;
|
|
78
|
+
settled = true;
|
|
79
|
+
signal?.removeEventListener("abort", onAbort);
|
|
80
|
+
server.off("error", onError);
|
|
81
|
+
if (error) rejectPromise(error);
|
|
82
|
+
else resolvePromise();
|
|
83
|
+
};
|
|
84
|
+
const onError = (error: Error) => finish(error);
|
|
85
|
+
const onAbort = () => {
|
|
86
|
+
server.close();
|
|
87
|
+
finish(abortError("Pi Agent Swarm transport start aborted"));
|
|
88
|
+
};
|
|
89
|
+
server.once("error", onError);
|
|
90
|
+
server.listen(path, () => finish());
|
|
91
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
92
|
+
if (signal?.aborted) onAbort();
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function closeSocketServer(server: Server): Promise<void> {
|
|
97
|
+
return new Promise((resolvePromise) => {
|
|
98
|
+
try {
|
|
99
|
+
server.close(() => resolvePromise());
|
|
100
|
+
} catch {
|
|
101
|
+
resolvePromise();
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function readBoundedUtf8(path: string, maximum: number): Promise<string> {
|
|
107
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
108
|
+
try {
|
|
109
|
+
return await readBoundedHandleUtf8(handle, maximum);
|
|
110
|
+
} finally {
|
|
111
|
+
await handle.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function readBoundedHandleUtf8(handle: FileHandle, maximum: number): Promise<string> {
|
|
116
|
+
const buffer = Buffer.alloc(maximum + 1);
|
|
117
|
+
let offset = 0;
|
|
118
|
+
while (offset < buffer.length) {
|
|
119
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
120
|
+
if (bytesRead === 0) break;
|
|
121
|
+
offset += bytesRead;
|
|
122
|
+
}
|
|
123
|
+
if (offset > maximum) throw new Error("Pi Agent Swarm endpoint manifest is too large");
|
|
124
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export class SwarmEndpointError extends Error {
|
|
128
|
+
constructor(
|
|
129
|
+
readonly code: string,
|
|
130
|
+
message: string,
|
|
131
|
+
) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = "SwarmEndpointError";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function isDeadEndpointError(error: unknown): boolean {
|
|
138
|
+
return (
|
|
139
|
+
error instanceof SwarmEndpointError &&
|
|
140
|
+
(error.code === "ENOENT" ||
|
|
141
|
+
error.code === "ECONNREFUSED" ||
|
|
142
|
+
error.code === "ECONNRESET" ||
|
|
143
|
+
error.code === "ETIMEDOUT")
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function abortError(message: string): Error {
|
|
148
|
+
const error = new Error(message);
|
|
149
|
+
error.name = "AbortError";
|
|
150
|
+
return error;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function assertPositiveDuration(value: number, label: string): void {
|
|
154
|
+
if (!Number.isFinite(value) || value < 1) throw new Error(`${label} is invalid`);
|
|
155
|
+
}
|