@elecnix/bellwether 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +106 -2
- 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 +47 -4
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
// The herdr socket client: newline-delimited JSON, one connection per request,
|
|
2
|
+
// and one held-open connection for the subscription. The subscription checks
|
|
3
|
+
// the `subscription_started` acknowledgement and buffers frames that arrive
|
|
4
|
+
// before it, because herdr can deliver an event in the same read as the ack.
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
export const MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
const MAX_PENDING_EVENTS = 4096;
|
|
10
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
11
|
+
export const AGENT_STATUSES = ['idle', 'working', 'blocked', 'done', 'unknown'];
|
|
12
|
+
export class HerdrApiError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(`herdr ${message}`);
|
|
16
|
+
this.name = 'HerdrApiError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
let sequence = 0;
|
|
21
|
+
export function nextRequestId(prefix = 'bellwether') {
|
|
22
|
+
sequence += 1;
|
|
23
|
+
return `${prefix}:${process.pid}:${sequence}`;
|
|
24
|
+
}
|
|
25
|
+
function isRecord(value) {
|
|
26
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
27
|
+
}
|
|
28
|
+
/** herdr's own config root, which is also where a named session's socket lives. */
|
|
29
|
+
export function configHome() {
|
|
30
|
+
return process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config');
|
|
31
|
+
}
|
|
32
|
+
function sessionSocket(session) {
|
|
33
|
+
return path.join(configHome(), 'herdr', 'sessions', session, 'herdr.sock');
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* herdr's documented socket order: an explicit path, then the session flag,
|
|
37
|
+
* then HERDR_SOCKET_PATH, then HERDR_SESSION, then the default session.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveSocketPath(options = {}) {
|
|
40
|
+
if (options.socketPath)
|
|
41
|
+
return options.socketPath;
|
|
42
|
+
if (options.session)
|
|
43
|
+
return sessionSocket(options.session);
|
|
44
|
+
const fromEnv = process.env['HERDR_SOCKET_PATH'];
|
|
45
|
+
if (fromEnv)
|
|
46
|
+
return fromEnv;
|
|
47
|
+
const envSession = process.env['HERDR_SESSION'];
|
|
48
|
+
if (envSession)
|
|
49
|
+
return sessionSocket(envSession);
|
|
50
|
+
return path.join(configHome(), 'herdr', 'herdr.sock');
|
|
51
|
+
}
|
|
52
|
+
class NdjsonFrames {
|
|
53
|
+
buffer = Buffer.alloc(0);
|
|
54
|
+
push(chunk) {
|
|
55
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
56
|
+
const frames = [];
|
|
57
|
+
for (;;) {
|
|
58
|
+
const newline = this.buffer.indexOf(0x0a);
|
|
59
|
+
if (newline < 0)
|
|
60
|
+
break;
|
|
61
|
+
const line = this.buffer.subarray(0, newline);
|
|
62
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
63
|
+
if (line.length === 0)
|
|
64
|
+
continue;
|
|
65
|
+
if (line.length > MAX_FRAME_BYTES)
|
|
66
|
+
throw new Error('herdr sent a frame over the size limit');
|
|
67
|
+
frames.push(JSON.parse(line.toString('utf8')));
|
|
68
|
+
}
|
|
69
|
+
if (this.buffer.length > MAX_FRAME_BYTES)
|
|
70
|
+
throw new Error('herdr sent a frame over the size limit');
|
|
71
|
+
return frames;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function errorFrom(frame) {
|
|
75
|
+
if (!('error' in frame))
|
|
76
|
+
return undefined;
|
|
77
|
+
const error = frame.error;
|
|
78
|
+
if (!isRecord(error))
|
|
79
|
+
return new HerdrApiError(undefined, 'returned an invalid error');
|
|
80
|
+
return new HerdrApiError(typeof error['code'] === 'string' ? error['code'] : undefined, typeof error['message'] === 'string' ? error['message'] : 'request failed');
|
|
81
|
+
}
|
|
82
|
+
/** One request on its own connection, resolving with `result` or rejecting with HerdrApiError. */
|
|
83
|
+
export function requestHerdr(socketPath, request, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
if (signal?.aborted)
|
|
86
|
+
return reject(new Error('herdr request aborted'));
|
|
87
|
+
const socket = net.createConnection(socketPath);
|
|
88
|
+
const frames = new NdjsonFrames();
|
|
89
|
+
let settled = false;
|
|
90
|
+
const timer = setTimeout(() => finish(new Error(`herdr ${request.method} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
91
|
+
timer.unref?.();
|
|
92
|
+
const cleanup = () => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
signal?.removeEventListener('abort', onAbort);
|
|
95
|
+
socket.destroy();
|
|
96
|
+
};
|
|
97
|
+
const finish = (error, value) => {
|
|
98
|
+
if (settled)
|
|
99
|
+
return;
|
|
100
|
+
settled = true;
|
|
101
|
+
cleanup();
|
|
102
|
+
if (error)
|
|
103
|
+
reject(error);
|
|
104
|
+
else
|
|
105
|
+
resolve(value);
|
|
106
|
+
};
|
|
107
|
+
const onAbort = () => finish(new Error('herdr request aborted'));
|
|
108
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
109
|
+
socket.on('connect', () => socket.write(`${JSON.stringify(request)}\n`));
|
|
110
|
+
socket.on('error', (error) => finish(error));
|
|
111
|
+
socket.on('end', () => finish(new Error(`herdr closed the connection before answering ${request.method}`)));
|
|
112
|
+
socket.on('data', (chunk) => {
|
|
113
|
+
if (settled)
|
|
114
|
+
return;
|
|
115
|
+
try {
|
|
116
|
+
for (const frame of frames.push(chunk)) {
|
|
117
|
+
if (!isRecord(frame))
|
|
118
|
+
continue;
|
|
119
|
+
const error = errorFrom(frame);
|
|
120
|
+
if (error && (frame['id'] === undefined || frame['id'] === ''))
|
|
121
|
+
return finish(error);
|
|
122
|
+
if (frame['id'] !== request.id)
|
|
123
|
+
continue;
|
|
124
|
+
if (error)
|
|
125
|
+
return finish(error);
|
|
126
|
+
if (!('result' in frame))
|
|
127
|
+
return finish(new Error(`herdr ${request.method} answered without a result`));
|
|
128
|
+
return finish(undefined, frame['result']);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Hold a subscription open. Frames that arrive before the acknowledgement are
|
|
139
|
+
* buffered and replayed, so no event is lost between connect and ack.
|
|
140
|
+
*/
|
|
141
|
+
export function openHerdrSubscription(socketPath, request, onEvent, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
if (signal.aborted)
|
|
144
|
+
return reject(new Error('herdr subscription aborted'));
|
|
145
|
+
const socket = net.createConnection(socketPath);
|
|
146
|
+
const frames = new NdjsonFrames();
|
|
147
|
+
const pending = [];
|
|
148
|
+
let ready = false;
|
|
149
|
+
let finished = false;
|
|
150
|
+
let intentional = false;
|
|
151
|
+
let resolveClosed = () => { };
|
|
152
|
+
let rejectClosed = () => { };
|
|
153
|
+
const closed = new Promise((res, rej) => {
|
|
154
|
+
resolveClosed = res;
|
|
155
|
+
rejectClosed = rej;
|
|
156
|
+
});
|
|
157
|
+
void closed.catch(() => undefined);
|
|
158
|
+
const timer = setTimeout(() => finish(new Error('herdr subscription was not acknowledged')), timeoutMs);
|
|
159
|
+
timer.unref?.();
|
|
160
|
+
function teardown() {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
signal.removeEventListener('abort', onAbort);
|
|
163
|
+
socket.destroy();
|
|
164
|
+
}
|
|
165
|
+
/** End the subscription. Before the ack it rejects the caller; after it, it closes. */
|
|
166
|
+
function finish(error) {
|
|
167
|
+
if (finished)
|
|
168
|
+
return;
|
|
169
|
+
finished = true;
|
|
170
|
+
teardown();
|
|
171
|
+
if (!ready) {
|
|
172
|
+
reject(error ?? new Error('herdr subscription aborted'));
|
|
173
|
+
resolveClosed();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (error && !intentional)
|
|
177
|
+
rejectClosed(error);
|
|
178
|
+
else
|
|
179
|
+
resolveClosed();
|
|
180
|
+
}
|
|
181
|
+
function onAbort() {
|
|
182
|
+
intentional = true;
|
|
183
|
+
finish();
|
|
184
|
+
}
|
|
185
|
+
function deliver(event) {
|
|
186
|
+
if (finished)
|
|
187
|
+
return;
|
|
188
|
+
try {
|
|
189
|
+
onEvent(event);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function handle(frame) {
|
|
196
|
+
if (isRecord(frame)) {
|
|
197
|
+
const error = errorFrom(frame);
|
|
198
|
+
const id = frame['id'];
|
|
199
|
+
if (error && (id === request.id || id === undefined || id === ''))
|
|
200
|
+
return finish(error);
|
|
201
|
+
if (id !== undefined && id !== '' && id !== request.id)
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (!ready) {
|
|
205
|
+
if (isRecord(frame) && frame['id'] === request.id) {
|
|
206
|
+
if (!isRecord(frame['result']) || frame['result']['type'] !== 'subscription_started') {
|
|
207
|
+
return finish(new Error('herdr returned an invalid subscription acknowledgement'));
|
|
208
|
+
}
|
|
209
|
+
ready = true;
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
socket.unref();
|
|
212
|
+
resolve({ close() { intentional = true; finish(); }, closed });
|
|
213
|
+
for (const event of pending.splice(0))
|
|
214
|
+
deliver(event);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (pending.length >= MAX_PENDING_EVENTS)
|
|
218
|
+
return finish(new Error('too many herdr events arrived before the acknowledgement'));
|
|
219
|
+
if (isRecord(frame) && typeof frame['event'] === 'string')
|
|
220
|
+
pending.push({ event: frame['event'], data: isRecord(frame['data']) ? frame['data'] : {} });
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (isRecord(frame) && typeof frame['event'] === 'string')
|
|
224
|
+
deliver({ event: frame['event'], data: isRecord(frame['data']) ? frame['data'] : {} });
|
|
225
|
+
}
|
|
226
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
227
|
+
socket.on('connect', () => socket.write(`${JSON.stringify(request)}\n`));
|
|
228
|
+
socket.on('error', (error) => finish(error));
|
|
229
|
+
socket.on('end', () => finish(intentional ? undefined : new Error('herdr closed the subscription')));
|
|
230
|
+
socket.on('data', (chunk) => {
|
|
231
|
+
if (finished)
|
|
232
|
+
return;
|
|
233
|
+
try {
|
|
234
|
+
for (const frame of frames.push(chunk)) {
|
|
235
|
+
if (finished)
|
|
236
|
+
return;
|
|
237
|
+
handle(frame);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
function optionalString(value) {
|
|
247
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
248
|
+
}
|
|
249
|
+
function optionalNumber(value) {
|
|
250
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
251
|
+
}
|
|
252
|
+
function agentStatus(value) {
|
|
253
|
+
return typeof value === 'string' && AGENT_STATUSES.includes(value) ? value : undefined;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The text of a pane.read answer. herdr nests it: the frame is
|
|
257
|
+
* `{type: 'pane_read', read: {pane_id, source, format, text}}`.
|
|
258
|
+
*/
|
|
259
|
+
export function paneText(result) {
|
|
260
|
+
if (typeof result === 'string')
|
|
261
|
+
return result;
|
|
262
|
+
if (isRecord(result)) {
|
|
263
|
+
const read = result['read'];
|
|
264
|
+
if (isRecord(read) && typeof read['text'] === 'string')
|
|
265
|
+
return read['text'];
|
|
266
|
+
if (typeof result['text'] === 'string')
|
|
267
|
+
return result['text'];
|
|
268
|
+
}
|
|
269
|
+
return '';
|
|
270
|
+
}
|
|
271
|
+
/** Read the fields Bellwether needs, and nothing else, from a raw pane object. */
|
|
272
|
+
export function parsePane(value) {
|
|
273
|
+
if (!isRecord(value))
|
|
274
|
+
return undefined;
|
|
275
|
+
const paneId = optionalString(value['pane_id']);
|
|
276
|
+
const workspaceId = optionalString(value['workspace_id']);
|
|
277
|
+
const tabId = optionalString(value['tab_id']);
|
|
278
|
+
const terminalId = optionalString(value['terminal_id']);
|
|
279
|
+
const status = agentStatus(value['agent_status']);
|
|
280
|
+
if (!paneId || !workspaceId || !tabId || !terminalId || !status)
|
|
281
|
+
return undefined;
|
|
282
|
+
const session = isRecord(value['agent_session']) ? optionalString(value['agent_session']['value']) : undefined;
|
|
283
|
+
return {
|
|
284
|
+
paneId,
|
|
285
|
+
workspaceId,
|
|
286
|
+
tabId,
|
|
287
|
+
terminalId,
|
|
288
|
+
focused: value['focused'] === true,
|
|
289
|
+
revision: optionalNumber(value['revision']) ?? 0,
|
|
290
|
+
cwd: optionalString(value['foreground_cwd']) ?? optionalString(value['cwd']),
|
|
291
|
+
agent: optionalString(value['agent']),
|
|
292
|
+
name: optionalString(value['name']),
|
|
293
|
+
agentStatus: status,
|
|
294
|
+
agentSessionId: session,
|
|
295
|
+
completionSeq: optionalNumber(value['completion_seq']),
|
|
296
|
+
terminalTitle: optionalString(value['terminal_title_stripped']) ?? optionalString(value['terminal_title']),
|
|
297
|
+
label: optionalString(value['label']),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/** A thin typed wrapper over one herdr socket. */
|
|
301
|
+
export class HerdrClient {
|
|
302
|
+
socketPath;
|
|
303
|
+
constructor(options = {}) {
|
|
304
|
+
this.socketPath = resolveSocketPath(options);
|
|
305
|
+
}
|
|
306
|
+
request(method, params = {}, options = {}) {
|
|
307
|
+
return requestHerdr(this.socketPath, { id: options.id ?? nextRequestId(), method, params }, options.signal, options.timeoutMs);
|
|
308
|
+
}
|
|
309
|
+
async agentList(signal) {
|
|
310
|
+
const result = await this.request('agent.list', {}, { signal });
|
|
311
|
+
if (!isRecord(result) || !Array.isArray(result['agents']))
|
|
312
|
+
throw new Error('herdr returned an invalid agent list');
|
|
313
|
+
return result['agents'].map(parsePane).filter((pane) => pane !== undefined);
|
|
314
|
+
}
|
|
315
|
+
async paneList(signal) {
|
|
316
|
+
const result = await this.request('pane.list', {}, { signal });
|
|
317
|
+
if (!isRecord(result) || !Array.isArray(result['panes']))
|
|
318
|
+
throw new Error('herdr returned an invalid pane list');
|
|
319
|
+
return result['panes'].map(parsePane).filter((pane) => pane !== undefined);
|
|
320
|
+
}
|
|
321
|
+
snapshot(signal) {
|
|
322
|
+
return this.request('session.snapshot', {}, { signal }).then((result) => (isRecord(result) ? result : {}));
|
|
323
|
+
}
|
|
324
|
+
tabCreate(params, signal) {
|
|
325
|
+
return this.request('tab.create', {
|
|
326
|
+
workspace_id: params.workspaceId ?? null,
|
|
327
|
+
cwd: params.cwd ?? null,
|
|
328
|
+
label: params.label ?? null,
|
|
329
|
+
env: params.env ?? {},
|
|
330
|
+
focus: params.focus ?? false,
|
|
331
|
+
}, { signal }).then((result) => {
|
|
332
|
+
if (!isRecord(result))
|
|
333
|
+
return {};
|
|
334
|
+
const tab = isRecord(result['tab']) ? result['tab'] : undefined;
|
|
335
|
+
// herdr answers with root_pane; keep the pane alias for older servers.
|
|
336
|
+
const pane = isRecord(result['root_pane']) ? result['root_pane'] : isRecord(result['pane']) ? result['pane'] : undefined;
|
|
337
|
+
return { tabId: optionalString(tab?.['tab_id']), paneId: optionalString(pane?.['pane_id']) };
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
agentStart(params, signal) {
|
|
341
|
+
return this.request('agent.start', { name: params.name, kind: params.kind, pane_id: params.paneId, args: params.args ?? [], timeout_ms: params.timeoutMs ?? null }, { signal }).then(() => undefined);
|
|
342
|
+
}
|
|
343
|
+
async paneRead(params, signal) {
|
|
344
|
+
const result = await this.request('pane.read', { pane_id: params.paneId, source: params.source, lines: params.lines ?? null, format: 'text' }, { signal, timeoutMs: 8000 });
|
|
345
|
+
return paneText(result);
|
|
346
|
+
}
|
|
347
|
+
agentPrompt(target, text, signal) {
|
|
348
|
+
return this.request('agent.prompt', { target, text }, { signal, timeoutMs: 12000 }).then(() => undefined);
|
|
349
|
+
}
|
|
350
|
+
sendKeys(target, keys, signal) {
|
|
351
|
+
return this.request('agent.send_keys', { target, keys }, { signal }).then(() => undefined);
|
|
352
|
+
}
|
|
353
|
+
paneClose(paneId, signal) {
|
|
354
|
+
return this.request('pane.close', { pane_id: paneId }, { signal }).then(() => undefined);
|
|
355
|
+
}
|
|
356
|
+
tabClose(tabId, signal) {
|
|
357
|
+
return this.request('tab.close', { tab_id: tabId }, { signal }).then(() => undefined);
|
|
358
|
+
}
|
|
359
|
+
workspaceList(signal) {
|
|
360
|
+
return this.request('workspace.list', {}, { signal }).then((result) => (isRecord(result) && Array.isArray(result['workspaces']) ? result['workspaces'] : []));
|
|
361
|
+
}
|
|
362
|
+
paneCurrent(signal) {
|
|
363
|
+
return this.request('pane.current', {}, { signal }).then((result) => (isRecord(result) ? parsePane(result['pane']) : undefined));
|
|
364
|
+
}
|
|
365
|
+
subscribe(subscriptions, onEvent, signal, timeoutMs) {
|
|
366
|
+
return openHerdrSubscription(this.socketPath, { id: nextRequestId('sub'), method: 'events.subscribe', params: { subscriptions } }, onEvent, signal, timeoutMs);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The outbox: one pending entry per child, where a newer state replaces an
|
|
2
|
+
// older one, and an entry counts as read once its receipt id reaches the
|
|
3
|
+
// parent's model context. It survives a restart on disk, because a parent
|
|
4
|
+
// session that resumes still owes its children an answer.
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { outboxPath } from './paths.js';
|
|
9
|
+
export function newReceipt() {
|
|
10
|
+
return `bw-${crypto.randomBytes(6).toString('hex')}`;
|
|
11
|
+
}
|
|
12
|
+
export function newChildId() {
|
|
13
|
+
return crypto.randomBytes(8).toString('hex');
|
|
14
|
+
}
|
|
15
|
+
export class Outbox {
|
|
16
|
+
entries = [];
|
|
17
|
+
constructor(entries) {
|
|
18
|
+
this.entries = entries;
|
|
19
|
+
}
|
|
20
|
+
static load(id) {
|
|
21
|
+
try {
|
|
22
|
+
const parsed = JSON.parse(fs.readFileSync(outboxPath(id), 'utf8'));
|
|
23
|
+
return new Outbox(Array.isArray(parsed) ? parsed : []);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return new Outbox([]);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
save(id) {
|
|
30
|
+
const target = outboxPath(id);
|
|
31
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
32
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
33
|
+
fs.writeFileSync(temp, `${JSON.stringify(this.entries, null, 2)}\n`);
|
|
34
|
+
fs.renameSync(temp, target);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Offer an event for a child. A newer event replaces an older unread one, so
|
|
38
|
+
* a child that goes quiet then blocked produces one message, not two.
|
|
39
|
+
*/
|
|
40
|
+
offer(entry) {
|
|
41
|
+
const existing = this.entries.find((candidate) => candidate.childId === entry.childId && !candidate.read);
|
|
42
|
+
const next = { ...entry, receipt: newReceipt(), read: false };
|
|
43
|
+
if (existing)
|
|
44
|
+
Object.assign(existing, next);
|
|
45
|
+
else
|
|
46
|
+
this.entries.push(next);
|
|
47
|
+
return existing ?? next;
|
|
48
|
+
}
|
|
49
|
+
add(entry) {
|
|
50
|
+
if (this.entries.some((candidate) => candidate.receipt === entry.receipt))
|
|
51
|
+
return;
|
|
52
|
+
this.entries.push(entry);
|
|
53
|
+
}
|
|
54
|
+
/** Mark an entry read. A repeated receipt is not an error; it returns false. */
|
|
55
|
+
markRead(receipt) {
|
|
56
|
+
const entry = this.entries.find((candidate) => candidate.receipt === receipt);
|
|
57
|
+
if (!entry || entry.read)
|
|
58
|
+
return false;
|
|
59
|
+
entry.read = true;
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
markDelivered(receipt, at = new Date().toISOString()) {
|
|
63
|
+
const entry = this.entries.find((candidate) => candidate.receipt === receipt);
|
|
64
|
+
if (entry)
|
|
65
|
+
entry.deliveredAt = at;
|
|
66
|
+
}
|
|
67
|
+
pending() {
|
|
68
|
+
return this.entries.filter((entry) => !entry.read);
|
|
69
|
+
}
|
|
70
|
+
unreadFor(childId) {
|
|
71
|
+
return this.entries.filter((entry) => !entry.read && entry.childId === childId);
|
|
72
|
+
}
|
|
73
|
+
all() {
|
|
74
|
+
return [...this.entries];
|
|
75
|
+
}
|
|
76
|
+
/** Drop read entries older than a day, so the file does not grow forever. */
|
|
77
|
+
prune(now = Date.now(), maxAgeMs = 24 * 60 * 60_000) {
|
|
78
|
+
this.entries = this.entries.filter((entry) => !entry.read || now - Date.parse(entry.at) < maxAgeMs);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
/** Every Bellwether file lives under one directory, overridable for tests. */
|
|
4
|
+
export function bellwetherHome() {
|
|
5
|
+
return process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
|
|
6
|
+
}
|
|
7
|
+
export function parentsDir() {
|
|
8
|
+
return path.join(bellwetherHome(), 'parents');
|
|
9
|
+
}
|
|
10
|
+
export function outboxDir() {
|
|
11
|
+
return path.join(bellwetherHome(), 'outbox');
|
|
12
|
+
}
|
|
13
|
+
export function spoolDir() {
|
|
14
|
+
return path.join(bellwetherHome(), 'spool');
|
|
15
|
+
}
|
|
16
|
+
/** One registry file per parent session, so a resumed parent reads the same file. */
|
|
17
|
+
export function parentId(harness, session) {
|
|
18
|
+
return `${harness}-${slug(session)}`;
|
|
19
|
+
}
|
|
20
|
+
export function registryPath(id) {
|
|
21
|
+
return path.join(parentsDir(), `${slug(id)}.json`);
|
|
22
|
+
}
|
|
23
|
+
export function outboxPath(id) {
|
|
24
|
+
return path.join(outboxDir(), `${slug(id)}.json`);
|
|
25
|
+
}
|
|
26
|
+
export function spoolPath(id) {
|
|
27
|
+
return path.join(spoolDir(), `${slug(id)}.jsonl`);
|
|
28
|
+
}
|
|
29
|
+
/** A herdr-safe handle: no separators, no spaces, nothing that needs quoting. */
|
|
30
|
+
export function slug(value) {
|
|
31
|
+
return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 120) || 'unnamed';
|
|
32
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The registry: one JSON file per parent session, under ~/.bellwether/parents.
|
|
2
|
+
// A child record is written before herdr is asked to create anything, so a
|
|
3
|
+
// crash mid-spawn still says what was asked for. A resumed parent reads the
|
|
4
|
+
// same file, which is why the file is named after the session and not the pid.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { parentId, parentsDir, registryPath, slug } from './paths.js';
|
|
8
|
+
export { parentId, slug };
|
|
9
|
+
function ensure(dir) {
|
|
10
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
11
|
+
}
|
|
12
|
+
export function emptyParent(harness, session, cwd, extra = {}) {
|
|
13
|
+
return {
|
|
14
|
+
id: parentId(harness, session),
|
|
15
|
+
harness,
|
|
16
|
+
session,
|
|
17
|
+
host: extra.host ?? 'unknown',
|
|
18
|
+
cwd,
|
|
19
|
+
depth: extra.depth ?? 0,
|
|
20
|
+
children: [],
|
|
21
|
+
updatedAt: new Date().toISOString(),
|
|
22
|
+
...extra,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function readParent(id) {
|
|
26
|
+
try {
|
|
27
|
+
const raw = fs.readFileSync(registryPath(id), 'utf8');
|
|
28
|
+
const parsed = JSON.parse(raw);
|
|
29
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
30
|
+
return undefined;
|
|
31
|
+
const record = parsed;
|
|
32
|
+
if (!Array.isArray(record.children))
|
|
33
|
+
record.children = [];
|
|
34
|
+
return record;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function listParents() {
|
|
41
|
+
let files;
|
|
42
|
+
try {
|
|
43
|
+
files = fs.readdirSync(parentsDir());
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
return files
|
|
49
|
+
.filter((file) => file.endsWith('.json'))
|
|
50
|
+
.map((file) => readParent(file.slice(0, -'.json'.length)))
|
|
51
|
+
.filter((record) => record !== undefined);
|
|
52
|
+
}
|
|
53
|
+
/** Write atomically: a reader never sees a half-written registry. */
|
|
54
|
+
export function saveParent(record) {
|
|
55
|
+
ensure(path.dirname(registryPath(record.id)));
|
|
56
|
+
record.updatedAt = new Date().toISOString();
|
|
57
|
+
const target = registryPath(record.id);
|
|
58
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
59
|
+
fs.writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`);
|
|
60
|
+
fs.renameSync(temp, target);
|
|
61
|
+
return record;
|
|
62
|
+
}
|
|
63
|
+
/** Read, change and write one registry in a single step. */
|
|
64
|
+
export function mutateParent(id, change) {
|
|
65
|
+
const record = readParent(id);
|
|
66
|
+
if (!record)
|
|
67
|
+
return undefined;
|
|
68
|
+
change(record);
|
|
69
|
+
return saveParent(record);
|
|
70
|
+
}
|
|
71
|
+
export function upsertChild(id, child) {
|
|
72
|
+
return mutateParent(id, (record) => {
|
|
73
|
+
const index = record.children.findIndex((entry) => entry.id === child.id);
|
|
74
|
+
if (index < 0)
|
|
75
|
+
record.children.push(child);
|
|
76
|
+
else
|
|
77
|
+
record.children[index] = child;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export function updateChild(id, childId, change) {
|
|
81
|
+
let updated;
|
|
82
|
+
mutateParent(id, (record) => {
|
|
83
|
+
const child = record.children.find((entry) => entry.id === childId);
|
|
84
|
+
if (!child)
|
|
85
|
+
return;
|
|
86
|
+
change(child);
|
|
87
|
+
updated = child;
|
|
88
|
+
});
|
|
89
|
+
return updated;
|
|
90
|
+
}
|
|
91
|
+
export function childById(record, childId) {
|
|
92
|
+
return record.children.find((child) => child.id === childId || child.name === childId || child.paneId === childId);
|
|
93
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// parent_report: a child appends one JSON line to its parent's spool file.
|
|
2
|
+
// A file keeps the child and the parent independent: either process can die
|
|
3
|
+
// and the report still waits for the other one.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { spoolPath } from './paths.js';
|
|
7
|
+
import { readParent } from './registry.js';
|
|
8
|
+
export function harnessForEnv() {
|
|
9
|
+
if (process.env['BELLWETHER_HARNESS'])
|
|
10
|
+
return process.env['BELLWETHER_HARNESS'];
|
|
11
|
+
if (process.env['CLAUDE_CODE_SESSION_ID'])
|
|
12
|
+
return 'claude-code';
|
|
13
|
+
return 'pi';
|
|
14
|
+
}
|
|
15
|
+
/** The parent id this session's environment points at, if any. */
|
|
16
|
+
export function parentFromEnv() {
|
|
17
|
+
return process.env['BELLWETHER_PARENT'];
|
|
18
|
+
}
|
|
19
|
+
export function childFromEnv() {
|
|
20
|
+
return process.env['BELLWETHER_CHILD'];
|
|
21
|
+
}
|
|
22
|
+
export function depthFromEnv() {
|
|
23
|
+
const value = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10);
|
|
24
|
+
return Number.isFinite(value) ? value : 0;
|
|
25
|
+
}
|
|
26
|
+
/** Append one report to the parent's spool, creating the directory if needed. */
|
|
27
|
+
export function writeReport(report) {
|
|
28
|
+
const target = spoolPath(report.parentId);
|
|
29
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
30
|
+
const seq = report.seq ?? Date.now();
|
|
31
|
+
const entry = { ...report, at: report.at ?? new Date().toISOString(), seq };
|
|
32
|
+
fs.appendFileSync(target, `${JSON.stringify(entry)}\n`);
|
|
33
|
+
return entry;
|
|
34
|
+
}
|
|
35
|
+
/** Report to the parent named in this session's environment. */
|
|
36
|
+
export function reportToParent(status, text) {
|
|
37
|
+
const parentId = parentFromEnv();
|
|
38
|
+
if (!parentId)
|
|
39
|
+
return undefined;
|
|
40
|
+
const parent = readParent(parentId);
|
|
41
|
+
return writeReport({
|
|
42
|
+
parentId,
|
|
43
|
+
parentPaneId: parent?.paneId,
|
|
44
|
+
childId: childFromEnv(),
|
|
45
|
+
childName: process.env['BELLWETHER_CHILD_NAME'] ?? 'child',
|
|
46
|
+
paneId: process.env['HERDR_PANE_ID'],
|
|
47
|
+
status,
|
|
48
|
+
text,
|
|
49
|
+
});
|
|
50
|
+
}
|