@elecnix/bellwether 0.1.0 → 0.1.2

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 (46) hide show
  1. package/README.md +2 -1
  2. package/dist/cli.js +295 -0
  3. package/dist/core/classifier.js +66 -0
  4. package/dist/core/herdr-client.js +368 -0
  5. package/dist/core/outbox.js +80 -0
  6. package/dist/core/paths.js +32 -0
  7. package/dist/core/registry.js +93 -0
  8. package/dist/core/report.js +50 -0
  9. package/dist/core/spawn.js +128 -0
  10. package/dist/core/transcript.js +79 -0
  11. package/dist/core/types.js +1 -0
  12. package/dist/core/watcher.js +593 -0
  13. package/dist/daemon/client.js +377 -0
  14. package/dist/daemon/lock.js +68 -0
  15. package/dist/daemon/main.js +34 -0
  16. package/dist/daemon/protocol.js +90 -0
  17. package/dist/daemon/server.js +244 -0
  18. package/dist/daemon/service.js +63 -0
  19. package/dist/integrations/claude/channel.js +245 -0
  20. package/dist/integrations/claude/transcript.js +135 -0
  21. package/dist/integrations/pi/extension.js +117 -0
  22. package/dist/integrations/tools.js +220 -0
  23. package/package.json +7 -6
  24. package/bin/bellwether-mcp.js +0 -4
  25. package/bin/bellwether.js +0 -2
  26. package/src/cli.ts +0 -293
  27. package/src/core/classifier.ts +0 -108
  28. package/src/core/herdr-client.ts +0 -410
  29. package/src/core/outbox.ts +0 -89
  30. package/src/core/paths.ts +0 -41
  31. package/src/core/registry.ts +0 -96
  32. package/src/core/report.ts +0 -54
  33. package/src/core/spawn.ts +0 -159
  34. package/src/core/transcript.ts +0 -74
  35. package/src/core/types.ts +0 -95
  36. package/src/core/watcher.ts +0 -590
  37. package/src/daemon/client.ts +0 -383
  38. package/src/daemon/lock.ts +0 -72
  39. package/src/daemon/main.ts +0 -38
  40. package/src/daemon/protocol.ts +0 -184
  41. package/src/daemon/server.ts +0 -275
  42. package/src/daemon/service.ts +0 -80
  43. package/src/integrations/claude/channel.ts +0 -247
  44. package/src/integrations/claude/transcript.ts +0 -124
  45. package/src/integrations/pi/extension.ts +0 -136
  46. package/src/integrations/tools.ts +0 -235
@@ -1,383 +0,0 @@
1
- // The daemon client: one connection per session, started on demand. A tool
2
- // call, a receipt and an event all cross the same socket, and a reconnect
3
- // replays the events the session missed while it was away.
4
- import fs from 'node:fs';
5
- import net from 'node:net';
6
- import os from 'node:os';
7
- import path from 'node:path';
8
- import { spawn } from 'node:child_process';
9
- import { fileURLToPath } from 'node:url';
10
- import { DAEMON_PROTOCOL, MAX_DAEMON_FRAME_BYTES, formatRequest, type DaemonReply, type ParentHello } from './protocol.ts';
11
- import { canConnect } from './server.ts';
12
- import type { OutboxEntry } from '../core/types.ts';
13
-
14
- const DEFAULT_TIMEOUT_MS = 60_000;
15
- const START_TIMEOUT_MS = 10_000;
16
- const RECONNECT_DELAY_MS = 200;
17
-
18
- export interface ConnectOptions {
19
- home?: string;
20
- socketPath?: string;
21
- /** Start the daemon when nothing answers on the socket. Default true. */
22
- spawn?: boolean;
23
- timeoutMs?: number;
24
- log?: (message: string) => void;
25
- /** The daemon entry point, overridable so a test can point at its own. */
26
- entry?: string;
27
- }
28
-
29
- interface Connection {
30
- socket: net.Socket;
31
- buffer: string;
32
- }
33
-
34
- export class DaemonClient {
35
- private connection: Connection | undefined;
36
- private readonly waiting = new Map<string, { resolve: (text: string) => void; reject: (error: Error) => void }>();
37
- private readonly handlers = new Set<(entries: OutboxEntry[]) => void>();
38
- private readonly paneHandlers = new Map<string, Set<(status: string) => void>>();
39
- private readonly received = new Map<string, OutboxEntry>();
40
- private readonly unsentReceipts: string[] = [];
41
- private sequence = 0;
42
- private stopped = false;
43
- private reconnecting = false;
44
- private lastEvents: OutboxEntry[] = [];
45
- private closedReply: (() => void) | undefined;
46
-
47
- parentId: string;
48
- pid: number;
49
- readonly socketPath: string;
50
- readonly home: string;
51
-
52
- private constructor(parent: ParentHello, home: string, socketPath: string, options: ConnectOptions) {
53
- this.parent = parent;
54
- this.parentId = '';
55
- this.pid = 0;
56
- this.home = home;
57
- this.socketPath = socketPath;
58
- this.log = options.log ?? (() => {});
59
- this.entry = options.entry;
60
- this.spawnAllowed = options.spawn !== false;
61
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
62
- }
63
-
64
- private readonly parent: ParentHello;
65
- private readonly log: (message: string) => void;
66
- private readonly entry: string | undefined;
67
- private readonly spawnAllowed: boolean;
68
- private readonly timeoutMs: number;
69
-
70
- static async connect(parent: ParentHello, options: ConnectOptions = {}): Promise<DaemonClient> {
71
- const home = options.home ?? process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
72
- const socketPath = options.socketPath ?? path.join(home, 'daemon.sock');
73
- const client = new DaemonClient(parent, home, socketPath, options);
74
- const hello = await client.establish();
75
- return Object.assign(client, { parentId: hello.parentId, pid: hello.pid });
76
- }
77
-
78
- /** Unread entries the daemon sent with the last hello. */
79
- pending(): Promise<OutboxEntry[]> {
80
- return Promise.resolve([...this.lastEvents]);
81
- }
82
-
83
- /** Unread entries this client has seen, newest state per child. */
84
- unread(): OutboxEntry[] {
85
- return [...this.received.values()];
86
- }
87
-
88
- /** Ask the daemon to report one pane's status, until the returned function runs. */
89
- watchPane(paneId: string, handler: (status: string) => void): () => void {
90
- const set = this.paneHandlers.get(paneId) ?? new Set<(status: string) => void>();
91
- set.add(handler);
92
- this.paneHandlers.set(paneId, set);
93
- void this.ensure()
94
- .then(() => this.write(formatRequest({ type: 'watch', paneId })))
95
- .catch((error: Error) => this.log(`watch failed: ${error.message}`));
96
- return () => {
97
- const current = this.paneHandlers.get(paneId);
98
- current?.delete(handler);
99
- if (current && current.size === 0) this.paneHandlers.delete(paneId);
100
- };
101
- }
102
-
103
- onEvents(handler: (entries: OutboxEntry[]) => void): () => void {
104
- this.handlers.add(handler);
105
- return () => this.handlers.delete(handler);
106
- }
107
-
108
- async tool(name: string, args: Record<string, unknown>): Promise<string> {
109
- if (this.stopped) throw new Error('the daemon client is closed');
110
- await this.ensure();
111
- const id = `c${++this.sequence}`;
112
- const line = formatRequest({ type: 'call', id, tool: name, args });
113
- return new Promise<string>((resolve, reject) => {
114
- const timer = setTimeout(() => {
115
- this.waiting.delete(id);
116
- reject(new Error(`the daemon did not answer ${name} within ${this.timeoutMs} ms`));
117
- }, this.timeoutMs);
118
- timer.unref?.();
119
- this.waiting.set(id, {
120
- resolve: (text) => {
121
- clearTimeout(timer);
122
- resolve(text);
123
- },
124
- reject: (error) => {
125
- clearTimeout(timer);
126
- reject(error);
127
- },
128
- });
129
- this.write(line);
130
- });
131
- }
132
-
133
- receipts(receipts: string[]): void {
134
- if (!receipts.length) return;
135
- for (const receipt of receipts) this.received.delete(receipt);
136
- if (!this.connection) {
137
- this.unsentReceipts.push(...receipts);
138
- return;
139
- }
140
- this.write(formatRequest({ type: 'receipt', receipts }));
141
- }
142
-
143
- /** Ask the daemon to close, which it does once the calls in flight finish. */
144
- drain(): Promise<void> {
145
- if (!this.connection) return Promise.resolve();
146
- const socket = this.connection.socket;
147
- return new Promise<void>((resolve) => {
148
- this.closedReply = resolve;
149
- this.write(formatRequest({ type: 'drain' }));
150
- socket.once('close', () => resolve());
151
- setTimeout(() => resolve(), 2_000).unref?.();
152
- });
153
- }
154
-
155
- async close(): Promise<void> {
156
- this.stopped = true;
157
- const connection = this.connection;
158
- this.connection = undefined;
159
- if (!connection) return;
160
- connection.socket.write(formatRequest({ type: 'bye' }));
161
- await new Promise<void>((resolve) => {
162
- connection.socket.once('close', () => resolve());
163
- connection.socket.end();
164
- setTimeout(() => resolve(), 1_000).unref?.();
165
- });
166
- connection.socket.destroy();
167
- for (const waiting of this.waiting.values()) waiting.reject(new Error('the daemon client closed'));
168
- this.waiting.clear();
169
- }
170
-
171
- /** Connect, starting a daemon when nothing answers and spawning is allowed. */
172
- private async establish(): Promise<{ parentId: string; pid: number }> {
173
- try {
174
- return await this.handshake();
175
- } catch (error) {
176
- if (!this.spawnAllowed) throw error;
177
- await this.startDaemon();
178
- return this.handshake();
179
- }
180
- }
181
-
182
- private async ensure(): Promise<void> {
183
- if (this.connection) return;
184
- if (this.stopped) throw new Error('the daemon client is closed');
185
- if (this.reconnecting) return;
186
- this.reconnecting = true;
187
- try {
188
- const hello = await this.establish();
189
- Object.assign(this, { parentId: hello.parentId, pid: hello.pid });
190
- if (this.unsentReceipts.length) this.write(formatRequest({ type: 'receipt', receipts: this.unsentReceipts.splice(0) }));
191
- } finally {
192
- this.reconnecting = false;
193
- }
194
- }
195
-
196
- private async handshake(): Promise<{ parentId: string; pid: number }> {
197
- const connection = await this.open();
198
- const hello = { type: 'hello', protocol: DAEMON_PROTOCOL, client: '0.1.0', parent: this.parent } as const;
199
- const reply = await this.ask(connection, formatRequest(hello));
200
- if (reply.type === 'error') {
201
- connection.socket.destroy();
202
- throw new Error(`${reply.code}: ${reply.message}`);
203
- }
204
- if (reply.type !== 'hello') {
205
- connection.socket.destroy();
206
- throw new Error(`the daemon answered ${reply.type} to a hello`);
207
- }
208
- this.attach(connection);
209
- this.lastEvents = reply.pending;
210
- for (const entry of reply.pending) this.received.set(entry.receipt, entry);
211
- if (reply.pending.length) for (const handler of this.handlers) handler(reply.pending);
212
- return { parentId: reply.parentId, pid: reply.pid };
213
- }
214
-
215
- private open(): Promise<Connection> {
216
- return new Promise((resolve, reject) => {
217
- const socket = net.createConnection(this.socketPath);
218
- const fail = (error: Error): void => {
219
- socket.destroy();
220
- reject(error);
221
- };
222
- socket.once('error', fail);
223
- socket.once('connect', () => {
224
- socket.off('error', fail);
225
- socket.setEncoding('utf8');
226
- resolve({ socket, buffer: '' });
227
- });
228
- });
229
- }
230
-
231
- /** Send one line and wait for the first reply that is not a push. */
232
- private ask(connection: Connection, line: string): Promise<DaemonReply> {
233
- return new Promise((resolve, reject) => {
234
- const timer = setTimeout(() => reject(new Error('the daemon did not answer in time')), START_TIMEOUT_MS);
235
- timer.unref?.();
236
- const onData = (chunk: string): void => {
237
- connection.buffer += chunk;
238
- const index = connection.buffer.indexOf('\n');
239
- if (index < 0) return;
240
- const first = connection.buffer.slice(0, index);
241
- connection.buffer = connection.buffer.slice(index + 1);
242
- connection.socket.off('data', onData);
243
- clearTimeout(timer);
244
- try {
245
- resolve(JSON.parse(first) as DaemonReply);
246
- } catch (error) {
247
- reject(error as Error);
248
- }
249
- };
250
- connection.socket.on('data', onData);
251
- connection.socket.write(line);
252
- });
253
- }
254
-
255
- private attach(connection: Connection): void {
256
- this.connection = connection;
257
- connection.socket.on('data', (chunk: string) => this.read(connection, chunk));
258
- connection.socket.on('close', () => {
259
- if (this.connection === connection) this.connection = undefined;
260
- for (const waiting of this.waiting.values()) waiting.reject(new Error('the daemon connection closed'));
261
- this.waiting.clear();
262
- if (!this.stopped) setTimeout(() => void this.ensure().catch((error: Error) => this.log(`reconnect failed: ${error.message}`)), RECONNECT_DELAY_MS).unref?.();
263
- });
264
- }
265
-
266
- private read(connection: Connection, chunk: string): void {
267
- connection.buffer += chunk;
268
- if (connection.buffer.length > MAX_DAEMON_FRAME_BYTES) {
269
- connection.socket.destroy();
270
- return;
271
- }
272
- let index = connection.buffer.indexOf('\n');
273
- while (index >= 0) {
274
- const line = connection.buffer.slice(0, index);
275
- connection.buffer = connection.buffer.slice(index + 1);
276
- index = connection.buffer.indexOf('\n');
277
- if (!line.trim()) continue;
278
- let reply: DaemonReply;
279
- try {
280
- reply = JSON.parse(line) as DaemonReply;
281
- } catch {
282
- continue;
283
- }
284
- this.dispatch(reply);
285
- }
286
- }
287
-
288
- private dispatch(reply: DaemonReply): void {
289
- if (reply.type === 'events') {
290
- for (const entry of reply.entries) this.received.set(entry.receipt, entry);
291
- for (const handler of this.handlers) handler(reply.entries);
292
- return;
293
- }
294
- if (reply.type === 'status') {
295
- for (const handler of this.paneHandlers.get(reply.paneId) ?? []) handler(reply.status);
296
- return;
297
- }
298
- if (reply.type === 'result') {
299
- const waiting = this.waiting.get(reply.id);
300
- if (!waiting) return;
301
- this.waiting.delete(reply.id);
302
- if (reply.error !== undefined) waiting.reject(new Error(reply.error));
303
- else waiting.resolve(reply.text ?? '');
304
- return;
305
- }
306
- if (reply.type === 'closed') {
307
- this.closedReply?.();
308
- this.closedReply = undefined;
309
- }
310
- }
311
-
312
- private write(line: string): void {
313
- if (!this.connection) throw new Error('the daemon connection is not open');
314
- this.connection.socket.write(line);
315
- }
316
-
317
- /** Start a daemon, with a marker so two clients do not start two. */
318
- private async startDaemon(): Promise<void> {
319
- fs.mkdirSync(this.home, { recursive: true });
320
- const marker = path.join(this.home, 'daemon.starting');
321
- const acquired = this.takeStartingMarker(marker);
322
- if (acquired) {
323
- const entry = this.entry ?? fileURLToPath(new URL('./main.ts', import.meta.url));
324
- const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', entry, '--socket', this.socketPath], {
325
- detached: true,
326
- stdio: 'ignore',
327
- env: { ...process.env, BELLWETHER_HOME: this.home },
328
- });
329
- child.unref();
330
- try {
331
- await this.waitForSocket();
332
- } finally {
333
- fs.rmSync(marker, { force: true });
334
- }
335
- return;
336
- }
337
- await this.waitForSocket();
338
- }
339
-
340
- private takeStartingMarker(marker: string): boolean {
341
- for (let attempt = 0; attempt < 2; attempt += 1) {
342
- try {
343
- const fd = fs.openSync(marker, 'wx', 0o600);
344
- fs.writeSync(fd, `${JSON.stringify({ pid: process.pid, at: Date.now() })}\n`);
345
- fs.closeSync(fd);
346
- return true;
347
- } catch (error) {
348
- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
349
- const holder = this.readMarker(marker);
350
- if (holder && holder.pid !== process.pid && alive(holder.pid) && Date.now() - holder.at < 30_000) return false;
351
- fs.rmSync(marker, { force: true });
352
- }
353
- }
354
- return false;
355
- }
356
-
357
- private readMarker(marker: string): { pid: number; at: number } | undefined {
358
- try {
359
- const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { pid?: number; at?: number };
360
- return typeof parsed.pid === 'number' ? { pid: parsed.pid, at: parsed.at ?? 0 } : undefined;
361
- } catch {
362
- return undefined;
363
- }
364
- }
365
-
366
- private async waitForSocket(): Promise<void> {
367
- const deadline = Date.now() + START_TIMEOUT_MS;
368
- while (Date.now() < deadline) {
369
- if (await canConnect(this.socketPath)) return;
370
- await new Promise((resolve) => setTimeout(resolve, 20));
371
- }
372
- throw new Error(`the daemon did not answer on ${this.socketPath}`);
373
- }
374
- }
375
-
376
- function alive(pid: number): boolean {
377
- try {
378
- process.kill(pid, 0);
379
- return true;
380
- } catch (error) {
381
- return (error as NodeJS.ErrnoException).code === 'EPERM';
382
- }
383
- }
@@ -1,72 +0,0 @@
1
- // The daemon's lock: one file per home, written before a client spawns a
2
- // daemon, so a second client waits for the daemon already starting instead of
3
- // starting another. A lock whose pid is gone is stale and is taken over.
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { DAEMON_PROTOCOL } from './protocol.ts';
7
-
8
- export interface LockRecord {
9
- pid: number;
10
- startedAt: number;
11
- protocol: number;
12
- socket: string;
13
- }
14
-
15
- export function lockPath(home: string): string {
16
- return path.join(home, 'daemon.lock');
17
- }
18
-
19
- export function readLock(home: string): LockRecord | undefined {
20
- try {
21
- const parsed: unknown = JSON.parse(fs.readFileSync(lockPath(home), 'utf8'));
22
- if (typeof parsed !== 'object' || parsed === null) return undefined;
23
- const record = parsed as Partial<LockRecord>;
24
- if (typeof record.pid !== 'number' || !Number.isInteger(record.pid)) return undefined;
25
- return { pid: record.pid, startedAt: record.startedAt ?? 0, protocol: record.protocol ?? 0, socket: record.socket ?? '' };
26
- } catch {
27
- return undefined;
28
- }
29
- }
30
-
31
- /** Whether a process with that pid still runs. EPERM counts as alive. */
32
- export function isAlive(pid: number): boolean {
33
- if (!Number.isInteger(pid) || pid <= 0) return false;
34
- try {
35
- process.kill(pid, 0);
36
- return true;
37
- } catch (error) {
38
- return (error as NodeJS.ErrnoException).code === 'EPERM';
39
- }
40
- }
41
-
42
- export type AcquireResult = { kind: 'acquired' } | { kind: 'held'; record: LockRecord };
43
-
44
- /** Take the lock, or report the live daemon that holds it. */
45
- export function acquire(home: string, socketPath: string, pid = process.pid, alive = isAlive): AcquireResult {
46
- fs.mkdirSync(home, { recursive: true });
47
- const target = lockPath(home);
48
- const record: LockRecord = { pid, startedAt: Date.now(), protocol: DAEMON_PROTOCOL, socket: socketPath };
49
- for (let attempt = 0; attempt < 2; attempt += 1) {
50
- try {
51
- const fd = fs.openSync(target, 'wx', 0o600);
52
- fs.writeSync(fd, `${JSON.stringify(record)}\n`);
53
- fs.closeSync(fd);
54
- return { kind: 'acquired' };
55
- } catch (error) {
56
- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
57
- const held = readLock(home);
58
- if (held && alive(held.pid)) return { kind: 'held', record: held };
59
- fs.rmSync(target, { force: true });
60
- }
61
- }
62
- const held = readLock(home);
63
- if (held && alive(held.pid)) return { kind: 'held', record: held };
64
- throw new Error('the daemon lock could not be taken');
65
- }
66
-
67
- /** Remove the lock when this process owns it. */
68
- export function release(home: string, pid = process.pid): void {
69
- const held = readLock(home);
70
- if (held && held.pid !== pid) return;
71
- fs.rmSync(lockPath(home), { force: true });
72
- }
@@ -1,38 +0,0 @@
1
- // The daemon process entry point. A client starts it detached with the socket
2
- // path, and it exits on drain, on an idle timeout, or on a signal.
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import { startDaemon } from './server.ts';
6
-
7
- const log = (message: string): void => console.error('[bellwether-daemon]', message);
8
-
9
- function flag(argv: string[], name: string): string | undefined {
10
- const index = argv.indexOf(name);
11
- return index >= 0 ? argv[index + 1] : undefined;
12
- }
13
-
14
- async function main(): Promise<void> {
15
- const argv = process.argv.slice(2);
16
- const home = process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
17
- const socketPath = flag(argv, '--socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(home, 'daemon.sock');
18
- const idleMs = Number.parseInt(process.env['BELLWETHER_DAEMON_IDLE_MS'] ?? '', 10);
19
- const daemon = await startDaemon({
20
- socketPath,
21
- home,
22
- log,
23
- ...(Number.isFinite(idleMs) ? { idleMs } : {}),
24
- });
25
- log(`listening on ${socketPath} with pid ${daemon.pid}`);
26
- const stop = (): void => {
27
- void daemon.close().then(() => process.exit(0));
28
- };
29
- process.on('SIGTERM', stop);
30
- process.on('SIGINT', stop);
31
- await daemon.whenClosed();
32
- process.exit(0);
33
- }
34
-
35
- main().catch((error: Error) => {
36
- log(error.message);
37
- process.exit(1);
38
- });
@@ -1,184 +0,0 @@
1
- // The daemon protocol: one request per line, JSON, on a local socket. The
2
- // version travels in every hello, so a client newer than a running daemon can
3
- // ask it to drain and start the new one.
4
- import type { Harness, OutboxEntry } from '../core/types.ts';
5
-
6
- export const DAEMON_PROTOCOL = 1;
7
-
8
- /** The largest line a daemon or client will read, matching the herdr client. */
9
- export const MAX_DAEMON_FRAME_BYTES = 4 * 1024 * 1024;
10
-
11
- export class ProtocolError extends Error {
12
- readonly code: string;
13
-
14
- constructor(code: string, message: string) {
15
- super(message);
16
- this.name = 'ProtocolError';
17
- this.code = code;
18
- }
19
- }
20
-
21
- /** What a client tells the daemon about the session it speaks for. */
22
- export interface ParentHello {
23
- harness: Harness;
24
- session: string;
25
- cwd: string;
26
- host: string;
27
- paneId?: string;
28
- workspaceId?: string;
29
- depth: number;
30
- /** The herdr socket this session watches, so a daemon can serve several. */
31
- herdrSocket: string;
32
- }
33
-
34
- export interface HelloRequest {
35
- type: 'hello';
36
- protocol: number;
37
- client: string;
38
- parent: ParentHello;
39
- }
40
-
41
- export interface CallRequest {
42
- type: 'call';
43
- id: string;
44
- tool: string;
45
- args: Record<string, unknown>;
46
- }
47
-
48
- export interface ReceiptRequest {
49
- type: 'receipt';
50
- receipts: string[];
51
- }
52
-
53
- export interface ByeRequest {
54
- type: 'bye';
55
- }
56
-
57
- export interface DrainRequest {
58
- type: 'drain';
59
- }
60
-
61
- /** Ask the daemon to report one pane's status, used for the parent's own pane. */
62
- export interface WatchRequest {
63
- type: 'watch';
64
- paneId: string;
65
- }
66
-
67
- export type DaemonRequest = HelloRequest | CallRequest | ReceiptRequest | ByeRequest | DrainRequest | WatchRequest;
68
-
69
- export interface HelloReply {
70
- type: 'hello';
71
- protocol: number;
72
- parentId: string;
73
- pid: number;
74
- pending: OutboxEntry[];
75
- }
76
-
77
- export interface ResultReply {
78
- type: 'result';
79
- id: string;
80
- text?: string;
81
- error?: string;
82
- }
83
-
84
- export interface EventsPush {
85
- type: 'events';
86
- entries: OutboxEntry[];
87
- }
88
-
89
- export interface ErrorReply {
90
- type: 'error';
91
- id?: string;
92
- code: string;
93
- message: string;
94
- protocol?: number;
95
- }
96
-
97
- export interface ClosedReply {
98
- type: 'closed';
99
- }
100
-
101
- export interface StatusPush {
102
- type: 'status';
103
- paneId: string;
104
- status: string;
105
- }
106
-
107
- export type DaemonReply = HelloReply | ResultReply | EventsPush | ErrorReply | ClosedReply | StatusPush;
108
-
109
- function isRecord(value: unknown): value is Record<string, unknown> {
110
- return typeof value === 'object' && value !== null && !Array.isArray(value);
111
- }
112
-
113
- function text(value: unknown): string {
114
- return typeof value === 'string' ? value.trim() : '';
115
- }
116
-
117
- /** Parse one request line, or throw a ProtocolError that names the fault. */
118
- export function parseRequest(line: string): DaemonRequest {
119
- let value: unknown;
120
- try {
121
- value = JSON.parse(line);
122
- } catch {
123
- throw new ProtocolError('invalid_json', 'the line is not JSON');
124
- }
125
- if (!isRecord(value)) throw new ProtocolError('invalid_request', 'the line is not an object');
126
- switch (value['type']) {
127
- case 'hello':
128
- return parseHello(value);
129
- case 'call': {
130
- const id = text(value['id']);
131
- const tool = text(value['tool']);
132
- if (!id || !tool) throw new ProtocolError('invalid_call', 'a call needs an id and a tool');
133
- const args = isRecord(value['args']) ? value['args'] : {};
134
- return { type: 'call', id, tool, args };
135
- }
136
- case 'receipt': {
137
- const receipts = Array.isArray(value['receipts']) ? value['receipts'].filter((entry): entry is string => typeof entry === 'string' && entry.length > 0) : [];
138
- return { type: 'receipt', receipts };
139
- }
140
- case 'bye':
141
- return { type: 'bye' };
142
- case 'drain':
143
- return { type: 'drain' };
144
- case 'watch': {
145
- const paneId = text(value['paneId']);
146
- if (!paneId) throw new ProtocolError('invalid_watch', 'a watch needs a pane id');
147
- return { type: 'watch', paneId };
148
- }
149
- default:
150
- throw new ProtocolError('unknown_type', `unknown request type ${JSON.stringify(value['type'])}`);
151
- }
152
- }
153
-
154
- function parseHello(value: Record<string, unknown>): HelloRequest {
155
- const protocol = value['protocol'];
156
- const parent = value['parent'];
157
- if (typeof protocol !== 'number' || !Number.isInteger(protocol)) throw new ProtocolError('invalid_hello', 'a hello needs an integer protocol');
158
- if (!isRecord(parent)) throw new ProtocolError('invalid_hello', 'a hello needs a parent');
159
- const harness = parent['harness'];
160
- const session = text(parent['session']);
161
- const cwd = text(parent['cwd']);
162
- const host = text(parent['host']);
163
- const herdrSocket = text(parent['herdrSocket']);
164
- if (harness !== 'pi' && harness !== 'claude-code') throw new ProtocolError('invalid_hello', 'the parent harness must be pi or claude-code');
165
- if (!session || !cwd || !host || !herdrSocket) throw new ProtocolError('invalid_hello', 'the parent needs a session, cwd, host and herdr socket');
166
- const depth = typeof parent['depth'] === 'number' && Number.isFinite(parent['depth']) ? parent['depth'] : 0;
167
- const optional = (key: string): string | undefined => (typeof parent[key] === 'string' && parent[key] ? (parent[key] as string) : undefined);
168
- return {
169
- type: 'hello',
170
- protocol,
171
- client: text(value['client']) || 'unknown',
172
- parent: { harness, session, cwd, host, depth, herdrSocket, paneId: optional('paneId'), workspaceId: optional('workspaceId') },
173
- };
174
- }
175
-
176
- /** One reply line, without its newline. */
177
- export function formatReply(reply: DaemonReply): string {
178
- return `${JSON.stringify(reply)}\n`;
179
- }
180
-
181
- /** One request line, without its newline. */
182
- export function formatRequest(request: DaemonRequest): string {
183
- return `${JSON.stringify(request)}\n`;
184
- }