@howaboua/pi-shepherdr 0.1.1 → 0.1.3

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.
@@ -0,0 +1,520 @@
1
+ // @howaboua/pi-shepherdr managed bridge
2
+ import { open, readFile, stat } from "node:fs/promises";
3
+ import { createConnection } from "node:net";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+
7
+ const BRIDGE_VERSION = 3;
8
+ const MAX_FRAME_BYTES = 8 * 1024 * 1024;
9
+ const READ_CHUNK_BYTES = 64 * 1024;
10
+ const subscriptions = new Map();
11
+ const sessionCache = new Map();
12
+
13
+ function argument(name) {
14
+ const index = process.argv.indexOf(`--${name}`);
15
+ return index >= 0 ? process.argv[index + 1] : undefined;
16
+ }
17
+
18
+ function expandHome(path) {
19
+ return path === "~"
20
+ ? homedir()
21
+ : path.startsWith("~/")
22
+ ? join(homedir(), path.slice(2))
23
+ : path;
24
+ }
25
+
26
+ function socketPath() {
27
+ const explicit = argument("socket");
28
+ if (explicit) return expandHome(explicit);
29
+ const root = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
30
+ const session = argument("session");
31
+ return session
32
+ ? join(root, "herdr", "sessions", session, "herdr.sock")
33
+ : join(root, "herdr", "herdr.sock");
34
+ }
35
+
36
+ function send(value) {
37
+ const frame = `${JSON.stringify(value)}\n`;
38
+ if (Buffer.byteLength(frame) > MAX_FRAME_BYTES) {
39
+ throw new Error("Shepherdr bridge response is too large");
40
+ }
41
+ process.stdout.write(frame);
42
+ }
43
+
44
+ function responseError(value) {
45
+ if (value && typeof value === "object" && typeof value.message === "string") {
46
+ return {
47
+ message: value.message,
48
+ ...(typeof value.code === "string" ? { code: value.code } : {}),
49
+ herdrResponse: true,
50
+ };
51
+ }
52
+ return {
53
+ message: `Herdr request failed: ${JSON.stringify(value)}`,
54
+ herdrResponse: true,
55
+ };
56
+ }
57
+
58
+ function errorFromResponse(value) {
59
+ const detail = responseError(value);
60
+ return Object.assign(new Error(detail.message), detail);
61
+ }
62
+
63
+ function openHerdr(label, message, onValue, onDisconnect) {
64
+ let buffer = "";
65
+ let disconnected = false;
66
+ const socket = createConnection(socketPath());
67
+ const disconnect = (error) => {
68
+ if (disconnected) return;
69
+ disconnected = true;
70
+ onDisconnect(error ?? new Error(`${label} disconnected`));
71
+ };
72
+ socket.setEncoding("utf8");
73
+ socket.on("connect", () => socket.write(`${JSON.stringify(message)}\n`));
74
+ socket.on("error", disconnect);
75
+ socket.on("end", () => disconnect());
76
+ socket.on("close", () => disconnect());
77
+ socket.on("data", (chunk) => {
78
+ buffer += chunk;
79
+ if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
80
+ disconnect(new Error(`${label} frame is too large`));
81
+ socket.destroy();
82
+ return;
83
+ }
84
+ for (;;) {
85
+ const newline = buffer.indexOf("\n");
86
+ if (newline < 0) break;
87
+ const line = buffer.slice(0, newline);
88
+ buffer = buffer.slice(newline + 1);
89
+ if (!line) continue;
90
+ let value;
91
+ try {
92
+ value = JSON.parse(line);
93
+ } catch (error) {
94
+ disconnect(
95
+ new Error(`${label} returned invalid JSON: ${error.message}`),
96
+ );
97
+ socket.destroy();
98
+ return;
99
+ }
100
+ onValue(value);
101
+ }
102
+ });
103
+ return socket;
104
+ }
105
+
106
+ function request(method, params = {}, timeoutMs = 10_000) {
107
+ return new Promise((resolveRequest, reject) => {
108
+ const id = `pi-shepherdr-bridge:${crypto.randomUUID()}`;
109
+ let settled = false;
110
+ let socket;
111
+ const timer = setTimeout(
112
+ () => finish(new Error(`Herdr ${method} timed out`)),
113
+ timeoutMs,
114
+ );
115
+ timer.unref();
116
+ const finish = (error, result) => {
117
+ if (settled) return;
118
+ settled = true;
119
+ clearTimeout(timer);
120
+ socket.destroy();
121
+ if (error) reject(error);
122
+ else resolveRequest(result);
123
+ };
124
+ socket = openHerdr(
125
+ `Herdr ${method}`,
126
+ { id, method, params },
127
+ (response) => {
128
+ if (response.id !== id)
129
+ finish(
130
+ new Error(`Herdr ${method} returned a mismatched response ID`),
131
+ );
132
+ else if (response.error !== undefined)
133
+ finish(errorFromResponse(response.error));
134
+ else if (response.result !== undefined)
135
+ finish(undefined, response.result);
136
+ else finish(new Error(`Herdr ${method} returned no result`));
137
+ },
138
+ (error) => finish(error),
139
+ );
140
+ });
141
+ }
142
+
143
+ function subscribe(id, requested) {
144
+ return new Promise((resolveSubscription, reject) => {
145
+ const requestId = `pi-shepherdr-bridge:subscribe:${crypto.randomUUID()}`;
146
+ let acknowledged = false;
147
+ let closed = false;
148
+ let socket;
149
+ const timer = setTimeout(() => {
150
+ socket.destroy();
151
+ reject(new Error("Herdr events.subscribe timed out"));
152
+ }, 10_000);
153
+ timer.unref();
154
+ const disconnected = (error) => {
155
+ clearTimeout(timer);
156
+ if (!acknowledged)
157
+ reject(error ?? new Error("Herdr subscription disconnected"));
158
+ else if (!closed) {
159
+ process.stderr.write(
160
+ `Herdr monitoring disconnected${error ? `: ${error.message}` : ""}\n`,
161
+ );
162
+ process.exitCode = 1;
163
+ setTimeout(() => process.exit(), 0);
164
+ }
165
+ };
166
+ socket = openHerdr(
167
+ "Herdr events.subscribe",
168
+ {
169
+ id: requestId,
170
+ method: "events.subscribe",
171
+ params: { subscriptions: requested },
172
+ },
173
+ (value) => {
174
+ if (!acknowledged && value.id === requestId) {
175
+ if (value.error !== undefined) {
176
+ disconnected(errorFromResponse(value.error));
177
+ socket.destroy();
178
+ return;
179
+ }
180
+ if (value.result?.type !== "subscription_started") {
181
+ disconnected(
182
+ new Error(
183
+ "Herdr events.subscribe returned an invalid acknowledgement",
184
+ ),
185
+ );
186
+ socket.destroy();
187
+ return;
188
+ }
189
+ acknowledged = true;
190
+ clearTimeout(timer);
191
+ subscriptions.set(id, () => {
192
+ closed = true;
193
+ socket.destroy();
194
+ });
195
+ resolveSubscription();
196
+ return;
197
+ }
198
+ if (
199
+ acknowledged &&
200
+ typeof value.event === "string" &&
201
+ value.data &&
202
+ typeof value.data === "object"
203
+ ) {
204
+ send({
205
+ subscription: id,
206
+ event: { event: value.event, data: value.data },
207
+ });
208
+ }
209
+ },
210
+ disconnected,
211
+ );
212
+ });
213
+ }
214
+
215
+ function assistantFromMessage(id, message) {
216
+ if (message.role !== "assistant") return undefined;
217
+ const text = [];
218
+ if (typeof message.content === "string") text.push(message.content);
219
+ else if (Array.isArray(message.content)) {
220
+ for (const part of message.content) {
221
+ if (
222
+ part &&
223
+ typeof part === "object" &&
224
+ part.type === "text" &&
225
+ typeof part.text === "string"
226
+ )
227
+ text.push(part.text);
228
+ }
229
+ }
230
+ const joined = text.join("");
231
+ const stopReason =
232
+ typeof message.stopReason === "string" ? message.stopReason : undefined;
233
+ if (!joined && stopReason !== "error") return undefined;
234
+ return {
235
+ id,
236
+ text: joined,
237
+ ...(stopReason ? { stopReason } : {}),
238
+ };
239
+ }
240
+
241
+ function userFromMessage(id, message) {
242
+ if (message.role !== "user") return undefined;
243
+ const text = [];
244
+ if (typeof message.content === "string") text.push(message.content);
245
+ else if (Array.isArray(message.content)) {
246
+ for (const part of message.content) {
247
+ if (
248
+ part &&
249
+ typeof part === "object" &&
250
+ part.type === "text" &&
251
+ typeof part.text === "string"
252
+ )
253
+ text.push(part.text);
254
+ }
255
+ }
256
+ const joined = text.join("");
257
+ return joined ? { id, text: joined } : undefined;
258
+ }
259
+
260
+ function askChoice(value) {
261
+ if (!value || typeof value !== "object" || typeof value.label !== "string")
262
+ return undefined;
263
+ return {
264
+ label: value.label,
265
+ ...(typeof value.description === "string"
266
+ ? { description: value.description }
267
+ : {}),
268
+ };
269
+ }
270
+
271
+ function askPrompt(value) {
272
+ if (!value || typeof value !== "object" || typeof value.title !== "string")
273
+ return undefined;
274
+ return {
275
+ title: value.title,
276
+ multiple: value.multiple === true,
277
+ choices: (Array.isArray(value.choices) ? value.choices : [])
278
+ .map(askChoice)
279
+ .filter(Boolean),
280
+ ...(typeof value.body === "string" ? { body: value.body } : {}),
281
+ };
282
+ }
283
+
284
+ function askCall(value) {
285
+ if (
286
+ !value ||
287
+ typeof value !== "object" ||
288
+ value.type !== "toolCall" ||
289
+ value.name !== "ask" ||
290
+ typeof value.id !== "string" ||
291
+ !value.arguments ||
292
+ typeof value.arguments !== "object"
293
+ )
294
+ return undefined;
295
+ const prompts = (
296
+ Array.isArray(value.arguments.prompts) ? value.arguments.prompts : []
297
+ )
298
+ .map(askPrompt)
299
+ .filter(Boolean);
300
+ if (prompts.length === 0) return undefined;
301
+ return {
302
+ toolCallId: value.id,
303
+ handoff: value.arguments.handoff === true,
304
+ prompts,
305
+ };
306
+ }
307
+
308
+ async function sessionView(path, size) {
309
+ const file = await open(path, "r");
310
+ let targetId;
311
+ let assistant;
312
+ let assistantDepth;
313
+ let ask;
314
+ let depth = 0;
315
+ let user;
316
+ let userDepth;
317
+ const resolved = new Set();
318
+ const result = () => ({
319
+ ...(assistant ? { assistant } : {}),
320
+ ...(ask ? { ask } : {}),
321
+ ...(user ? { user } : {}),
322
+ ...(assistantDepth !== undefined && userDepth !== undefined
323
+ ? { assistantAfterUser: assistantDepth < userDepth }
324
+ : {}),
325
+ });
326
+ const inspect = (line) => {
327
+ if (line.length === 0) return false;
328
+ let entry;
329
+ try {
330
+ entry = JSON.parse(line.toString("utf8"));
331
+ } catch {
332
+ return false;
333
+ }
334
+ if (typeof entry.id !== "string") return false;
335
+ targetId ??= entry.id;
336
+ if (entry.id !== targetId) return false;
337
+ const currentDepth = depth;
338
+ depth += 1;
339
+ const message = entry.message;
340
+ if (message && typeof message === "object") {
341
+ if (
342
+ (message.role === "toolResult" || message.role === "tool") &&
343
+ typeof (message.toolCallId ?? message.tool_call_id) === "string"
344
+ )
345
+ resolved.add(message.toolCallId ?? message.tool_call_id);
346
+ if (!assistant) {
347
+ assistant = assistantFromMessage(entry.id, message);
348
+ if (assistant) assistantDepth = currentDepth;
349
+ }
350
+ if (!user) {
351
+ user = userFromMessage(entry.id, message);
352
+ if (user) userDepth = currentDepth;
353
+ }
354
+ if (
355
+ !ask &&
356
+ message.role === "assistant" &&
357
+ Array.isArray(message.content)
358
+ )
359
+ ask = [...message.content]
360
+ .reverse()
361
+ .map(askCall)
362
+ .find(
363
+ (candidate) => candidate && !resolved.has(candidate.toolCallId),
364
+ );
365
+ }
366
+ if (typeof entry.parentId !== "string") return true;
367
+ targetId = entry.parentId;
368
+ return false;
369
+ };
370
+
371
+ try {
372
+ let position = size;
373
+ let partial = Buffer.alloc(0);
374
+ while (position > 0) {
375
+ const length = Math.min(READ_CHUNK_BYTES, position);
376
+ position -= length;
377
+ const chunk = Buffer.allocUnsafe(length);
378
+ const { bytesRead } = await file.read(chunk, 0, length, position);
379
+ const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
380
+ let lineEnd = data.length;
381
+ for (let index = data.length - 1; index >= 0; index -= 1) {
382
+ if (data[index] !== 0x0a) continue;
383
+ if (inspect(data.subarray(index + 1, lineEnd))) return result();
384
+ lineEnd = index;
385
+ }
386
+ partial = data.subarray(0, lineEnd);
387
+ }
388
+ inspect(partial);
389
+ return result();
390
+ } finally {
391
+ await file.close();
392
+ }
393
+ }
394
+
395
+ async function view(path) {
396
+ if (!path) return {};
397
+ const expanded = expandHome(path);
398
+ let metadata;
399
+ try {
400
+ metadata = await stat(expanded);
401
+ } catch (error) {
402
+ if (error.code === "ENOENT") return {};
403
+ throw error;
404
+ }
405
+ const cached = sessionCache.get(expanded);
406
+ if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs)
407
+ return cached.result;
408
+ const result = await sessionView(expanded, metadata.size);
409
+ sessionCache.set(expanded, {
410
+ size: metadata.size,
411
+ mtimeMs: metadata.mtimeMs,
412
+ result,
413
+ });
414
+ return result;
415
+ }
416
+
417
+ async function directory(value, fallback) {
418
+ const base = expandHome(fallback?.trim() || homedir());
419
+ const path = resolve(base, expandHome(value?.trim() || "."));
420
+ const metadata = await stat(path).catch((error) => {
421
+ throw new Error(
422
+ `cannot use working directory ${JSON.stringify(path)}: ${error.message}`,
423
+ );
424
+ });
425
+ if (!metadata.isDirectory())
426
+ throw new Error(`${JSON.stringify(path)} is not a directory`);
427
+ return path;
428
+ }
429
+
430
+ async function keybindings() {
431
+ const directory =
432
+ process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
433
+ try {
434
+ const value = JSON.parse(
435
+ await readFile(join(directory, "keybindings.json"), "utf8"),
436
+ );
437
+ return value && typeof value === "object" ? value : {};
438
+ } catch {
439
+ return {};
440
+ }
441
+ }
442
+
443
+ function serializableError(error) {
444
+ return {
445
+ message: error instanceof Error ? error.message : String(error),
446
+ ...(typeof error?.code === "string" ? { code: error.code } : {}),
447
+ ...(error?.herdrResponse === true ? { herdrResponse: true } : {}),
448
+ };
449
+ }
450
+
451
+ async function handle(message) {
452
+ if (
453
+ !message ||
454
+ typeof message !== "object" ||
455
+ typeof message.id !== "string" ||
456
+ typeof message.op !== "string"
457
+ ) {
458
+ throw new Error("invalid Shepherdr bridge request");
459
+ }
460
+ if (message.op === "request") {
461
+ return request(message.method, message.params ?? {}, message.timeoutMs);
462
+ }
463
+ if (message.op === "subscribe") {
464
+ await subscribe(message.id, message.subscriptions ?? []);
465
+ return { subscribed: true };
466
+ }
467
+ if (message.op === "unsubscribe") {
468
+ subscriptions.get(message.subscription)?.();
469
+ subscriptions.delete(message.subscription);
470
+ return { unsubscribed: true };
471
+ }
472
+ if (message.op === "view") return view(message.path);
473
+ if (message.op === "keybindings") return keybindings();
474
+ if (message.op === "directory")
475
+ return directory(message.value, message.fallback);
476
+ throw new Error(`unsupported Shepherdr bridge operation ${message.op}`);
477
+ }
478
+
479
+ let input = "";
480
+ process.stdin.setEncoding("utf8");
481
+ process.stdin.on("data", (chunk) => {
482
+ input += chunk;
483
+ if (Buffer.byteLength(input) > MAX_FRAME_BYTES) {
484
+ process.stderr.write("Shepherdr bridge request is too large\n");
485
+ process.exit(1);
486
+ }
487
+ for (;;) {
488
+ const newline = input.indexOf("\n");
489
+ if (newline < 0) break;
490
+ const line = input.slice(0, newline);
491
+ input = input.slice(newline + 1);
492
+ if (!line) continue;
493
+ let message;
494
+ try {
495
+ message = JSON.parse(line);
496
+ } catch (error) {
497
+ send({ id: "invalid", ok: false, error: serializableError(error) });
498
+ continue;
499
+ }
500
+ void handle(message).then(
501
+ (result) => send({ id: message.id, ok: true, result }),
502
+ (error) =>
503
+ send({ id: message.id, ok: false, error: serializableError(error) }),
504
+ );
505
+ }
506
+ });
507
+
508
+ process.stdin.on("end", () => process.exit());
509
+ for (const signal of ["SIGINT", "SIGTERM"]) {
510
+ process.on(signal, () => {
511
+ for (const close of subscriptions.values()) close();
512
+ process.exit();
513
+ });
514
+ }
515
+
516
+ send({
517
+ type: "ready",
518
+ version: BRIDGE_VERSION,
519
+ socket: socketPath(),
520
+ });