@howaboua/pi-shepherdr 0.2.22 → 0.2.24

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +16 -18
  2. package/README.md +79 -58
  3. package/biome.json +1 -1
  4. package/index.ts +7 -3
  5. package/package.json +14 -9
  6. package/src/agents-discovery.ts +42 -27
  7. package/src/agents-focus.ts +2 -2
  8. package/src/agents-reply.ts +1 -1
  9. package/src/agents-spawn.ts +143 -137
  10. package/src/agents-tool.ts +3 -3
  11. package/src/agents-work.ts +33 -9
  12. package/src/attachment-notes.ts +14 -2
  13. package/src/attachment-protocol.ts +21 -4
  14. package/src/attachment-routing.ts +1 -1
  15. package/src/attachment-target.ts +5 -2
  16. package/src/attachment.ts +2 -3
  17. package/src/board/host.ts +2 -2
  18. package/src/board/membership.ts +1 -1
  19. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  20. package/src/{control-panel.ts → control-panel/index.ts} +4 -4
  21. package/src/{control-panel-items.ts → control-panel/items.ts} +3 -3
  22. package/src/{control-panel-view.ts → control-panel/view.ts} +3 -3
  23. package/src/controller.ts +6 -3
  24. package/src/fleet/index.ts +384 -0
  25. package/src/fleet/inspection.ts +141 -0
  26. package/src/fleet/machine.ts +52 -0
  27. package/src/fleet/monitor.ts +71 -0
  28. package/src/fleet/persistence.ts +42 -0
  29. package/src/fleet/reconnect.ts +75 -0
  30. package/src/fleet/setup.ts +92 -0
  31. package/src/launch.ts +14 -2
  32. package/src/messages/attachments.ts +39 -0
  33. package/src/messages/attribution.ts +75 -0
  34. package/src/messages/event-details.ts +69 -0
  35. package/src/messages/events.ts +189 -0
  36. package/src/messages/focus.ts +38 -0
  37. package/src/messages/guidance.ts +83 -0
  38. package/src/messages/render.ts +89 -0
  39. package/src/messages/voice-announcements.ts +79 -0
  40. package/src/monitor-extension-messages.ts +14 -1
  41. package/src/monitor.ts +4 -2
  42. package/src/peer-inbox.ts +2 -2
  43. package/src/profile-prompt.ts +32 -0
  44. package/src/profiles.ts +5 -25
  45. package/src/remote/client.ts +127 -0
  46. package/src/remote/context-relay.ts +84 -0
  47. package/src/remote/deployment.ts +179 -0
  48. package/src/remote/focus-channels.ts +89 -0
  49. package/src/remote/transport.ts +369 -0
  50. package/src/settlement/collector.ts +122 -0
  51. package/src/settlement/delivery.ts +144 -0
  52. package/src/{settlement.ts → settlement/index.ts} +23 -233
  53. package/src/shared-context-host.ts +33 -11
  54. package/src/shared-context.ts +10 -4
  55. package/src/spawn-context.ts +20 -17
  56. package/src/voice-handoff.ts +1 -1
  57. package/src/worker-role.ts +83 -0
  58. package/src/worker-service.ts +74 -89
  59. package/src/fleet.ts +0 -702
  60. package/src/messages.ts +0 -629
  61. package/src/remote-client.ts +0 -751
@@ -1,751 +0,0 @@
1
- import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import { readFile } from "node:fs/promises";
4
- import { fileURLToPath } from "node:url";
5
- import type { HerdrConnection } from "./herdr-client.js";
6
- import type { SshMachine } from "./machine-catalog.js";
7
- import { createBufferedChannel } from "./remote/shepherdr-channel.mjs";
8
- import { readPeerCommands } from "./remote/shepherdr-peer.mjs";
9
- import type { AssistantReader } from "./session-reader.js";
10
- import type {
11
- HerdrEvent,
12
- LatestAssistant,
13
- PaneInfo,
14
- PeerChannel,
15
- PeerDelivery,
16
- PeerMessage,
17
- SessionView,
18
- } from "./types.js";
19
-
20
- const BRIDGE_VERSION = 22;
21
- const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
22
- const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
23
- const REMOTE_CHANNEL_HELPER = "~/.pi/agent/shepherdr-channel.mjs";
24
- const REMOTE_SESSION_HELPER = "~/.pi/agent/shepherdr-session.mjs";
25
- const REMOTE_SESSION_WATCH_HELPER = "~/.pi/agent/shepherdr-session-watch.mjs";
26
- const REMOTE_CHECKPOINT_HELPER = "~/.pi/agent/shepherdr-checkpoints.mjs";
27
- const REMOTE_CONTEXT_HELPER = "~/.pi/agent/shepherdr-context.mjs";
28
- const MAX_FRAME_BYTES = 8 * 1024 * 1024;
29
- const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
30
- const DEPLOY_TIMEOUT_MS = 20_000;
31
- const READY_TIMEOUT_MS = 15_000;
32
-
33
- const DEPLOY_SOURCE = String.raw`
34
- const { randomUUID } = require("node:crypto");
35
- const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
36
- const { homedir } = require("node:os");
37
- const { dirname, join } = require("node:path");
38
- const targetValue = process.argv[1];
39
- const marker = "// @howaboua/pi-shepherdr managed bridge";
40
- const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
41
- const chunks = [];
42
- let size = 0;
43
- process.stdin.on("data", chunk => { size += chunk.length; if (size > 1024 * 1024) { process.stderr.write("bridge source is too large\n"); process.exit(1); } chunks.push(chunk); });
44
- process.stdin.on("end", () => { void (async () => {
45
- const source = Buffer.concat(chunks);
46
- let existing;
47
- try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
48
- if (existing) {
49
- if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
50
- if (!existing.toString("utf8", 0, marker.length + 32).startsWith(marker)) throw new Error(target + " is not owned by Shepherdr");
51
- }
52
- await mkdir(dirname(target), { recursive: true, mode: 0o700 });
53
- const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
54
- try {
55
- await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
56
- await rename(temporary, target);
57
- } catch (error) {
58
- await unlink(temporary).catch(() => undefined);
59
- throw error;
60
- }
61
- process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
62
- })().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
63
- `;
64
-
65
- interface PendingCall {
66
- reject: (error: Error) => void;
67
- resolve: (value: unknown) => void;
68
- timer: NodeJS.Timeout | undefined;
69
- cleanup?: () => void;
70
- }
71
-
72
- interface SubscriptionCallbacks {
73
- onDisconnect: (error?: Error) => void;
74
- onEvent: (event: HerdrEvent) => void;
75
- }
76
-
77
- interface BridgeError {
78
- code?: string;
79
- herdrResponse?: boolean;
80
- message: string;
81
- }
82
-
83
- function shellQuote(value: string): string {
84
- return `'${value.replaceAll("'", `'"'"'`)}'`;
85
- }
86
-
87
- function executablePath(path: string): string {
88
- return path.startsWith("~/")
89
- ? `"$HOME"/${shellQuote(path.slice(2))}`
90
- : shellQuote(path);
91
- }
92
-
93
- function remoteCommand(config: SshMachine): string {
94
- const args = [
95
- "exec",
96
- "node",
97
- executablePath(REMOTE_HELPER),
98
- "--session",
99
- shellQuote(config.session),
100
- ];
101
- return args.join(" ");
102
- }
103
-
104
- function spawnConnector(
105
- config: SshMachine,
106
- command: string,
107
- ): ChildProcessWithoutNullStreams {
108
- return spawn(
109
- "ssh",
110
- ["-T", "-o", "BatchMode=yes", "--", config.target, command],
111
- {
112
- stdio: ["pipe", "pipe", "pipe"],
113
- },
114
- );
115
- }
116
-
117
- function appendBounded(current: string, chunk: Buffer): string {
118
- const next = current + chunk.toString("utf8");
119
- return next.length <= MAX_DIAGNOSTIC_BYTES
120
- ? next
121
- : next.slice(next.length - MAX_DIAGNOSTIC_BYTES);
122
- }
123
-
124
- async function deploy(
125
- config: SshMachine,
126
- source: Buffer,
127
- target: string,
128
- ): Promise<void> {
129
- const command = [
130
- "node",
131
- "-e",
132
- shellQuote(DEPLOY_SOURCE),
133
- shellQuote(target),
134
- ].join(" ");
135
- const child = spawnConnector(config, command);
136
- let stdout = "";
137
- let stderr = "";
138
- child.stdout.on("data", (chunk: Buffer) => {
139
- stdout = appendBounded(stdout, chunk);
140
- });
141
- child.stderr.on("data", (chunk: Buffer) => {
142
- stderr = appendBounded(stderr, chunk);
143
- });
144
- child.stdin.end(source);
145
- await new Promise<void>((resolve, reject) => {
146
- const timer = setTimeout(() => {
147
- child.kill();
148
- reject(new Error("remote bridge deployment timed out"));
149
- }, DEPLOY_TIMEOUT_MS);
150
- timer.unref();
151
- child.on("error", (error) => {
152
- clearTimeout(timer);
153
- reject(error);
154
- });
155
- child.on("exit", (code) => {
156
- clearTimeout(timer);
157
- if (code === 0) resolve();
158
- else
159
- reject(
160
- new Error(
161
- stderr.trim() ||
162
- stdout.trim() ||
163
- `remote bridge deployment exited ${code ?? "without status"}`,
164
- ),
165
- );
166
- });
167
- });
168
- }
169
-
170
- export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
171
- private contextHandler:
172
- | ((request: unknown, signal: AbortSignal) => Promise<unknown>)
173
- | undefined;
174
- private readonly incomingContext = new Map<string, AbortController>();
175
- private relayPath: string | undefined;
176
- private readonly child: ChildProcessWithoutNullStreams;
177
- private closed = false;
178
- private diagnostics = "";
179
- private input = "";
180
- private readonly onClose: (error: Error) => void;
181
- private readonly pending = new Map<string, PendingCall>();
182
- private readonly subscriptions = new Map<string, SubscriptionCallbacks>();
183
- private readonly channels = new Map<
184
- string,
185
- ReturnType<typeof createBufferedChannel>
186
- >();
187
-
188
- private constructor(
189
- child: ChildProcessWithoutNullStreams,
190
- onClose: (error: Error) => void,
191
- ) {
192
- this.child = child;
193
- this.onClose = onClose;
194
- child.stdout.setEncoding("utf8");
195
- child.stdout.on("data", (chunk: string) => this.consume(chunk));
196
- child.stderr.on("data", (chunk: Buffer) => {
197
- this.diagnostics = appendBounded(this.diagnostics, chunk);
198
- });
199
- child.on("error", (error) => this.disconnected(error));
200
- child.on("exit", (code) => {
201
- this.disconnected(
202
- new Error(
203
- this.diagnostics.trim() ||
204
- `remote Shepherdr bridge exited ${code ?? "without status"}`,
205
- ),
206
- );
207
- });
208
- }
209
-
210
- static async connect(
211
- config: SshMachine,
212
- onClose: (error: Error) => void,
213
- ): Promise<RemoteHerdrClient> {
214
- const [
215
- source,
216
- peerSource,
217
- channelSource,
218
- sessionSource,
219
- contextSource,
220
- checkpointSource,
221
- sessionWatchSource,
222
- ] = await Promise.all([
223
- readFile(
224
- fileURLToPath(new URL("./remote/shepherdr.mjs", import.meta.url)),
225
- ),
226
- readFile(
227
- fileURLToPath(new URL("./remote/shepherdr-peer.mjs", import.meta.url)),
228
- ),
229
- readFile(
230
- fileURLToPath(
231
- new URL("./remote/shepherdr-channel.mjs", import.meta.url),
232
- ),
233
- ),
234
- readFile(
235
- fileURLToPath(
236
- new URL("./remote/shepherdr-session.mjs", import.meta.url),
237
- ),
238
- ),
239
- readFile(
240
- fileURLToPath(
241
- new URL("./remote/shepherdr-context.mjs", import.meta.url),
242
- ),
243
- ),
244
- readFile(
245
- fileURLToPath(
246
- new URL("./remote/shepherdr-checkpoints.mjs", import.meta.url),
247
- ),
248
- ),
249
- readFile(
250
- fileURLToPath(
251
- new URL("./remote/shepherdr-session-watch.mjs", import.meta.url),
252
- ),
253
- ),
254
- ]);
255
- await deploy(config, peerSource, REMOTE_PEER_HELPER);
256
- await deploy(config, channelSource, REMOTE_CHANNEL_HELPER);
257
- await deploy(config, sessionSource, REMOTE_SESSION_HELPER);
258
- await deploy(config, sessionWatchSource, REMOTE_SESSION_WATCH_HELPER);
259
- await deploy(config, checkpointSource, REMOTE_CHECKPOINT_HELPER);
260
- await deploy(config, contextSource, REMOTE_CONTEXT_HELPER);
261
- await deploy(config, source, REMOTE_HELPER);
262
- const child = spawnConnector(config, remoteCommand(config));
263
- const client = new RemoteHerdrClient(child, onClose);
264
- try {
265
- await client.ready();
266
- return client;
267
- } catch (error) {
268
- client.close();
269
- throw error;
270
- }
271
- }
272
-
273
- async request<T>(
274
- method: string,
275
- params: object = {},
276
- timeoutMs = 10_000,
277
- ): Promise<T> {
278
- return (await this.call(
279
- { op: "request", method, params, timeoutMs },
280
- timeoutMs + 1_000,
281
- )) as T;
282
- }
283
-
284
- async requestContext(
285
- path: string,
286
- request: unknown,
287
- signal?: AbortSignal,
288
- ): Promise<unknown> {
289
- signal?.throwIfAborted();
290
- return this.call({ op: "context", path, request }, 36_000, signal);
291
- }
292
-
293
- async startContextRelay(
294
- threadId: string,
295
- routeId: string,
296
- handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
297
- ): Promise<void> {
298
- this.contextHandler = handler;
299
- const path = await this.call({ op: "context_relay", threadId, routeId });
300
- if (typeof path !== "string")
301
- throw new Error("Invalid shared context relay path");
302
- this.relayPath = path;
303
- }
304
-
305
- contextRelayPath(): string {
306
- if (!this.relayPath)
307
- throw new Error(
308
- "Shared context relay is unavailable; open /herdr → Status to retry",
309
- );
310
- return this.relayPath;
311
- }
312
-
313
- async replyExtension(
314
- agent: PaneInfo,
315
- reply: import("./types.js").ExtensionReply,
316
- ): Promise<string> {
317
- const result = await this.call(
318
- { op: "extension-reply", agent, reply },
319
- 60_000,
320
- );
321
- if (typeof result !== "string")
322
- throw new Error(
323
- "Invalid extension reply receipt; inspect the target before retrying",
324
- );
325
- return result;
326
- }
327
-
328
- async commands(agent: PaneInfo): Promise<import("./types.js").PeerCommand[]> {
329
- const result = await this.call({ op: "commands", agent }, 26_000);
330
- return readPeerCommands(result);
331
- }
332
-
333
- async sendMessage(
334
- agent: PaneInfo,
335
- message: PeerMessage,
336
- ): Promise<PeerDelivery> {
337
- const result = await this.call(
338
- { op: "message", agent, message },
339
- message.text.trim() === "/quit" ? 0 : 26_000,
340
- );
341
- if (
342
- !result ||
343
- typeof result !== "object" ||
344
- !("command" in result) ||
345
- typeof result.command !== "boolean"
346
- )
347
- throw new Error(
348
- "Invalid peer acknowledgement; inspect the target before retrying",
349
- );
350
- return { command: result.command };
351
- }
352
-
353
- async machineIdentity(): Promise<import("./types.js").MachineIdentity> {
354
- const result = await this.call({ op: "identity" });
355
- if (
356
- !result ||
357
- typeof result !== "object" ||
358
- !("host" in result) ||
359
- typeof result.host !== "string" ||
360
- !("session" in result) ||
361
- typeof result.session !== "string"
362
- )
363
- throw new Error("Could not identify remote Herdr session");
364
- return { host: result.host, session: result.session };
365
- }
366
-
367
- async openFocusChannel(
368
- agent: PaneInfo,
369
- request: import("./types.js").FocusRequest,
370
- ): Promise<PeerChannel> {
371
- const id = randomUUID();
372
- const state = createBufferedChannel(
373
- (message) => {
374
- const frame = `${JSON.stringify({ op: "channel_send", id, message })}\n`;
375
- if (
376
- this.closed ||
377
- this.child.stdin.writableLength + Buffer.byteLength(frame) >
378
- 1024 * 1024
379
- )
380
- throw new Error(
381
- "Focus channel output is unavailable or exceeded its buffer",
382
- );
383
- this.child.stdin.write(frame);
384
- },
385
- () => {
386
- this.channels.delete(id);
387
- if (!this.closed)
388
- this.child.stdin.write(
389
- `${JSON.stringify({ op: "channel_close", id })}\n`,
390
- );
391
- },
392
- );
393
- this.channels.set(id, state);
394
- try {
395
- const result = await this.call(
396
- { op: "channel_open", id, agent, request },
397
- 60_000,
398
- );
399
- if (
400
- !result ||
401
- typeof result !== "object" ||
402
- !("admitted" in result) ||
403
- result.admitted !== true
404
- )
405
- throw new Error("Focus channel was not admitted");
406
- return state.channel;
407
- } catch (error) {
408
- state.fail(error instanceof Error ? error : new Error(String(error)));
409
- throw error;
410
- }
411
- }
412
-
413
- focus(
414
- agent: PaneInfo,
415
- request: import("./types.js").FocusRequest,
416
- ): Promise<unknown> {
417
- return this.call({ op: "focus", agent, request }, 60_000);
418
- }
419
-
420
- async subscribe(
421
- subscriptions: object[],
422
- onEvent: (event: HerdrEvent) => void,
423
- onDisconnect: (error?: Error) => void,
424
- signal?: AbortSignal,
425
- ): Promise<() => void> {
426
- return this.subscribeTo(
427
- { op: "subscribe", subscriptions },
428
- onEvent,
429
- onDisconnect,
430
- signal,
431
- );
432
- }
433
-
434
- async watch(
435
- paths: string[],
436
- onChange: (path: string) => void,
437
- onError: (error: Error) => void,
438
- signal: AbortSignal,
439
- ): Promise<() => void> {
440
- return this.subscribeTo(
441
- { op: "session_subscribe", paths },
442
- (event) => {
443
- if (typeof event.data["path"] === "string")
444
- onChange(event.data["path"]);
445
- },
446
- (error) => onError(error ?? new Error("Session activity stream closed")),
447
- signal,
448
- );
449
- }
450
-
451
- private async subscribeTo(
452
- request: Record<string, unknown>,
453
- onEvent: (event: HerdrEvent) => void,
454
- onDisconnect: (error?: Error) => void,
455
- signal?: AbortSignal,
456
- ): Promise<() => void> {
457
- signal?.throwIfAborted();
458
- const id = randomUUID();
459
- this.subscriptions.set(id, { onEvent, onDisconnect });
460
- const unsubscribe = () => {
461
- signal?.removeEventListener("abort", unsubscribe);
462
- if (!this.subscriptions.delete(id) || this.closed) return;
463
- void this.call({ op: "unsubscribe", subscription: id }).catch(
464
- () => undefined,
465
- );
466
- };
467
- try {
468
- const ready = this.call({ ...request, id }, 11_000);
469
- signal?.addEventListener("abort", unsubscribe, { once: true });
470
- if (signal?.aborted) unsubscribe();
471
- await ready;
472
- signal?.throwIfAborted();
473
- } catch (error) {
474
- unsubscribe();
475
- throw error;
476
- }
477
- return unsubscribe;
478
- }
479
-
480
- async latest(path?: string): Promise<LatestAssistant | undefined> {
481
- return (await this.view(path)).assistant;
482
- }
483
-
484
- async view(path?: string): Promise<SessionView> {
485
- return (await this.call({ op: "view", path })) as SessionView;
486
- }
487
-
488
- async keybindings(): Promise<Record<string, unknown>> {
489
- return (await this.call({ op: "keybindings" })) as Record<string, unknown>;
490
- }
491
-
492
- async directory(
493
- value: string | undefined,
494
- fallback: string,
495
- ): Promise<string> {
496
- return (await this.call({ op: "directory", value, fallback })) as string;
497
- }
498
-
499
- close(): void {
500
- if (this.closed) return;
501
- this.closed = true;
502
- this.child.kill();
503
- this.failPending(new Error("remote Shepherdr bridge closed"), false);
504
- }
505
-
506
- private ready(): Promise<void> {
507
- return new Promise((resolve, reject) => {
508
- const timer = setTimeout(() => {
509
- this.close();
510
- reject(new Error("remote Shepherdr bridge did not become ready"));
511
- }, READY_TIMEOUT_MS);
512
- timer.unref();
513
- this.pending.set("ready", {
514
- timer,
515
- resolve: (value) => {
516
- const ready = value as { version?: unknown };
517
- if (ready.version !== BRIDGE_VERSION) {
518
- reject(new Error("remote Shepherdr bridge version mismatch"));
519
- return;
520
- }
521
- resolve();
522
- },
523
- reject,
524
- });
525
- });
526
- }
527
-
528
- private call(
529
- message: Record<string, unknown>,
530
- timeoutMs = 10_000,
531
- signal?: AbortSignal,
532
- ): Promise<unknown> {
533
- signal?.throwIfAborted();
534
- if (this.closed)
535
- return Promise.reject(
536
- new Error("remote Shepherdr bridge is unavailable"),
537
- );
538
- const id = typeof message["id"] === "string" ? message["id"] : randomUUID();
539
- return new Promise((resolve, reject) => {
540
- const timer =
541
- timeoutMs === 0
542
- ? undefined
543
- : setTimeout(() => {
544
- const error = new Error(
545
- `remote Shepherdr ${String(message["op"])} timed out`,
546
- );
547
- if (message["op"] === "context_relay")
548
- this.rejectPending(id, error);
549
- else this.disconnected(error);
550
- }, timeoutMs);
551
- timer?.unref();
552
- const abort = () => {
553
- if (!this.pending.has(id)) return;
554
- this.rejectPending(
555
- id,
556
- new Error(
557
- "Shared context request cancelled; a write may have completed. Reread the note before retrying",
558
- ),
559
- );
560
- this.child.stdin.write(
561
- `${JSON.stringify({ op: "context_cancel", id })}\n`,
562
- );
563
- };
564
- this.pending.set(id, {
565
- resolve,
566
- reject,
567
- timer,
568
- cleanup: () => signal?.removeEventListener("abort", abort),
569
- });
570
- signal?.addEventListener("abort", abort, { once: true });
571
- this.child.stdin.write(
572
- `${JSON.stringify({ ...message, id })}\n`,
573
- (error) => {
574
- if (!error) return;
575
- this.rejectPending(id, error);
576
- },
577
- );
578
- });
579
- }
580
-
581
- private consume(chunk: string): void {
582
- this.input += chunk;
583
- if (Buffer.byteLength(this.input) > MAX_FRAME_BYTES) {
584
- this.disconnected(
585
- new Error("remote Shepherdr bridge frame is too large"),
586
- );
587
- return;
588
- }
589
- for (;;) {
590
- const newline = this.input.indexOf("\n");
591
- if (newline < 0) break;
592
- const line = this.input.slice(0, newline);
593
- this.input = this.input.slice(newline + 1);
594
- if (!line) continue;
595
- let value: Record<string, unknown>;
596
- try {
597
- value = JSON.parse(line) as Record<string, unknown>;
598
- } catch (error) {
599
- this.disconnected(
600
- new Error(
601
- `remote Shepherdr bridge returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
602
- ),
603
- );
604
- return;
605
- }
606
- if (value["type"] === "ready") {
607
- this.resolvePending("ready", value);
608
- continue;
609
- }
610
- if (value["type"] === "channel" && typeof value["channel"] === "string") {
611
- const state = this.channels.get(value["channel"]);
612
- if (value["closed"] === true)
613
- state?.fail(
614
- new Error(
615
- typeof value["error"] === "string"
616
- ? value["error"]
617
- : "Focus channel disconnected",
618
- ),
619
- );
620
- else if ("message" in value) state?.receive(value["message"]);
621
- else state?.fail(new Error("Invalid focus channel frame"));
622
- continue;
623
- }
624
- const subscription = value["subscription"];
625
- if (typeof subscription === "string") {
626
- const callbacks = this.subscriptions.get(subscription);
627
- const event = value["event"];
628
- if (callbacks && event && typeof event === "object") {
629
- try {
630
- callbacks.onEvent(event as HerdrEvent);
631
- } catch (error) {
632
- this.disconnected(
633
- new Error(
634
- `Shepherdr event handling failed: ${error instanceof Error ? error.message : String(error)}`,
635
- { cause: error },
636
- ),
637
- );
638
- return;
639
- }
640
- }
641
- continue;
642
- }
643
- const id = value["id"];
644
- if (typeof id !== "string") continue;
645
- if (value["type"] === "context_cancel") {
646
- this.incomingContext.get(id)?.abort();
647
- continue;
648
- }
649
- if (value["type"] === "context_request") {
650
- const controller = new AbortController();
651
- this.incomingContext.set(id, controller);
652
- const reply = (data: object) => {
653
- if (this.closed || controller.signal.aborted) return;
654
- let frame = `${JSON.stringify({ op: "context_reply", id, ...data })}\n`;
655
- if (Buffer.byteLength(frame) > MAX_FRAME_BYTES)
656
- frame = `${JSON.stringify({ op: "context_reply", id, ok: false, error: "Shared context response is too large" })}\n`;
657
- this.child.stdin.write(frame);
658
- };
659
- void Promise.resolve()
660
- .then(() => {
661
- if (!this.contextHandler)
662
- throw new Error("Shared context controller is unavailable");
663
- controller.signal.throwIfAborted();
664
- return this.contextHandler(value["request"], controller.signal);
665
- })
666
- .then(
667
- (result) => reply({ ok: true, result }),
668
- (error: unknown) =>
669
- reply({
670
- ok: false,
671
- error: error instanceof Error ? error.message : String(error),
672
- }),
673
- )
674
- .finally(() => {
675
- this.incomingContext.delete(id);
676
- });
677
- continue;
678
- }
679
- if (value["ok"] === true) this.resolvePending(id, value["result"]);
680
- else {
681
- const detail = value["error"] as BridgeError | undefined;
682
- const error = new Error(
683
- detail?.message ?? "remote Shepherdr bridge request failed",
684
- ) as Error & {
685
- code?: string;
686
- herdrResponse?: true;
687
- };
688
- if (detail?.code) error.code = detail.code;
689
- if (detail?.herdrResponse) error.herdrResponse = true;
690
- this.rejectPending(id, error);
691
- }
692
- }
693
- }
694
-
695
- private resolvePending(id: string, value: unknown): void {
696
- const pending = this.pending.get(id);
697
- if (!pending) return;
698
- this.pending.delete(id);
699
- clearTimeout(pending.timer);
700
- pending.cleanup?.();
701
- pending.resolve(value);
702
- }
703
-
704
- private rejectPending(id: string, error: Error): void {
705
- const pending = this.pending.get(id);
706
- if (!pending) return;
707
- this.pending.delete(id);
708
- clearTimeout(pending.timer);
709
- pending.cleanup?.();
710
- pending.reject(error);
711
- }
712
-
713
- private disconnected(error: Error): void {
714
- if (this.closed) return;
715
- this.closed = true;
716
- this.child.kill();
717
- this.failPending(error, true);
718
- }
719
-
720
- private failPending(error: Error, notify: boolean): void {
721
- for (const state of this.channels.values()) state.fail(error);
722
- this.channels.clear();
723
- for (const controller of this.incomingContext.values()) controller.abort();
724
- this.incomingContext.clear();
725
- for (const pending of this.pending.values()) {
726
- clearTimeout(pending.timer);
727
- pending.cleanup?.();
728
- pending.reject(error);
729
- }
730
- this.pending.clear();
731
- let callbackFailure: unknown;
732
- for (const callbacks of this.subscriptions.values()) {
733
- try {
734
- callbacks.onDisconnect(error);
735
- } catch (failure) {
736
- callbackFailure ??= failure;
737
- }
738
- }
739
- this.subscriptions.clear();
740
- if (notify) {
741
- this.onClose(
742
- callbackFailure === undefined
743
- ? error
744
- : new Error(
745
- `${error.message}; disconnect handler failed: ${callbackFailure instanceof Error ? callbackFailure.message : String(callbackFailure)}`,
746
- { cause: callbackFailure },
747
- ),
748
- );
749
- }
750
- }
751
- }