@elecnix/bellwether 0.1.0 → 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.
Files changed (58) hide show
  1. package/README.md +58 -7
  2. package/dist/cli.js +296 -0
  3. package/dist/core/adopt.js +59 -0
  4. package/dist/core/brief.js +61 -0
  5. package/dist/core/child-lock.js +84 -0
  6. package/dist/core/classifier.js +100 -0
  7. package/dist/core/herdr-client.js +382 -0
  8. package/dist/core/inactivity.js +31 -0
  9. package/dist/core/label.js +7 -0
  10. package/dist/core/machine.js +134 -0
  11. package/dist/core/mcp-config.js +47 -0
  12. package/dist/core/outbox.js +145 -0
  13. package/dist/core/paths.js +46 -0
  14. package/dist/core/registry.js +129 -0
  15. package/dist/core/report.js +95 -0
  16. package/dist/core/resume.js +210 -0
  17. package/dist/core/retire.js +416 -0
  18. package/dist/core/send.js +17 -0
  19. package/dist/core/spawn-resume.js +96 -0
  20. package/dist/core/spawn.js +226 -0
  21. package/dist/core/startup-dialogs.js +120 -0
  22. package/dist/core/transcript.js +87 -0
  23. package/dist/core/types.js +2 -0
  24. package/dist/core/watcher.js +821 -0
  25. package/dist/daemon/client.js +459 -0
  26. package/dist/daemon/lock.js +68 -0
  27. package/dist/daemon/main.js +40 -0
  28. package/dist/daemon/protocol.js +104 -0
  29. package/dist/daemon/server.js +244 -0
  30. package/dist/daemon/service.js +67 -0
  31. package/dist/integrations/claude/channel.js +257 -0
  32. package/dist/integrations/claude/transcript.js +135 -0
  33. package/dist/integrations/pi/extension.js +119 -0
  34. package/dist/integrations/tools.js +314 -0
  35. package/package.json +10 -9
  36. package/bin/bellwether-mcp.js +0 -4
  37. package/bin/bellwether.js +0 -2
  38. package/src/cli.ts +0 -293
  39. package/src/core/classifier.ts +0 -108
  40. package/src/core/herdr-client.ts +0 -410
  41. package/src/core/outbox.ts +0 -89
  42. package/src/core/paths.ts +0 -41
  43. package/src/core/registry.ts +0 -96
  44. package/src/core/report.ts +0 -54
  45. package/src/core/spawn.ts +0 -159
  46. package/src/core/transcript.ts +0 -74
  47. package/src/core/types.ts +0 -95
  48. package/src/core/watcher.ts +0 -590
  49. package/src/daemon/client.ts +0 -383
  50. package/src/daemon/lock.ts +0 -72
  51. package/src/daemon/main.ts +0 -38
  52. package/src/daemon/protocol.ts +0 -184
  53. package/src/daemon/server.ts +0 -275
  54. package/src/daemon/service.ts +0 -80
  55. package/src/integrations/claude/channel.ts +0 -247
  56. package/src/integrations/claude/transcript.ts +0 -124
  57. package/src/integrations/pi/extension.ts +0 -136
  58. package/src/integrations/tools.ts +0 -235
@@ -0,0 +1,459 @@
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 } from './protocol.js';
11
+ import { canConnect } from './server.js';
12
+ const DEFAULT_TIMEOUT_MS = 60_000;
13
+ const START_TIMEOUT_MS = 10_000;
14
+ const RECONNECT_DELAY_MS = 200;
15
+ /**
16
+ * The variables that name one session. The daemon serves every session on the
17
+ * machine, so it starts without the identity of whichever session started it.
18
+ */
19
+ export const SESSION_IDENTITY = ['BELLWETHER_PARENT', 'BELLWETHER_CHILD', 'BELLWETHER_CHILD_NAME', 'BELLWETHER_DEPTH', 'BELLWETHER_HARNESS', 'HERDR_PANE_ID', 'CLAUDE_CODE_SESSION_ID'];
20
+ /** The environment a daemon starts with: the caller's, less any session identity. */
21
+ export function daemonEnv(env, home) {
22
+ const next = { ...env, BELLWETHER_HOME: home };
23
+ for (const key of SESSION_IDENTITY)
24
+ delete next[key];
25
+ return next;
26
+ }
27
+ /** A daemon that speaks another protocol, and the one it speaks. */
28
+ class ProtocolMismatch extends Error {
29
+ daemonProtocol;
30
+ constructor(message, daemonProtocol) {
31
+ super(`protocol_mismatch: ${message}`);
32
+ this.daemonProtocol = daemonProtocol;
33
+ this.name = 'ProtocolMismatch';
34
+ }
35
+ }
36
+ /** The daemon socket a client uses when none is given: the one under its home. */
37
+ export function defaultDaemonSocket(home) {
38
+ return path.join(home, 'daemon.sock');
39
+ }
40
+ export class DaemonClient {
41
+ connection;
42
+ waiting = new Map();
43
+ handlers = new Set();
44
+ paneHandlers = new Map();
45
+ received = new Map();
46
+ unsentReceipts = [];
47
+ sequence = 0;
48
+ stopped = false;
49
+ reconnecting = false;
50
+ lastEvents = [];
51
+ closedReply;
52
+ parentId;
53
+ pid;
54
+ socketPath;
55
+ home;
56
+ constructor(parent, home, socketPath, options) {
57
+ this.parent = parent;
58
+ this.parentId = '';
59
+ this.pid = 0;
60
+ this.home = home;
61
+ this.socketPath = socketPath;
62
+ this.log = options.log ?? (() => { });
63
+ this.entry = options.entry;
64
+ this.spawnAllowed = options.spawn !== false;
65
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
66
+ }
67
+ parent;
68
+ log;
69
+ entry;
70
+ spawnAllowed;
71
+ timeoutMs;
72
+ static async connect(parent, options = {}) {
73
+ const home = options.home ?? process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
74
+ const socketPath = options.socketPath ?? defaultDaemonSocket(home);
75
+ const client = new DaemonClient(parent, home, socketPath, options);
76
+ const hello = await client.establish();
77
+ return Object.assign(client, { parentId: hello.parentId, pid: hello.pid });
78
+ }
79
+ /** Unread entries the daemon sent with the last hello. */
80
+ pending() {
81
+ return Promise.resolve([...this.lastEvents]);
82
+ }
83
+ /** Unread entries this client has seen, newest state per child. */
84
+ unread() {
85
+ return [...this.received.values()];
86
+ }
87
+ /** Ask the daemon to report one pane's status, until the returned function runs. */
88
+ watchPane(paneId, handler) {
89
+ const set = this.paneHandlers.get(paneId) ?? new Set();
90
+ set.add(handler);
91
+ this.paneHandlers.set(paneId, set);
92
+ void this.ensure()
93
+ .then(() => this.write(formatRequest({ type: 'watch', paneId })))
94
+ .catch((error) => this.log(`watch failed: ${error.message}`));
95
+ return () => {
96
+ const current = this.paneHandlers.get(paneId);
97
+ current?.delete(handler);
98
+ if (current && current.size === 0)
99
+ this.paneHandlers.delete(paneId);
100
+ };
101
+ }
102
+ onEvents(handler) {
103
+ this.handlers.add(handler);
104
+ return () => this.handlers.delete(handler);
105
+ }
106
+ async tool(name, args) {
107
+ if (this.stopped)
108
+ throw new Error('the daemon client is closed');
109
+ await this.ensure();
110
+ const id = `c${++this.sequence}`;
111
+ // The caller identity travels with every call, so the daemon routes by its
112
+ // own records whichever client process asked.
113
+ const caller = { ...(this.parent.paneId ? { paneId: this.parent.paneId } : {}), ...(this.parent.childId ? { childId: this.parent.childId } : {}) };
114
+ const line = formatRequest({ type: 'call', id, tool: name, args, caller });
115
+ return new Promise((resolve, reject) => {
116
+ const timer = setTimeout(() => {
117
+ this.waiting.delete(id);
118
+ reject(new Error(`the daemon did not answer ${name} within ${this.timeoutMs} ms`));
119
+ }, this.timeoutMs);
120
+ timer.unref?.();
121
+ this.waiting.set(id, {
122
+ resolve: (text) => {
123
+ clearTimeout(timer);
124
+ resolve(text);
125
+ },
126
+ reject: (error) => {
127
+ clearTimeout(timer);
128
+ reject(error);
129
+ },
130
+ });
131
+ this.write(line);
132
+ });
133
+ }
134
+ receipts(receipts) {
135
+ if (!receipts.length)
136
+ return;
137
+ for (const receipt of receipts)
138
+ this.received.delete(receipt);
139
+ if (!this.connection) {
140
+ this.unsentReceipts.push(...receipts);
141
+ return;
142
+ }
143
+ this.write(formatRequest({ type: 'receipt', receipts }));
144
+ }
145
+ /** Ask the daemon to close, which it does once the calls in flight finish. */
146
+ drain() {
147
+ if (!this.connection)
148
+ return Promise.resolve();
149
+ const socket = this.connection.socket;
150
+ return new Promise((resolve) => {
151
+ this.closedReply = resolve;
152
+ this.write(formatRequest({ type: 'drain' }));
153
+ socket.once('close', () => resolve());
154
+ setTimeout(() => resolve(), 2_000).unref?.();
155
+ });
156
+ }
157
+ async close() {
158
+ this.stopped = true;
159
+ const connection = this.connection;
160
+ this.connection = undefined;
161
+ if (!connection)
162
+ return;
163
+ connection.socket.write(formatRequest({ type: 'bye' }));
164
+ await new Promise((resolve) => {
165
+ connection.socket.once('close', () => resolve());
166
+ connection.socket.end();
167
+ setTimeout(() => resolve(), 1_000).unref?.();
168
+ });
169
+ connection.socket.destroy();
170
+ for (const waiting of this.waiting.values())
171
+ waiting.reject(new Error('the daemon client closed'));
172
+ this.waiting.clear();
173
+ }
174
+ /**
175
+ * Connect, starting a daemon when nothing answers and spawning is allowed.
176
+ * A daemon from an older release is drained first, so the newer protocol
177
+ * takes over; a newer daemon is left running, and the error says to update.
178
+ */
179
+ async establish() {
180
+ try {
181
+ return await this.handshake();
182
+ }
183
+ catch (error) {
184
+ if (error instanceof ProtocolMismatch) {
185
+ if (error.daemonProtocol === undefined || error.daemonProtocol > DAEMON_PROTOCOL) {
186
+ throw new Error(`the running daemon speaks protocol ${error.daemonProtocol ?? 'unknown'}, newer than this client's ${DAEMON_PROTOCOL}. Update this Bellwether install.`);
187
+ }
188
+ this.log(`draining the daemon on protocol ${error.daemonProtocol}, older than ${DAEMON_PROTOCOL}`);
189
+ const replaced = await this.drainOlder();
190
+ if (replaced)
191
+ return replaced;
192
+ }
193
+ if (!this.spawnAllowed)
194
+ throw error;
195
+ await this.startDaemon();
196
+ return this.handshake();
197
+ }
198
+ }
199
+ async ensure() {
200
+ if (this.connection)
201
+ return;
202
+ if (this.stopped)
203
+ throw new Error('the daemon client is closed');
204
+ if (this.reconnecting)
205
+ return;
206
+ this.reconnecting = true;
207
+ try {
208
+ const hello = await this.establish();
209
+ Object.assign(this, { parentId: hello.parentId, pid: hello.pid });
210
+ if (this.unsentReceipts.length)
211
+ this.write(formatRequest({ type: 'receipt', receipts: this.unsentReceipts.splice(0) }));
212
+ }
213
+ finally {
214
+ this.reconnecting = false;
215
+ }
216
+ }
217
+ async handshake() {
218
+ const connection = await this.open();
219
+ const hello = { type: 'hello', protocol: DAEMON_PROTOCOL, client: '0.1.0', parent: this.parent };
220
+ const reply = await this.ask(connection, formatRequest(hello));
221
+ if (reply.type === 'error') {
222
+ connection.socket.destroy();
223
+ if (reply.code === 'protocol_mismatch')
224
+ throw new ProtocolMismatch(reply.message, reply.protocol);
225
+ throw new Error(`${reply.code}: ${reply.message}`);
226
+ }
227
+ if (reply.type !== 'hello') {
228
+ connection.socket.destroy();
229
+ throw new Error(`the daemon answered ${reply.type} to a hello`);
230
+ }
231
+ this.attach(connection);
232
+ this.lastEvents = reply.pending;
233
+ for (const entry of reply.pending)
234
+ this.received.set(entry.receipt, entry);
235
+ if (reply.pending.length)
236
+ for (const handler of this.handlers)
237
+ handler(reply.pending);
238
+ return { parentId: reply.parentId, pid: reply.pid };
239
+ }
240
+ /**
241
+ * Ask an older daemon to drain, and wait until its socket stops answering,
242
+ * or answers with this protocol because another client started the new daemon first.
243
+ */
244
+ async drainOlder() {
245
+ const connection = await this.open();
246
+ await new Promise((resolve) => {
247
+ connection.socket.once('close', () => resolve());
248
+ connection.socket.write(formatRequest({ type: 'drain' }));
249
+ setTimeout(() => resolve(), START_TIMEOUT_MS).unref?.();
250
+ });
251
+ connection.socket.destroy();
252
+ const deadline = Date.now() + START_TIMEOUT_MS;
253
+ while (await canConnect(this.socketPath)) {
254
+ try {
255
+ return await this.handshake();
256
+ }
257
+ catch (error) {
258
+ if (!(error instanceof ProtocolMismatch))
259
+ throw error;
260
+ }
261
+ if (Date.now() > deadline)
262
+ throw new Error(`the daemon on ${this.socketPath} did not drain within ${START_TIMEOUT_MS} ms`);
263
+ await new Promise((resolve) => setTimeout(resolve, 50));
264
+ }
265
+ return undefined;
266
+ }
267
+ open() {
268
+ return new Promise((resolve, reject) => {
269
+ const socket = net.createConnection(this.socketPath);
270
+ const fail = (error) => {
271
+ socket.destroy();
272
+ reject(error);
273
+ };
274
+ socket.once('error', fail);
275
+ socket.once('connect', () => {
276
+ socket.off('error', fail);
277
+ socket.setEncoding('utf8');
278
+ resolve({ socket, buffer: '' });
279
+ });
280
+ });
281
+ }
282
+ /** Send one line and wait for the first reply that is not a push. */
283
+ ask(connection, line) {
284
+ return new Promise((resolve, reject) => {
285
+ const timer = setTimeout(() => reject(new Error('the daemon did not answer in time')), START_TIMEOUT_MS);
286
+ timer.unref?.();
287
+ const onData = (chunk) => {
288
+ connection.buffer += chunk;
289
+ const index = connection.buffer.indexOf('\n');
290
+ if (index < 0)
291
+ return;
292
+ const first = connection.buffer.slice(0, index);
293
+ connection.buffer = connection.buffer.slice(index + 1);
294
+ connection.socket.off('data', onData);
295
+ clearTimeout(timer);
296
+ try {
297
+ resolve(JSON.parse(first));
298
+ }
299
+ catch (error) {
300
+ reject(error);
301
+ }
302
+ };
303
+ connection.socket.on('data', onData);
304
+ connection.socket.write(line);
305
+ });
306
+ }
307
+ attach(connection) {
308
+ this.connection = connection;
309
+ connection.socket.on('data', (chunk) => this.read(connection, chunk));
310
+ connection.socket.on('close', () => {
311
+ if (this.connection === connection)
312
+ this.connection = undefined;
313
+ for (const waiting of this.waiting.values())
314
+ waiting.reject(new Error('the daemon connection closed'));
315
+ this.waiting.clear();
316
+ if (!this.stopped)
317
+ setTimeout(() => void this.ensure().catch((error) => this.log(`reconnect failed: ${error.message}`)), RECONNECT_DELAY_MS).unref?.();
318
+ });
319
+ }
320
+ read(connection, chunk) {
321
+ connection.buffer += chunk;
322
+ if (connection.buffer.length > MAX_DAEMON_FRAME_BYTES) {
323
+ connection.socket.destroy();
324
+ return;
325
+ }
326
+ let index = connection.buffer.indexOf('\n');
327
+ while (index >= 0) {
328
+ const line = connection.buffer.slice(0, index);
329
+ connection.buffer = connection.buffer.slice(index + 1);
330
+ index = connection.buffer.indexOf('\n');
331
+ if (!line.trim())
332
+ continue;
333
+ let reply;
334
+ try {
335
+ reply = JSON.parse(line);
336
+ }
337
+ catch {
338
+ continue;
339
+ }
340
+ this.dispatch(reply);
341
+ }
342
+ }
343
+ dispatch(reply) {
344
+ if (reply.type === 'events') {
345
+ // An entry that arrives read was settled in the daemon, by a newer state
346
+ // or a newer event for the same child. Drop it, so no resend repeats it.
347
+ const unread = [];
348
+ for (const entry of reply.entries) {
349
+ if (entry.read)
350
+ this.received.delete(entry.receipt);
351
+ else {
352
+ this.received.set(entry.receipt, entry);
353
+ unread.push(entry);
354
+ }
355
+ }
356
+ if (unread.length)
357
+ for (const handler of this.handlers)
358
+ handler(unread);
359
+ return;
360
+ }
361
+ if (reply.type === 'status') {
362
+ for (const handler of this.paneHandlers.get(reply.paneId) ?? [])
363
+ handler(reply.status);
364
+ return;
365
+ }
366
+ if (reply.type === 'result') {
367
+ const waiting = this.waiting.get(reply.id);
368
+ if (!waiting)
369
+ return;
370
+ this.waiting.delete(reply.id);
371
+ if (reply.error !== undefined)
372
+ waiting.reject(new Error(reply.error));
373
+ else
374
+ waiting.resolve(reply.text ?? '');
375
+ return;
376
+ }
377
+ if (reply.type === 'closed') {
378
+ this.closedReply?.();
379
+ this.closedReply = undefined;
380
+ }
381
+ }
382
+ write(line) {
383
+ if (!this.connection)
384
+ throw new Error('the daemon connection is not open');
385
+ this.connection.socket.write(line);
386
+ }
387
+ /** Start a daemon, with a marker so two clients do not start two. */
388
+ async startDaemon() {
389
+ fs.mkdirSync(this.home, { recursive: true });
390
+ const marker = path.join(this.home, 'daemon.starting');
391
+ const acquired = this.takeStartingMarker(marker);
392
+ if (acquired) {
393
+ // From the sources this file is client.ts and the entry is main.ts; from the build, both end in .js.
394
+ const entry = this.entry ?? fileURLToPath(new URL(`./main${path.extname(import.meta.url)}`, import.meta.url));
395
+ const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', entry, '--socket', this.socketPath], {
396
+ detached: true,
397
+ stdio: 'ignore',
398
+ // Never the caller's directory, which for a child is its worktree.
399
+ cwd: this.home,
400
+ env: daemonEnv(process.env, this.home),
401
+ });
402
+ child.unref();
403
+ try {
404
+ await this.waitForSocket();
405
+ }
406
+ finally {
407
+ fs.rmSync(marker, { force: true });
408
+ }
409
+ return;
410
+ }
411
+ await this.waitForSocket();
412
+ }
413
+ takeStartingMarker(marker) {
414
+ for (let attempt = 0; attempt < 2; attempt += 1) {
415
+ try {
416
+ const fd = fs.openSync(marker, 'wx', 0o600);
417
+ fs.writeSync(fd, `${JSON.stringify({ pid: process.pid, at: Date.now() })}\n`);
418
+ fs.closeSync(fd);
419
+ return true;
420
+ }
421
+ catch (error) {
422
+ if (error.code !== 'EEXIST')
423
+ throw error;
424
+ const holder = this.readMarker(marker);
425
+ if (holder && holder.pid !== process.pid && alive(holder.pid) && Date.now() - holder.at < 30_000)
426
+ return false;
427
+ fs.rmSync(marker, { force: true });
428
+ }
429
+ }
430
+ return false;
431
+ }
432
+ readMarker(marker) {
433
+ try {
434
+ const parsed = JSON.parse(fs.readFileSync(marker, 'utf8'));
435
+ return typeof parsed.pid === 'number' ? { pid: parsed.pid, at: parsed.at ?? 0 } : undefined;
436
+ }
437
+ catch {
438
+ return undefined;
439
+ }
440
+ }
441
+ async waitForSocket() {
442
+ const deadline = Date.now() + START_TIMEOUT_MS;
443
+ while (Date.now() < deadline) {
444
+ if (await canConnect(this.socketPath))
445
+ return;
446
+ await new Promise((resolve) => setTimeout(resolve, 20));
447
+ }
448
+ throw new Error(`the daemon did not answer on ${this.socketPath}`);
449
+ }
450
+ }
451
+ function alive(pid) {
452
+ try {
453
+ process.kill(pid, 0);
454
+ return true;
455
+ }
456
+ catch (error) {
457
+ return error.code === 'EPERM';
458
+ }
459
+ }
@@ -0,0 +1,68 @@
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.js';
7
+ export function lockPath(home) {
8
+ return path.join(home, 'daemon.lock');
9
+ }
10
+ export function readLock(home) {
11
+ try {
12
+ const parsed = JSON.parse(fs.readFileSync(lockPath(home), 'utf8'));
13
+ if (typeof parsed !== 'object' || parsed === null)
14
+ return undefined;
15
+ const record = parsed;
16
+ if (typeof record.pid !== 'number' || !Number.isInteger(record.pid))
17
+ return undefined;
18
+ return { pid: record.pid, startedAt: record.startedAt ?? 0, protocol: record.protocol ?? 0, socket: record.socket ?? '' };
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /** Whether a process with that pid still runs. EPERM counts as alive. */
25
+ export function isAlive(pid) {
26
+ if (!Number.isInteger(pid) || pid <= 0)
27
+ return false;
28
+ try {
29
+ process.kill(pid, 0);
30
+ return true;
31
+ }
32
+ catch (error) {
33
+ return error.code === 'EPERM';
34
+ }
35
+ }
36
+ /** Take the lock, or report the live daemon that holds it. */
37
+ export function acquire(home, socketPath, pid = process.pid, alive = isAlive) {
38
+ fs.mkdirSync(home, { recursive: true });
39
+ const target = lockPath(home);
40
+ const record = { pid, startedAt: Date.now(), protocol: DAEMON_PROTOCOL, socket: socketPath };
41
+ for (let attempt = 0; attempt < 2; attempt += 1) {
42
+ try {
43
+ const fd = fs.openSync(target, 'wx', 0o600);
44
+ fs.writeSync(fd, `${JSON.stringify(record)}\n`);
45
+ fs.closeSync(fd);
46
+ return { kind: 'acquired' };
47
+ }
48
+ catch (error) {
49
+ if (error.code !== 'EEXIST')
50
+ throw error;
51
+ const held = readLock(home);
52
+ if (held && alive(held.pid))
53
+ return { kind: 'held', record: held };
54
+ fs.rmSync(target, { force: true });
55
+ }
56
+ }
57
+ const held = readLock(home);
58
+ if (held && alive(held.pid))
59
+ return { kind: 'held', record: held };
60
+ throw new Error('the daemon lock could not be taken');
61
+ }
62
+ /** Remove the lock when this process owns it. */
63
+ export function release(home, pid = process.pid) {
64
+ const held = readLock(home);
65
+ if (held && held.pid !== pid)
66
+ return;
67
+ fs.rmSync(lockPath(home), { force: true });
68
+ }
@@ -0,0 +1,40 @@
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 fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { startDaemon } from './server.js';
7
+ const log = (message) => console.error('[bellwether-daemon]', message);
8
+ function flag(argv, name) {
9
+ const index = argv.indexOf(name);
10
+ return index >= 0 ? argv[index + 1] : undefined;
11
+ }
12
+ async function main() {
13
+ const argv = process.argv.slice(2);
14
+ const home = process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
15
+ const socketPath = flag(argv, '--socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(home, 'daemon.sock');
16
+ // Whichever session starts the daemon lends it its working directory, and a
17
+ // child's is the worktree the daemon may later remove. Work from the home,
18
+ // so the daemon never counts as a process inside a worktree.
19
+ fs.mkdirSync(home, { recursive: true });
20
+ process.chdir(home);
21
+ const idleMs = Number.parseInt(process.env['BELLWETHER_DAEMON_IDLE_MS'] ?? '', 10);
22
+ const daemon = await startDaemon({
23
+ socketPath,
24
+ home,
25
+ log,
26
+ ...(Number.isFinite(idleMs) ? { idleMs } : {}),
27
+ });
28
+ log(`listening on ${socketPath} with pid ${daemon.pid}`);
29
+ const stop = () => {
30
+ void daemon.close().then(() => process.exit(0));
31
+ };
32
+ process.on('SIGTERM', stop);
33
+ process.on('SIGINT', stop);
34
+ await daemon.whenClosed();
35
+ process.exit(0);
36
+ }
37
+ main().catch((error) => {
38
+ log(error.message);
39
+ process.exit(1);
40
+ });
@@ -0,0 +1,104 @@
1
+ // 2: a call carries the caller identity, and parent_report routes by it.
2
+ export const DAEMON_PROTOCOL = 2;
3
+ /** The largest line a daemon or client will read, matching the herdr client. */
4
+ export const MAX_DAEMON_FRAME_BYTES = 4 * 1024 * 1024;
5
+ export class ProtocolError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = 'ProtocolError';
10
+ this.code = code;
11
+ }
12
+ }
13
+ function isRecord(value) {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ }
16
+ function text(value) {
17
+ return typeof value === 'string' ? value.trim() : '';
18
+ }
19
+ /** Parse one request line, or throw a ProtocolError that names the fault. */
20
+ export function parseRequest(line) {
21
+ let value;
22
+ try {
23
+ value = JSON.parse(line);
24
+ }
25
+ catch {
26
+ throw new ProtocolError('invalid_json', 'the line is not JSON');
27
+ }
28
+ if (!isRecord(value))
29
+ throw new ProtocolError('invalid_request', 'the line is not an object');
30
+ switch (value['type']) {
31
+ case 'hello':
32
+ return parseHello(value);
33
+ case 'call': {
34
+ const id = text(value['id']);
35
+ const tool = text(value['tool']);
36
+ if (!id || !tool)
37
+ throw new ProtocolError('invalid_call', 'a call needs an id and a tool');
38
+ const args = isRecord(value['args']) ? value['args'] : {};
39
+ const caller = parseCaller(value['caller']);
40
+ return caller ? { type: 'call', id, tool, args, caller } : { type: 'call', id, tool, args };
41
+ }
42
+ case 'receipt': {
43
+ const receipts = Array.isArray(value['receipts']) ? value['receipts'].filter((entry) => typeof entry === 'string' && entry.length > 0) : [];
44
+ return { type: 'receipt', receipts };
45
+ }
46
+ case 'bye':
47
+ return { type: 'bye' };
48
+ case 'drain':
49
+ return { type: 'drain' };
50
+ case 'watch': {
51
+ const paneId = text(value['paneId']);
52
+ if (!paneId)
53
+ throw new ProtocolError('invalid_watch', 'a watch needs a pane id');
54
+ return { type: 'watch', paneId };
55
+ }
56
+ default:
57
+ throw new ProtocolError('unknown_type', `unknown request type ${JSON.stringify(value['type'])}`);
58
+ }
59
+ }
60
+ function parseCaller(value) {
61
+ if (!isRecord(value))
62
+ return undefined;
63
+ const caller = {};
64
+ const childId = text(value['childId']);
65
+ const paneId = text(value['paneId']);
66
+ if (childId)
67
+ caller.childId = childId;
68
+ if (paneId)
69
+ caller.paneId = paneId;
70
+ return caller;
71
+ }
72
+ function parseHello(value) {
73
+ const protocol = value['protocol'];
74
+ const parent = value['parent'];
75
+ if (typeof protocol !== 'number' || !Number.isInteger(protocol))
76
+ throw new ProtocolError('invalid_hello', 'a hello needs an integer protocol');
77
+ if (!isRecord(parent))
78
+ throw new ProtocolError('invalid_hello', 'a hello needs a parent');
79
+ const harness = parent['harness'];
80
+ const session = text(parent['session']);
81
+ const cwd = text(parent['cwd']);
82
+ const host = text(parent['host']);
83
+ const herdrSocket = text(parent['herdrSocket']);
84
+ if (harness !== 'pi' && harness !== 'claude-code')
85
+ throw new ProtocolError('invalid_hello', 'the parent harness must be pi or claude-code');
86
+ if (!session || !cwd || !host || !herdrSocket)
87
+ throw new ProtocolError('invalid_hello', 'the parent needs a session, cwd, host and herdr socket');
88
+ const depth = typeof parent['depth'] === 'number' && Number.isFinite(parent['depth']) ? parent['depth'] : 0;
89
+ const optional = (key) => (typeof parent[key] === 'string' && parent[key] ? parent[key] : undefined);
90
+ return {
91
+ type: 'hello',
92
+ protocol,
93
+ client: text(value['client']) || 'unknown',
94
+ parent: { harness, session, cwd, host, depth, herdrSocket, paneId: optional('paneId'), workspaceId: optional('workspaceId'), childId: optional('childId') },
95
+ };
96
+ }
97
+ /** One reply line, without its newline. */
98
+ export function formatReply(reply) {
99
+ return `${JSON.stringify(reply)}\n`;
100
+ }
101
+ /** One request line, without its newline. */
102
+ export function formatRequest(request) {
103
+ return `${JSON.stringify(request)}\n`;
104
+ }