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