pi-cowboy 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,240 +0,0 @@
1
- /**
2
- * subagent/socket-ipc.ts — local IPC transport: newline-delimited JSON over node:net.
3
- *
4
- * One address per channel (a Unix domain socket under os.tmpdir() on POSIX, a
5
- * named pipe on Windows), one server, any number of clients. A frame is one JSON
6
- * object on one line; the reader tolerates split chunks, CRLF endings, and blank
7
- * lines, and never throws on a malformed peer. The message payload is the
8
- * caller's contract — the transport only requires a JSON object.
9
- */
10
- import { createHash } from "node:crypto";
11
- import { unlinkSync } from "node:fs";
12
- import { connect, createServer } from "node:net";
13
- import { tmpdir } from "node:os";
14
- import { join } from "node:path";
15
- /**
16
- * Longest frame body tolerated without a newline. A peer that sends more has that
17
- * frame dropped — a truncated giant frame must not be mistaken for a message.
18
- */
19
- export const MAX_FRAME_CHARS = 1_048_576;
20
- /** Longest sanitized id carried in an address, keeping the POSIX path inside sun_path's 104-byte limit. */
21
- const MAX_ADDRESS_ID_CHARS = 32;
22
- /** Characters an agent id keeps in an address; every other character becomes "_". */
23
- const UNSAFE_ADDRESS_CHARS = /[^A-Za-z0-9._-]/g;
24
- /** One character an address can carry; an id with none has no address to be distinct in. */
25
- const SAFE_ADDRESS_CHAR = /[A-Za-z0-9._-]/;
26
- /** A named pipe is not a filesystem entry, so nothing may be unlinked for one. */
27
- const NAMED_PIPE_PREFIX = "\\\\.\\pipe\\";
28
- /**
29
- * The address a local IPC channel for `agentId` listens on. `platform` is a
30
- * parameter so the Windows and POSIX shapes are both testable from one host.
31
- */
32
- export function getIpcAddress(agentId, platform = process.platform) {
33
- const safe = sanitizeAddressId(agentId);
34
- return platform === "win32"
35
- ? `${NAMED_PIPE_PREFIX}cowboy-${safe}`
36
- : join(tmpdir(), `cowboy-ipc-${safe}.sock`);
37
- }
38
- /**
39
- * Build a decoder for one byte stream. `onMessage` sees every complete frame in
40
- * order; `onError` sees each dropped frame (malformed JSON, non-object JSON,
41
- * oversized). Without `onError` those frames are dropped silently.
42
- */
43
- export function createNdjsonDecoder(onMessage, onError) {
44
- let buffer = "";
45
- // Once a frame is dropped for size, everything up to its terminating newline is
46
- // that frame's tail; without this, the tail would be read as the next frame.
47
- let discardingOversized = false;
48
- return {
49
- push(chunk) {
50
- buffer += chunk;
51
- let newline = buffer.indexOf("\n");
52
- while (newline !== -1) {
53
- const line = buffer.slice(0, newline).trim();
54
- buffer = buffer.slice(newline + 1);
55
- newline = buffer.indexOf("\n");
56
- if (discardingOversized) {
57
- discardingOversized = false;
58
- continue;
59
- }
60
- if (line)
61
- parseFrame(line, onMessage, onError);
62
- }
63
- if (discardingOversized) {
64
- // Only the next newline matters; the retained tail is discarded frames.
65
- buffer = "";
66
- }
67
- else if (buffer.length > MAX_FRAME_CHARS) {
68
- onError?.(new Error(`ipc: dropping a ${buffer.length}-char frame with no newline within ${MAX_FRAME_CHARS} chars`));
69
- buffer = "";
70
- discardingOversized = true;
71
- }
72
- },
73
- };
74
- }
75
- /**
76
- * Listen on `address`. Resolves once the socket is bound, and rejects if the bind
77
- * fails — including EADDRINUSE from a live peer, since a leftover socket file is
78
- * removed before binding but a live listener is not something this can detect.
79
- */
80
- export async function createIpcServer(address, options) {
81
- const report = (error) => options.onError?.(error);
82
- const server = createServer();
83
- const connections = new Map();
84
- let nextConnectionId = 1;
85
- let closed = false;
86
- discardSocketFile(address, report);
87
- server.on("connection", (socket) => {
88
- const connectionId = `c${nextConnectionId++}`;
89
- connections.set(connectionId, socket);
90
- socket.setEncoding("utf8");
91
- const decoder = createNdjsonDecoder(options.onMessage, report);
92
- // setEncoding makes this a string at runtime; toString() is the no-op the Buffer typing asks for.
93
- socket.on("data", (chunk) => decoder.push(chunk.toString()));
94
- socket.on("error", report);
95
- socket.on("close", () => {
96
- connections.delete(connectionId);
97
- options.onDisconnect?.(connectionId);
98
- });
99
- options.onConnect?.(connectionId);
100
- });
101
- await new Promise((resolve, reject) => {
102
- const onBindError = (error) => reject(error);
103
- server.once("error", onBindError);
104
- server.listen(address, () => {
105
- server.off("error", onBindError);
106
- server.on("error", report);
107
- resolve();
108
- });
109
- });
110
- return {
111
- address,
112
- broadcast(message) {
113
- if (closed)
114
- throw new Error("ipc: server is closed");
115
- const line = `${JSON.stringify(message)}\n`;
116
- for (const socket of connections.values())
117
- socket.write(line);
118
- },
119
- send(connectionId, message) {
120
- if (closed)
121
- throw new Error("ipc: server is closed");
122
- const socket = connections.get(connectionId);
123
- if (!socket)
124
- throw new Error(`ipc: unknown connection ${connectionId}`);
125
- socket.write(`${JSON.stringify(message)}\n`);
126
- },
127
- async close() {
128
- if (closed)
129
- return;
130
- closed = true;
131
- for (const socket of connections.values())
132
- socket.destroy();
133
- connections.clear();
134
- await new Promise((resolve) => {
135
- server.close(() => resolve());
136
- });
137
- discardSocketFile(address, report);
138
- },
139
- };
140
- }
141
- /**
142
- * Connect to `address`. Resolves once connected, and rejects if the connection
143
- * fails (a missing listener is the common case). A socket "error" never goes
144
- * unhandled: before the connect settles it rejects this promise, after that it
145
- * goes to `onError`.
146
- */
147
- export async function createIpcClient(address, options = {}) {
148
- const socket = connect(address);
149
- let disconnected = false;
150
- let rejectConnect = null;
151
- socket.setEncoding("utf8");
152
- socket.on("error", (error) => {
153
- if (rejectConnect)
154
- rejectConnect(error);
155
- else
156
- options.onError?.(error);
157
- });
158
- const { onMessage } = options;
159
- if (onMessage) {
160
- const decoder = createNdjsonDecoder(onMessage, options.onError);
161
- socket.on("data", (chunk) => decoder.push(chunk.toString()));
162
- }
163
- await new Promise((resolve, reject) => {
164
- rejectConnect = (error) => reject(error);
165
- socket.once("connect", () => {
166
- rejectConnect = null;
167
- resolve();
168
- });
169
- });
170
- return {
171
- address,
172
- send(message) {
173
- if (disconnected)
174
- throw new Error("ipc: client is disconnected");
175
- socket.write(`${JSON.stringify(message)}\n`);
176
- },
177
- async disconnect() {
178
- if (disconnected)
179
- return;
180
- disconnected = true;
181
- await new Promise((resolve) => {
182
- if (socket.destroyed || socket.readyState === "closed") {
183
- resolve();
184
- return;
185
- }
186
- // Flush what is queued, then destroy: the peer's FIN is not what ends
187
- // this socket, and an inbound stream nobody reads (a send-only client)
188
- // would keep "close" back forever while we waited for it.
189
- socket.once("close", () => resolve());
190
- socket.end(() => socket.destroy());
191
- });
192
- },
193
- };
194
- }
195
- /** Compact an agent id into address characters, hashing what truncation would otherwise merge. */
196
- function sanitizeAddressId(agentId) {
197
- if (!SAFE_ADDRESS_CHAR.test(agentId)) {
198
- throw new Error("getIpcAddress requires an agent id with at least one [A-Za-z0-9._-] character");
199
- }
200
- const safe = agentId.replace(UNSAFE_ADDRESS_CHARS, "_");
201
- if (safe.length <= MAX_ADDRESS_ID_CHARS)
202
- return safe;
203
- const digest = createHash("sha256").update(agentId).digest("hex");
204
- // "-" + 8 hex chars fills the cap, so two long ids sharing a prefix stay distinct.
205
- return `${safe.slice(0, MAX_ADDRESS_ID_CHARS - 9)}-${digest.slice(0, 8)}`;
206
- }
207
- function isNamedPipeAddress(address) {
208
- return address.startsWith(NAMED_PIPE_PREFIX);
209
- }
210
- /** Best-effort removal of a stale POSIX socket file; failures are reported, never thrown. */
211
- function discardSocketFile(address, report) {
212
- if (isNamedPipeAddress(address))
213
- return;
214
- try {
215
- unlinkSync(address);
216
- }
217
- catch (error) {
218
- const code = error.code;
219
- if (code !== "ENOENT")
220
- report(error);
221
- }
222
- }
223
- function parseFrame(line, onMessage, onError) {
224
- let parsed;
225
- try {
226
- parsed = JSON.parse(line);
227
- }
228
- catch {
229
- onError?.(new Error(`ipc: dropping an unparsable ${line.length}-char frame`));
230
- return;
231
- }
232
- if (!isIpcMessage(parsed)) {
233
- onError?.(new Error(`ipc: dropping a non-object ${line.length}-char frame`));
234
- return;
235
- }
236
- onMessage(parsed);
237
- }
238
- function isIpcMessage(value) {
239
- return typeof value === "object" && value !== null && !Array.isArray(value);
240
- }