@howaboua/pi-shepherdr 0.2.27 → 0.2.28-core.12.1.gda85fa2e8a0f

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 (112) hide show
  1. package/README.md +48 -48
  2. package/index.ts +7 -1
  3. package/package.json +2 -9
  4. package/src/agent-identity.ts +3 -3
  5. package/src/agents-contract.ts +10 -14
  6. package/src/agents-discovery.ts +34 -54
  7. package/src/agents-focus.ts +23 -35
  8. package/src/agents-spawn.ts +24 -23
  9. package/src/agents-tool.ts +4 -19
  10. package/src/agents-work.ts +4 -3
  11. package/src/attachment-notes.ts +8 -7
  12. package/src/attachment-protocol.ts +3 -2
  13. package/src/attachment-routing.ts +1 -1
  14. package/src/attachment-target.ts +10 -18
  15. package/src/attachment.ts +14 -9
  16. package/src/board/discovery.ts +67 -0
  17. package/src/board/host.ts +93 -63
  18. package/src/board/membership.ts +16 -11
  19. package/src/board/records.ts +185 -0
  20. package/src/close-idle.ts +2 -9
  21. package/src/context-briefing.ts +230 -0
  22. package/src/context-routing.ts +1 -1
  23. package/src/control-panel/index.ts +2 -4
  24. package/src/control-panel/items.ts +1 -11
  25. package/src/control-panel/view.ts +3 -9
  26. package/src/controller.ts +50 -63
  27. package/src/core/AGENTS.md +7 -4
  28. package/src/core/admission-broker.mjs +235 -0
  29. package/src/core/admission-endpoint.ts +180 -0
  30. package/src/core/admission-owner.mjs +52 -0
  31. package/src/core/admission-startup.ts +130 -0
  32. package/src/core/admission.ts +181 -0
  33. package/src/core/agents.ts +102 -0
  34. package/src/core/backend.ts +110 -84
  35. package/src/core/client.ts +16 -0
  36. package/src/core/focus-channel-helper.mjs +6 -27
  37. package/src/core/focus-channel-wire.mjs +9 -6
  38. package/src/core/focus-channel.ts +5 -3
  39. package/src/core/focus-window.ts +15 -4
  40. package/src/core/helper-bootstrap.mjs +70 -0
  41. package/src/core/helper-context.mjs +98 -0
  42. package/src/core/helper-core.mjs +121 -0
  43. package/src/core/machines.ts +30 -0
  44. package/src/core/registration.ts +7 -2
  45. package/src/core/remote-endpoint.ts +80 -74
  46. package/src/core/remote-helper.ts +330 -0
  47. package/src/core/remote-reader.ts +3 -42
  48. package/src/core/remote-service.mjs +239 -0
  49. package/src/core/remote-transport.ts +290 -0
  50. package/src/core/spawn.ts +20 -20
  51. package/src/core/terminal-peer.mjs +57 -0
  52. package/src/core/terminal.ts +4 -2
  53. package/src/delivery.ts +39 -0
  54. package/src/fleet/catalog.ts +16 -58
  55. package/src/fleet/connection.ts +9 -18
  56. package/src/fleet/index.ts +38 -76
  57. package/src/fleet/inspection.ts +9 -22
  58. package/src/fleet/machine.ts +28 -12
  59. package/src/fleet/monitor.ts +8 -29
  60. package/src/fleet/persistence.ts +2 -2
  61. package/src/fleet/reconnect.ts +5 -3
  62. package/src/fleet/setup.ts +6 -16
  63. package/src/launch-contract.ts +0 -3
  64. package/src/launch-location.ts +4 -132
  65. package/src/launch.ts +18 -144
  66. package/src/messages/attachments.ts +1 -1
  67. package/src/messages/attribution.ts +9 -14
  68. package/src/messages/events.ts +5 -9
  69. package/src/messages/focus.ts +2 -7
  70. package/src/messages/guidance.ts +2 -43
  71. package/src/messages/peer-sharing.ts +133 -0
  72. package/src/monitor-events.ts +14 -43
  73. package/src/monitor-extension-messages.ts +5 -6
  74. package/src/monitor-record.ts +4 -0
  75. package/src/monitor-state.ts +1 -101
  76. package/src/monitor.ts +38 -66
  77. package/src/notes-discovery.ts +67 -0
  78. package/src/peer-inbox.ts +21 -27
  79. package/src/remote/context-relay.ts +25 -10
  80. package/src/remote/notes-reader.mjs +67 -0
  81. package/src/remote/shepherdr-channel.mjs +1 -1
  82. package/src/remote/shepherdr-checkpoints.mjs +49 -102
  83. package/src/remote/shepherdr-context.mjs +1 -1
  84. package/src/remote/shepherdr-peer.mjs +19 -24
  85. package/src/remote/shepherdr-session.mjs +18 -7
  86. package/src/saved-context.ts +62 -0
  87. package/src/settlement/collector.ts +29 -9
  88. package/src/settlement/index.ts +35 -6
  89. package/src/shared-context-host.ts +27 -33
  90. package/src/shared-context.ts +44 -15
  91. package/src/spawn-context.ts +11 -3
  92. package/src/spawn-ownership.ts +1 -1
  93. package/src/ssh-setup.ts +40 -73
  94. package/src/types.ts +4 -8
  95. package/src/voice-handoff.ts +1 -1
  96. package/src/widget.ts +7 -2
  97. package/src/worker-ownership.ts +2 -8
  98. package/src/worker-service.ts +6 -14
  99. package/src/core/context-relay.mjs +0 -111
  100. package/src/core/remote-exec.ts +0 -122
  101. package/src/core/remote-helper.mjs +0 -244
  102. package/src/core/remote-relay.ts +0 -191
  103. package/src/core/request.ts +0 -124
  104. package/src/herdr-client.ts +0 -364
  105. package/src/herdr.ts +0 -268
  106. package/src/machine-catalog.ts +0 -83
  107. package/src/monitor-event.ts +0 -84
  108. package/src/remote/client.ts +0 -127
  109. package/src/remote/deployment.ts +0 -179
  110. package/src/remote/focus-channels.ts +0 -89
  111. package/src/remote/shepherdr.mjs +0 -504
  112. package/src/remote/transport.ts +0 -369
@@ -1,191 +0,0 @@
1
- import { createHash, randomBytes } from "node:crypto";
2
- import { CoreClient } from "./client.js";
3
- import { object } from "./protocol.js";
4
- import { type CoreMachine, remoteExec } from "./remote-exec.js";
5
-
6
- // Fleet closes synchronously and can immediately construct a replacement owner.
7
- // Retain only live/closing routes, including starts not yet acknowledged by Core.
8
- const routes = new Map<string, CoreContextRelay>();
9
- // Match context-relay.mjs: sixfold Notes escaping plus envelope headroom.
10
- const RELAY_PAYLOAD_BYTES = 6_250_000;
11
-
12
- /** Owns the reverse route, its bounded polling and all host-side handlers. */
13
- export class CoreContextRelay {
14
- private readonly client: CoreClient;
15
- private readonly machine: CoreMachine;
16
- private readonly token = randomBytes(32).toString("hex");
17
- private readonly controller = new AbortController();
18
- private readonly incoming = new Map<string, AbortController>();
19
- private pathValue: string | undefined;
20
- private failed: Error | undefined;
21
- private closed = false;
22
- private closing: Promise<void> | undefined;
23
- private starting: Promise<void> | undefined;
24
- private route: string | undefined;
25
- private readonly socket: string;
26
- private onFailure: ((error: Error) => void) | undefined;
27
- constructor(socket: string, machine: CoreMachine) {
28
- this.socket = socket;
29
- this.client = new CoreClient(socket);
30
- this.machine = machine;
31
- }
32
- start(
33
- threadId: string,
34
- handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
35
- onFailure: (error: Error) => void,
36
- ): Promise<void> {
37
- if (this.starting || this.closed)
38
- return Promise.reject(
39
- new Error("Shared context relay is already started or closed"),
40
- );
41
- this.route = JSON.stringify([this.socket, this.machine.id, threadId]);
42
- const previous = routes.get(this.route);
43
- routes.set(this.route, this);
44
- this.starting = this.open(threadId, handle, onFailure, previous);
45
- return this.starting;
46
- }
47
- private async open(
48
- threadId: string,
49
- handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
50
- onFailure: (error: Error) => void,
51
- previous: CoreContextRelay | undefined,
52
- ): Promise<void> {
53
- await previous?.close();
54
- this.controller.signal.throwIfAborted();
55
- this.onFailure = onFailure;
56
- const path = await remoteExec(
57
- this.client,
58
- this.machine,
59
- {
60
- op: "relay-start",
61
- threadId,
62
- routeId: createHash("sha256")
63
- .update(this.machine.id)
64
- .digest("hex")
65
- .slice(0, 32),
66
- relayToken: this.token,
67
- },
68
- // Accepted machine.exec is not cancelled by closing its local socket.
69
- // Finish this bounded start so close can remove its actual daemon.
70
- );
71
- if (typeof path !== "string")
72
- throw new Error("Invalid shared context relay path");
73
- this.pathValue = path;
74
- if (this.closed) return;
75
- void this.poll(handle).catch((error: unknown) => {
76
- this.fail(error);
77
- });
78
- }
79
- path(): string {
80
- if (this.failed)
81
- throw new Error(
82
- `Shared context relay disconnected: ${this.failed.message}. Open /herdr → Status to retry sharing`,
83
- );
84
- if (!this.pathValue || this.controller.signal.aborted)
85
- throw new Error(
86
- "Shared context relay is unavailable; open /herdr → Status to retry sharing",
87
- );
88
- return this.pathValue;
89
- }
90
- private call(request: object, signal?: AbortSignal) {
91
- return remoteExec(
92
- this.client,
93
- this.machine,
94
- {
95
- op: "context",
96
- path: this.pathValue,
97
- request: { ...request, relayToken: this.token },
98
- },
99
- { timeoutMs: 25_000, ...(signal ? { signal } : {}) },
100
- );
101
- }
102
- private async poll(
103
- handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
104
- ) {
105
- while (!this.controller.signal.aborted) {
106
- const batch = object(
107
- await this.call({ action: "poll" }, this.controller.signal),
108
- );
109
- if (!Array.isArray(batch["requests"]) || !Array.isArray(batch["active"]))
110
- throw new Error("Invalid shared context relay batch");
111
- const active = batch["active"];
112
- for (const [id, controller] of this.incoming)
113
- if (!active.includes(id)) controller.abort();
114
- for (const value of batch["requests"]) {
115
- const entry = object(value);
116
- const id = entry["id"];
117
- if (typeof id !== "string" || this.incoming.has(id))
118
- throw new Error("Invalid shared context relay request");
119
- const controller = new AbortController();
120
- this.incoming.set(id, controller);
121
- void this.respond(id, entry["request"], controller, handle)
122
- .catch((error: unknown) => {
123
- this.fail(error);
124
- })
125
- .finally(() => this.incoming.delete(id));
126
- }
127
- }
128
- if (this.failed) throw this.failed;
129
- }
130
- private async respond(
131
- id: string,
132
- request: unknown,
133
- controller: AbortController,
134
- handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
135
- ) {
136
- let reply: object;
137
- try {
138
- controller.signal.throwIfAborted();
139
- const result = await handle(request, controller.signal);
140
- reply = { ok: true, result };
141
- } catch (error) {
142
- reply = {
143
- ok: false,
144
- error: error instanceof Error ? error.message : String(error),
145
- };
146
- }
147
- if (controller.signal.aborted || this.controller.signal.aborted) return;
148
- if (Buffer.byteLength(JSON.stringify(reply)) > RELAY_PAYLOAD_BYTES)
149
- reply = {
150
- ok: false,
151
- error: "Shared context response is too large; narrow the request",
152
- };
153
- await this.call({ action: "reply", id, ...reply }, this.controller.signal);
154
- }
155
- private fail(error: unknown): void {
156
- if (this.closed) return;
157
- this.failed = error instanceof Error ? error : new Error(String(error));
158
- void this.close();
159
- this.onFailure?.(this.failed);
160
- }
161
- close(): Promise<void> {
162
- if (this.closing) return this.closing;
163
- this.closed = true;
164
- this.controller.abort();
165
- for (const controller of this.incoming.values()) controller.abort();
166
- this.incoming.clear();
167
- // A separate bounded connection can close the accepted remote daemon.
168
- // If the machine disappeared, its 30-second lease performs cleanup.
169
- this.closing = (async () => {
170
- await this.starting?.catch(() => {});
171
- if (this.pathValue)
172
- await remoteExec(
173
- this.client,
174
- this.machine,
175
- { op: "relay-close", path: this.pathValue, relayToken: this.token },
176
- { timeoutMs: 10_000 },
177
- );
178
- })()
179
- .catch(async () => {
180
- // A failed close cannot prove removal. Keep replacement starts
181
- // behind the daemon's 30-second no-poll lease, not a stale owner.
182
- await new Promise((resolve) => setTimeout(resolve, 31_000));
183
- })
184
- .finally(() => {
185
- this.client.close();
186
- if (this.route && routes.get(this.route) === this)
187
- routes.delete(this.route);
188
- });
189
- return this.closing;
190
- }
191
- }
@@ -1,124 +0,0 @@
1
- import type { CoreClient } from "./client.js";
2
- import { focusCoreWindow } from "./focus-window.js";
3
- import { object } from "./protocol.js";
4
- import { RemoteCoreEndpoint } from "./remote-endpoint.js";
5
- import { terminalPane, terminalSnapshot } from "./terminal.js";
6
-
7
- function unavailableFocus(): Error {
8
- return Object.assign(
9
- new Error(
10
- "Focus is unavailable: the Herdr window cannot confirm which Core it controls. Use hc attach with the terminal address on this Core; messages and supervision remain available.",
11
- ),
12
- { code: "SHEPHERDR_DELIVERY_REJECTED" },
13
- );
14
- }
15
-
16
- /** Translate legacy connection operations to Core without owning connection lifetime. */
17
- export async function dispatchCoreRequest(
18
- core: CoreClient | RemoteCoreEndpoint,
19
- method: string,
20
- params: Record<string, unknown>,
21
- timeoutMs: number,
22
- ): Promise<unknown> {
23
- const options = { timeoutMs };
24
- switch (method) {
25
- case "ping":
26
- return core.request("hello", {}, options);
27
- case "session.snapshot":
28
- return {
29
- snapshot: terminalSnapshot(
30
- await core.request("terminal.list", {}, options),
31
- ),
32
- };
33
- case "agent.get": {
34
- const listing = object(await core.request("terminal.list", {}, options));
35
- const snapshot = terminalSnapshot(listing);
36
- const terminals = listing["terminals"];
37
- // Include finished and non-Pi terminals: an address must not redirect.
38
- const exact =
39
- Array.isArray(terminals) &&
40
- terminals.some(
41
- (terminal) => object(terminal)["address"] === params["target"],
42
- );
43
- const matches = exact
44
- ? []
45
- : snapshot.agents.filter((agent) => agent.name === params["target"]);
46
- if (matches.length > 1)
47
- throw new Error("Agent name is ambiguous; use its terminal address");
48
- return {
49
- agent: terminalPane(
50
- await core.request(
51
- "terminal.get",
52
- { terminal: matches[0]?.terminal_id ?? params["target"] },
53
- options,
54
- ),
55
- ),
56
- };
57
- }
58
- case "pane.get":
59
- case "pane.current":
60
- return {
61
- pane: terminalPane(
62
- await core.request(
63
- "terminal.get",
64
- { terminal: params["pane_id"] ?? params["caller_pane_id"] },
65
- options,
66
- ),
67
- ),
68
- };
69
- case "agent.read": {
70
- const result = object(
71
- await core.request(
72
- "terminal.read",
73
- {
74
- terminal: params["target"],
75
- lines: params["source"] === "visible" ? 0 : params["lines"],
76
- },
77
- options,
78
- ),
79
- );
80
- return {
81
- read: {
82
- text: result["text"],
83
- truncated: result["complete"] === false,
84
- },
85
- };
86
- }
87
- case "agent.focus":
88
- if (core instanceof RemoteCoreEndpoint) throw unavailableFocus();
89
- if (typeof params["target"] !== "string")
90
- throw new Error("Use the exact local terminal address");
91
- return focusCoreWindow(core, params["target"]);
92
- case "workspace.close":
93
- case "tab.close":
94
- throw new Error(
95
- "Window-location cleanup is unavailable through Core; close only the created terminal by its exact address",
96
- );
97
- case "terminal.close":
98
- case "pane.close": {
99
- const terminal = params["pane_id"] ?? params["id"];
100
- if (typeof terminal !== "string" || !/^t[0-9a-z]+$/.test(terminal))
101
- throw new Error(
102
- "Cleanup requires an exact local Core terminal address",
103
- );
104
- const current = object(
105
- await core.request("terminal.get", { terminal }, options),
106
- );
107
- if (current["address"] !== terminal)
108
- throw new Error(
109
- "Core terminal identity changed; resolve the target again",
110
- );
111
- if (current["state"] === "live")
112
- await core.request("terminal.kill", { terminal }, options);
113
- else if (current["state"] !== "finished")
114
- throw new Error(
115
- "Core terminal state is unknown; inspect it before cleanup",
116
- );
117
- return core.request("terminal.rm", { terminal }, options);
118
- }
119
- default:
120
- throw new Error(
121
- `Action ${method} is unavailable through Core; use Core terminal operations or the Herdr window commands`,
122
- );
123
- }
124
- }
@@ -1,364 +0,0 @@
1
- import { createConnection } from "node:net";
2
- import { hostname } from "node:os";
3
- import { openPeerChannel } from "./remote/shepherdr-channel.mjs";
4
- import { requestContext } from "./remote/shepherdr-context.mjs";
5
- import {
6
- sendPeerCommands,
7
- sendPeerExtensionReply,
8
- sendPeerFocus,
9
- sendPeerMessage,
10
- } from "./remote/shepherdr-peer.mjs";
11
- import type {
12
- FocusRequest,
13
- HerdrEvent,
14
- MachineIdentity,
15
- PaneInfo,
16
- PeerChannel,
17
- PeerCommand,
18
- PeerDelivery,
19
- PeerMessage,
20
- } from "./types.js";
21
-
22
- const MAX_FRAME_BUFFER = 8 * 1024 * 1024;
23
-
24
- function socketEndpoint(socketPath: string): string {
25
- return process.platform === "win32"
26
- ? `\\\\.\\pipe\\${socketPath}`
27
- : socketPath;
28
- }
29
-
30
- function errorFromResponse(value: unknown): Error {
31
- let error: Error & { code?: string; herdrResponse?: true };
32
- if (
33
- typeof value === "object" &&
34
- value !== null &&
35
- "message" in value &&
36
- typeof value.message === "string"
37
- ) {
38
- error = new Error(value.message);
39
- if ("code" in value && typeof value.code === "string") {
40
- error.code = value.code;
41
- }
42
- } else {
43
- error = new Error(`Herdr request failed: ${JSON.stringify(value)}`);
44
- }
45
- error.herdrResponse = true;
46
- return error;
47
- }
48
-
49
- function isHerdrResponseError(error: unknown): boolean {
50
- return (error as Error & { herdrResponse?: unknown }).herdrResponse === true;
51
- }
52
-
53
- export function isDispatchRejected(error: unknown): boolean {
54
- return (
55
- isHerdrResponseError(error) ||
56
- (error instanceof Error &&
57
- "code" in error &&
58
- error.code === "SHEPHERDR_DELIVERY_REJECTED")
59
- );
60
- }
61
-
62
- export function isHerdrErrorCode(error: unknown, code: string): boolean {
63
- return (
64
- isHerdrResponseError(error) &&
65
- (error as Error & { code?: unknown }).code === code
66
- );
67
- }
68
-
69
- export interface HerdrConnection {
70
- replyExtension(
71
- agent: PaneInfo,
72
- reply: import("./types.js").ExtensionReply,
73
- ): Promise<string>;
74
- machineIdentity(): Promise<MachineIdentity>;
75
- focus(agent: PaneInfo, request: FocusRequest): Promise<unknown>;
76
- openFocusChannel(
77
- agent: PaneInfo,
78
- request: FocusRequest,
79
- ): Promise<PeerChannel>;
80
- requestContext(
81
- path: string,
82
- request: unknown,
83
- signal?: AbortSignal,
84
- ): Promise<unknown>;
85
- contextRelayPath(): string;
86
- request<T>(method: string, params?: object, timeoutMs?: number): Promise<T>;
87
- sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery>;
88
- commands(agent: PaneInfo): Promise<PeerCommand[]>;
89
- subscribe(
90
- subscriptions: object[],
91
- onEvent: (event: HerdrEvent) => void,
92
- onDisconnect: (error?: Error) => void,
93
- signal?: AbortSignal,
94
- ): Promise<() => void>;
95
- }
96
-
97
- export class HerdrClient implements HerdrConnection {
98
- readonly socketPath: string;
99
- replyExtension(
100
- agent: PaneInfo,
101
- reply: import("./types.js").ExtensionReply,
102
- ): Promise<string> {
103
- return sendPeerExtensionReply(
104
- (method, params) => this.request(method, params),
105
- agent,
106
- reply,
107
- );
108
- }
109
- openFocusChannel(
110
- agent: PaneInfo,
111
- request: FocusRequest,
112
- ): Promise<PeerChannel> {
113
- return openPeerChannel(
114
- (method, params) => this.request(method, params),
115
- agent,
116
- request,
117
- );
118
- }
119
- async machineIdentity(): Promise<MachineIdentity> {
120
- return {
121
- host: hostname(),
122
- session: process.env["HERDR_SESSION"] || "default",
123
- };
124
- }
125
- focus(agent: PaneInfo, request: FocusRequest): Promise<unknown> {
126
- return sendPeerFocus(
127
- (method, params) => this.request(method, params),
128
- agent,
129
- request,
130
- );
131
- }
132
- requestContext(
133
- path: string,
134
- request: unknown,
135
- signal?: AbortSignal,
136
- ): Promise<unknown> {
137
- return requestContext(path, request, signal);
138
- }
139
- contextRelayPath(): string {
140
- throw new Error("Local context routes use the controller session");
141
- }
142
-
143
- constructor(socketPath = process.env["HERDR_SOCKET_PATH"]) {
144
- if (!socketPath) {
145
- throw new Error(
146
- "HERDR_SOCKET_PATH is not set; run the controlling Pi session inside Herdr",
147
- );
148
- }
149
- this.socketPath = socketPath;
150
- }
151
-
152
- sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery> {
153
- return sendPeerMessage(
154
- (method, params) => this.request(method, params),
155
- agent,
156
- message,
157
- );
158
- }
159
-
160
- commands(agent: PaneInfo): Promise<PeerCommand[]> {
161
- return sendPeerCommands(
162
- (method, params) => this.request(method, params),
163
- agent,
164
- );
165
- }
166
-
167
- request<T>(
168
- method: string,
169
- params: object = {},
170
- timeoutMs = 10_000,
171
- ): Promise<T> {
172
- return new Promise((resolve, reject) => {
173
- const id = `pi-shepherdr:${crypto.randomUUID()}`;
174
- let buffer = "";
175
- let settled = false;
176
- const socket = createConnection(socketEndpoint(this.socketPath));
177
- socket.setEncoding("utf8");
178
- const timer = setTimeout(
179
- () => finish(new Error(`Herdr ${method} timed out`)),
180
- timeoutMs,
181
- );
182
- timer.unref();
183
-
184
- const finish = (error?: Error, result?: T) => {
185
- if (settled) return;
186
- settled = true;
187
- clearTimeout(timer);
188
- socket.destroy();
189
- if (error) reject(error);
190
- else resolve(result as T);
191
- };
192
-
193
- socket.on("connect", () => {
194
- socket.write(`${JSON.stringify({ id, method, params })}\n`);
195
- });
196
- socket.on("error", (error) => finish(error));
197
- socket.on("end", () => finish(new Error(`Herdr ${method} disconnected`)));
198
- socket.on("data", (chunk: string) => {
199
- buffer += chunk;
200
- if (buffer.length > MAX_FRAME_BUFFER) {
201
- finish(new Error(`Herdr ${method} response is too large`));
202
- return;
203
- }
204
- const newline = buffer.indexOf("\n");
205
- if (newline < 0) return;
206
- try {
207
- const response = JSON.parse(buffer.slice(0, newline)) as {
208
- id?: unknown;
209
- error?: unknown;
210
- result?: T;
211
- };
212
- if (response.id !== id)
213
- finish(
214
- new Error(`Herdr ${method} returned a mismatched response ID`),
215
- );
216
- else if (response.error !== undefined)
217
- finish(errorFromResponse(response.error));
218
- else if (response.result !== undefined)
219
- finish(undefined, response.result);
220
- else finish(new Error(`Herdr ${method} returned no result`));
221
- } catch (error) {
222
- finish(
223
- new Error(
224
- `Herdr ${method} returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
225
- ),
226
- );
227
- }
228
- });
229
- });
230
- }
231
-
232
- subscribe(
233
- subscriptions: object[],
234
- onEvent: (event: HerdrEvent) => void,
235
- onDisconnect: (error?: Error) => void,
236
- signal?: AbortSignal,
237
- ): Promise<() => void> {
238
- return new Promise((resolve, reject) => {
239
- const id = `pi-shepherdr:subscribe:${crypto.randomUUID()}`;
240
- let acknowledged = false;
241
- let buffer = "";
242
- let closed = false;
243
- let disconnected = false;
244
- const socket = createConnection(socketEndpoint(this.socketPath));
245
- socket.setEncoding("utf8");
246
- const timer = setTimeout(
247
- () => disconnect(new Error("Herdr events.subscribe timed out")),
248
- 10_000,
249
- );
250
- timer.unref();
251
-
252
- const disconnect = (error?: Error) => {
253
- if (disconnected) return;
254
- disconnected = true;
255
- clearTimeout(timer);
256
- signal?.removeEventListener("abort", abort);
257
- socket.destroy();
258
- if (!acknowledged)
259
- reject(
260
- error ??
261
- new Error("Herdr events.subscribe closed before acknowledgement"),
262
- );
263
- else if (!closed) onDisconnect(error);
264
- };
265
- const abort = () => {
266
- closed = true;
267
- disconnect(
268
- signal?.reason instanceof Error
269
- ? signal.reason
270
- : new Error("Herdr subscription cancelled"),
271
- );
272
- };
273
- signal?.addEventListener("abort", abort, { once: true });
274
- if (signal?.aborted) abort();
275
-
276
- socket.on("connect", () => {
277
- socket.write(
278
- `${JSON.stringify({ id, method: "events.subscribe", params: { subscriptions } })}\n`,
279
- );
280
- });
281
- socket.on("error", disconnect);
282
- socket.on("end", () => disconnect());
283
- socket.on("close", () => disconnect());
284
- socket.on("data", (chunk: string) => {
285
- if (disconnected) return;
286
- buffer += chunk;
287
- if (buffer.length > MAX_FRAME_BUFFER) {
288
- disconnect(new Error("Herdr event frame is too large"));
289
- socket.destroy();
290
- return;
291
- }
292
- for (;;) {
293
- const newline = buffer.indexOf("\n");
294
- if (newline < 0) break;
295
- const line = buffer.slice(0, newline);
296
- buffer = buffer.slice(newline + 1);
297
- if (!line) continue;
298
- let value: Record<string, unknown>;
299
- try {
300
- value = JSON.parse(line) as Record<string, unknown>;
301
- } catch (error) {
302
- disconnect(
303
- new Error(
304
- `Herdr events.subscribe returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
305
- ),
306
- );
307
- socket.destroy();
308
- return;
309
- }
310
- if (value["id"] === id && value["error"] !== undefined) {
311
- disconnect(errorFromResponse(value["error"]));
312
- return;
313
- }
314
- if (!acknowledged && value["id"] === id) {
315
- const result = value["result"];
316
- if (
317
- typeof result !== "object" ||
318
- result === null ||
319
- !("type" in result) ||
320
- result.type !== "subscription_started"
321
- ) {
322
- disconnect(
323
- new Error(
324
- "Herdr events.subscribe returned an invalid acknowledgement",
325
- ),
326
- );
327
- socket.destroy();
328
- return;
329
- }
330
- acknowledged = true;
331
- clearTimeout(timer);
332
- resolve(() => {
333
- closed = true;
334
- disconnect();
335
- });
336
- continue;
337
- }
338
- if (
339
- acknowledged &&
340
- typeof value["event"] === "string" &&
341
- typeof value["data"] === "object" &&
342
- value["data"] !== null
343
- ) {
344
- try {
345
- onEvent({
346
- event: value["event"],
347
- data: value["data"] as Record<string, unknown>,
348
- });
349
- } catch (error) {
350
- disconnect(
351
- new Error(
352
- `Shepherdr event handling failed: ${error instanceof Error ? error.message : String(error)}`,
353
- { cause: error },
354
- ),
355
- );
356
- socket.destroy();
357
- return;
358
- }
359
- }
360
- }
361
- });
362
- });
363
- }
364
- }