@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
package/src/daemon/server.ts
DELETED
|
@@ -1,275 +0,0 @@
|
|
|
1
|
-
// The daemon: one local socket that owns a herdr subscription, a registry and
|
|
2
|
-
// an outbox for every parent session on the machine. A client says hello, gets
|
|
3
|
-
// the events it missed, runs the Bellwether tools through the daemon, and marks
|
|
4
|
-
// receipts read. The daemon starts on demand, drains for an upgrade, and exits
|
|
5
|
-
// when no session needs it.
|
|
6
|
-
import fs from 'node:fs';
|
|
7
|
-
import net from 'node:net';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import { DAEMON_PROTOCOL, MAX_DAEMON_FRAME_BYTES, ProtocolError, formatReply, parseRequest, type DaemonReply, type ParentHello } from './protocol.ts';
|
|
10
|
-
import { defaultServiceFactory, parentIdOf, type ParentService, type ServiceFactory } from './service.ts';
|
|
11
|
-
import { acquire, isAlive, readLock, release } from './lock.ts';
|
|
12
|
-
import type { OutboxEntry } from '../core/types.ts';
|
|
13
|
-
|
|
14
|
-
export type { ParentService, ServiceFactory } from './service.ts';
|
|
15
|
-
|
|
16
|
-
export interface DaemonOptions {
|
|
17
|
-
socketPath: string;
|
|
18
|
-
/** The home whose lock and registry the daemon uses. */
|
|
19
|
-
home?: string;
|
|
20
|
-
/** Exit after this long with no client and no call. Default 5 min. */
|
|
21
|
-
idleMs?: number;
|
|
22
|
-
/** How often the idle clock is checked. Default 30 s. */
|
|
23
|
-
idleCheckMs?: number;
|
|
24
|
-
factory?: ServiceFactory;
|
|
25
|
-
log?: (message: string) => void;
|
|
26
|
-
now?: () => number;
|
|
27
|
-
pid?: number;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface Daemon {
|
|
31
|
-
socketPath: string;
|
|
32
|
-
pid: number;
|
|
33
|
-
readonly closed: boolean;
|
|
34
|
-
/** Close the daemon now, stopping every parent service. */
|
|
35
|
-
close(): Promise<void>;
|
|
36
|
-
parents(): string[];
|
|
37
|
-
connections(): number;
|
|
38
|
-
/** Wait until the daemon has closed for any reason. */
|
|
39
|
-
whenClosed(): Promise<void>;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
interface Session {
|
|
43
|
-
parentId: string;
|
|
44
|
-
service: ParentService;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Start the daemon on a socket. Another live daemon on the same home wins, and
|
|
49
|
-
* this call refuses rather than stealing its socket.
|
|
50
|
-
*/
|
|
51
|
-
export async function startDaemon(options: DaemonOptions): Promise<Daemon> {
|
|
52
|
-
const pid = options.pid ?? process.pid;
|
|
53
|
-
const home = options.home ?? path.dirname(options.socketPath);
|
|
54
|
-
const log = options.log ?? (() => {});
|
|
55
|
-
const now = options.now ?? (() => Date.now());
|
|
56
|
-
const factory = options.factory ?? defaultServiceFactory;
|
|
57
|
-
const idleMs = options.idleMs ?? 5 * 60_000;
|
|
58
|
-
const idleCheckMs = options.idleCheckMs ?? 30_000;
|
|
59
|
-
|
|
60
|
-
if (await canConnect(options.socketPath)) throw new Error(`a daemon already listens on ${options.socketPath}`);
|
|
61
|
-
const lock = acquire(home, options.socketPath, pid);
|
|
62
|
-
if (lock.kind === 'held' && lock.record.pid !== pid) throw new Error(`a daemon with pid ${lock.record.pid} holds this home`);
|
|
63
|
-
|
|
64
|
-
fs.mkdirSync(path.dirname(options.socketPath), { recursive: true });
|
|
65
|
-
fs.rmSync(options.socketPath, { force: true });
|
|
66
|
-
|
|
67
|
-
const services = new Map<string, ParentService>();
|
|
68
|
-
const subscribers = new Map<string, Set<net.Socket>>();
|
|
69
|
-
const sockets = new Set<net.Socket>();
|
|
70
|
-
const paneWatches = new Map<net.Socket, (() => void)[]>();
|
|
71
|
-
let lastActivity = now();
|
|
72
|
-
let closed = false;
|
|
73
|
-
let closing: Promise<void> | undefined;
|
|
74
|
-
let closeResolve: () => void = () => {};
|
|
75
|
-
const closedPromise = new Promise<void>((resolve) => {
|
|
76
|
-
closeResolve = resolve;
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
const forgetSocket = (socket: net.Socket): void => {
|
|
80
|
-
sockets.delete(socket);
|
|
81
|
-
for (const stop of paneWatches.get(socket) ?? []) stop();
|
|
82
|
-
paneWatches.delete(socket);
|
|
83
|
-
for (const [parentId, set] of subscribers) {
|
|
84
|
-
set.delete(socket);
|
|
85
|
-
if (set.size === 0) subscribers.delete(parentId);
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
const push = (parentId: string, entries: OutboxEntry[]): void => {
|
|
90
|
-
const set = subscribers.get(parentId);
|
|
91
|
-
if (!set || entries.length === 0) return;
|
|
92
|
-
const line = formatReply({ type: 'events', entries });
|
|
93
|
-
for (const socket of set) if (socket.writable) socket.write(line);
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
const serviceFor = (parent: ParentHello): Session => {
|
|
97
|
-
const id = parentIdOf(parent);
|
|
98
|
-
const existing = services.get(id);
|
|
99
|
-
if (existing) return { parentId: id, service: existing };
|
|
100
|
-
const service = factory(parent, id);
|
|
101
|
-
services.set(id, service);
|
|
102
|
-
service.onEvents((entries) => push(id, entries));
|
|
103
|
-
return { parentId: id, service };
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
const close = async (): Promise<void> => {
|
|
107
|
-
if (closing) return closing;
|
|
108
|
-
closed = true;
|
|
109
|
-
const serverClosed = new Promise<void>((resolve) => server.close(() => resolve()));
|
|
110
|
-
for (const stops of paneWatches.values()) for (const stop of stops) stop();
|
|
111
|
-
paneWatches.clear();
|
|
112
|
-
for (const socket of sockets) socket.destroy();
|
|
113
|
-
sockets.clear();
|
|
114
|
-
subscribers.clear();
|
|
115
|
-
for (const service of services.values()) service.stop();
|
|
116
|
-
services.clear();
|
|
117
|
-
fs.rmSync(options.socketPath, { force: true });
|
|
118
|
-
release(home, pid);
|
|
119
|
-
await serverClosed;
|
|
120
|
-
closeResolve();
|
|
121
|
-
closing = Promise.resolve();
|
|
122
|
-
return closing;
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
const idle = setInterval(() => {
|
|
126
|
-
if (closed) return;
|
|
127
|
-
if (sockets.size === 0 && now() - lastActivity >= idleMs) {
|
|
128
|
-
log('idle: closing the daemon');
|
|
129
|
-
void close();
|
|
130
|
-
}
|
|
131
|
-
}, idleCheckMs);
|
|
132
|
-
idle.unref?.();
|
|
133
|
-
|
|
134
|
-
const server = net.createServer((socket) => {
|
|
135
|
-
sockets.add(socket);
|
|
136
|
-
socket.setEncoding('utf8');
|
|
137
|
-
let buffer = '';
|
|
138
|
-
let session: Session | undefined;
|
|
139
|
-
|
|
140
|
-
const reply = (value: DaemonReply): void => {
|
|
141
|
-
if (socket.writable) socket.write(formatReply(value));
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
socket.on('data', (chunk: string) => {
|
|
145
|
-
if (closed) return;
|
|
146
|
-
lastActivity = now();
|
|
147
|
-
buffer += chunk;
|
|
148
|
-
if (buffer.length > MAX_DAEMON_FRAME_BYTES) {
|
|
149
|
-
reply({ type: 'error', code: 'frame_too_large', message: 'the frame exceeds the daemon limit' });
|
|
150
|
-
socket.destroy();
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
let index = buffer.indexOf('\n');
|
|
154
|
-
while (index >= 0) {
|
|
155
|
-
const line = buffer.slice(0, index);
|
|
156
|
-
buffer = buffer.slice(index + 1);
|
|
157
|
-
void handle(line);
|
|
158
|
-
index = buffer.indexOf('\n');
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
const handle = async (line: string): Promise<void> => {
|
|
163
|
-
if (!line.trim()) return;
|
|
164
|
-
let request;
|
|
165
|
-
try {
|
|
166
|
-
request = parseRequest(line);
|
|
167
|
-
} catch (error) {
|
|
168
|
-
const fault = error as ProtocolError;
|
|
169
|
-
reply({ type: 'error', code: fault.code, message: fault.message });
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
if (request.type === 'hello') {
|
|
173
|
-
if (request.protocol !== DAEMON_PROTOCOL) {
|
|
174
|
-
reply({ type: 'error', code: 'protocol_mismatch', message: 'the client spoke another protocol', protocol: DAEMON_PROTOCOL });
|
|
175
|
-
socket.end();
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
session = serviceFor(request.parent);
|
|
179
|
-
const set = subscribers.get(session.parentId) ?? new Set<net.Socket>();
|
|
180
|
-
set.add(socket);
|
|
181
|
-
subscribers.set(session.parentId, set);
|
|
182
|
-
reply({ type: 'hello', protocol: DAEMON_PROTOCOL, parentId: session.parentId, pid, pending: session.service.pending() });
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
if (request.type === 'bye') {
|
|
186
|
-
if (session) {
|
|
187
|
-
subscribers.get(session.parentId)?.delete(socket);
|
|
188
|
-
const remaining = subscribers.get(session.parentId);
|
|
189
|
-
if (!remaining || remaining.size === 0) {
|
|
190
|
-
session.service.stop();
|
|
191
|
-
services.delete(session.parentId);
|
|
192
|
-
subscribers.delete(session.parentId);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
socket.end();
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
if (request.type === 'drain') {
|
|
199
|
-
log('drain: closing after the current calls');
|
|
200
|
-
reply({ type: 'closed' });
|
|
201
|
-
socket.end();
|
|
202
|
-
void close();
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
if (!session) {
|
|
206
|
-
if (request.type === 'call') reply({ type: 'error', id: request.id, code: 'no_hello', message: 'say hello before calling a tool' });
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
if (request.type === 'receipt') {
|
|
210
|
-
session.service.markRead(request.receipts);
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
if (request.type === 'watch') {
|
|
214
|
-
const stop = session.service.watchPane(request.paneId, (status) => reply({ type: 'status', paneId: request.paneId, status }));
|
|
215
|
-
const stops = paneWatches.get(socket) ?? [];
|
|
216
|
-
stops.push(stop);
|
|
217
|
-
paneWatches.set(socket, stops);
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
if (request.type === 'call') {
|
|
221
|
-
try {
|
|
222
|
-
const text = await session.service.tool(request.tool, request.args);
|
|
223
|
-
reply({ type: 'result', id: request.id, text });
|
|
224
|
-
} catch (error) {
|
|
225
|
-
reply({ type: 'result', id: request.id, error: (error as Error).message });
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
|
|
230
|
-
socket.on('error', () => forgetSocket(socket));
|
|
231
|
-
socket.on('close', () => forgetSocket(socket));
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
await new Promise<void>((resolve, reject) => {
|
|
235
|
-
server.once('error', reject);
|
|
236
|
-
server.listen(options.socketPath, () => {
|
|
237
|
-
server.off('error', reject);
|
|
238
|
-
resolve();
|
|
239
|
-
});
|
|
240
|
-
});
|
|
241
|
-
fs.chmodSync(options.socketPath, 0o600);
|
|
242
|
-
|
|
243
|
-
return {
|
|
244
|
-
socketPath: options.socketPath,
|
|
245
|
-
pid,
|
|
246
|
-
get closed() {
|
|
247
|
-
return closed;
|
|
248
|
-
},
|
|
249
|
-
close,
|
|
250
|
-
parents: () => [...services.keys()],
|
|
251
|
-
connections: () => sockets.size,
|
|
252
|
-
whenClosed: () => closedPromise,
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** Whether something answers on the socket, used to spot a live daemon. */
|
|
257
|
-
export async function canConnect(socketPath: string): Promise<boolean> {
|
|
258
|
-
if (!fs.existsSync(socketPath)) return false;
|
|
259
|
-
return new Promise((resolve) => {
|
|
260
|
-
const socket = net.createConnection(socketPath);
|
|
261
|
-
const done = (value: boolean): void => {
|
|
262
|
-
socket.destroy();
|
|
263
|
-
resolve(value);
|
|
264
|
-
};
|
|
265
|
-
socket.once('connect', () => done(true));
|
|
266
|
-
socket.once('error', () => done(false));
|
|
267
|
-
setTimeout(() => done(false), 300).unref?.();
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** Whether a lock names a daemon that still runs. */
|
|
272
|
-
export function daemonIsLive(home: string): boolean {
|
|
273
|
-
const record = readLock(home);
|
|
274
|
-
return Boolean(record && isAlive(record.pid));
|
|
275
|
-
}
|
package/src/daemon/service.ts
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
// A parent service: everything the daemon keeps for one parent session. The
|
|
2
|
-
// herdr-backed service wraps the same tool list, watcher and outbox the
|
|
3
|
-
// adapters used to run in-process; the daemon now runs it once for every
|
|
4
|
-
// client of the session, and tests pass a fake in its place.
|
|
5
|
-
import { HerdrClient } from '../core/herdr-client.ts';
|
|
6
|
-
import { emptyParent, parentId, readParent, saveParent } from '../core/registry.ts';
|
|
7
|
-
import { Watcher } from '../core/watcher.ts';
|
|
8
|
-
import { runBellwetherTool, type ToolContext } from '../integrations/tools.ts';
|
|
9
|
-
import type { OutboxEntry } from '../core/types.ts';
|
|
10
|
-
import type { ParentHello } from './protocol.ts';
|
|
11
|
-
|
|
12
|
-
export interface ParentService {
|
|
13
|
-
/** Run one Bellwether tool for a client, and return its text. */
|
|
14
|
-
tool(name: string, args: Record<string, unknown>): Promise<string>;
|
|
15
|
-
/** Mark receipts read, which settles their outbox entries. */
|
|
16
|
-
markRead(receipts: string[]): void;
|
|
17
|
-
/** Subscribe to new events. One handler per service, set by the daemon. */
|
|
18
|
-
onEvents(handler: (entries: OutboxEntry[]) => void): void;
|
|
19
|
-
/** Unread entries, ready to send again after a reconnect. */
|
|
20
|
-
pending(): OutboxEntry[];
|
|
21
|
-
/** Report one pane's status changes, and stop when the returned function runs. */
|
|
22
|
-
watchPane(paneId: string, handler: (status: string) => void): () => void;
|
|
23
|
-
stop(): void;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export type ServiceFactory = (parent: ParentHello, id: string) => ParentService;
|
|
27
|
-
|
|
28
|
-
/** The herdr-backed service, one per parent session. */
|
|
29
|
-
export function createHerdrService(parent: ParentHello, id: string): ParentService {
|
|
30
|
-
const existing = readParent(id);
|
|
31
|
-
const record = existing ?? saveParent(emptyParent(parent.harness, parent.session, parent.cwd, { host: parent.host, paneId: parent.paneId, workspaceId: parent.workspaceId, depth: parent.depth }));
|
|
32
|
-
if (!existing) saveParent(record);
|
|
33
|
-
const client = new HerdrClient({ socketPath: parent.herdrSocket });
|
|
34
|
-
let handler: ((entries: OutboxEntry[]) => void) | undefined;
|
|
35
|
-
const watcher = new Watcher({ client, parentId: record.id, onEntries: (entries) => handler?.(entries) });
|
|
36
|
-
const context: ToolContext = { client, parentId: record.id, watcher };
|
|
37
|
-
const paneWatches = new Set<{ close: () => void }>();
|
|
38
|
-
watcher.start();
|
|
39
|
-
return {
|
|
40
|
-
tool: (name, args) => runBellwetherTool(context, name, args),
|
|
41
|
-
markRead: (receipts) => {
|
|
42
|
-
for (const receipt of receipts) watcher.markRead(receipt);
|
|
43
|
-
},
|
|
44
|
-
onEvents: (next) => {
|
|
45
|
-
handler = next;
|
|
46
|
-
},
|
|
47
|
-
pending: () => watcher.outboxEntries().filter((entry) => !entry.read).map((entry) => ({ ...entry, deliveredAt: undefined })),
|
|
48
|
-
watchPane: (paneId, handler) => {
|
|
49
|
-
const controller = new AbortController();
|
|
50
|
-
const watch = { close: () => controller.abort() };
|
|
51
|
-
paneWatches.add(watch);
|
|
52
|
-
void client
|
|
53
|
-
.subscribe([{ type: 'pane.agent_status_changed', pane_id: paneId }], (event) => {
|
|
54
|
-
const id = event.data['pane_id'];
|
|
55
|
-
const status = event.data['agent_status'];
|
|
56
|
-
if (id === paneId && typeof status === 'string') handler(status);
|
|
57
|
-
}, controller.signal)
|
|
58
|
-
.catch((error: unknown) => {
|
|
59
|
-
paneWatches.delete(watch);
|
|
60
|
-
handler(`unavailable: ${String(error)}`);
|
|
61
|
-
});
|
|
62
|
-
return () => {
|
|
63
|
-
paneWatches.delete(watch);
|
|
64
|
-
controller.abort();
|
|
65
|
-
};
|
|
66
|
-
},
|
|
67
|
-
stop: () => {
|
|
68
|
-
for (const watch of paneWatches) watch.close();
|
|
69
|
-
paneWatches.clear();
|
|
70
|
-
watcher.stop();
|
|
71
|
-
},
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export const defaultServiceFactory: ServiceFactory = createHerdrService;
|
|
76
|
-
|
|
77
|
-
/** The parent id a hello stands for, so a resumed session finds its children. */
|
|
78
|
-
export function parentIdOf(parent: ParentHello): string {
|
|
79
|
-
return parentId(parent.harness, parent.session);
|
|
80
|
-
}
|
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
// The Claude Code channel: an MCP server over stdio that gives the parent
|
|
2
|
-
// session the Bellwether tools, and pushes each child event into the session
|
|
3
|
-
// as a notifications/claude/channel event. The core runs in the daemon; this
|
|
4
|
-
// server is one client of it. A receipt id in the event text marks that event
|
|
5
|
-
// read once it reaches the session transcript, which is where Claude Code
|
|
6
|
-
// records what the model received.
|
|
7
|
-
//
|
|
8
|
-
// stdout carries the MCP protocol, so every log line goes to stderr.
|
|
9
|
-
import os from 'node:os';
|
|
10
|
-
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
11
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
12
|
-
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
13
|
-
import { DaemonClient } from '../../daemon/client.ts';
|
|
14
|
-
import { resolveSocketPath } from '../../core/herdr-client.ts';
|
|
15
|
-
import { hostName } from '../../core/spawn.ts';
|
|
16
|
-
import type { OutboxEntry } from '../../core/types.ts';
|
|
17
|
-
import { childTools, parentTools } from '../tools.ts';
|
|
18
|
-
import { ReceiptScan, claudeConfigDir } from './transcript.ts';
|
|
19
|
-
|
|
20
|
-
const log = (...args: unknown[]): void => console.error('[bellwether]', ...args);
|
|
21
|
-
|
|
22
|
-
/** How long a burst of events settles before it is pushed, so churn collapses. */
|
|
23
|
-
const SETTLE_MS = 200;
|
|
24
|
-
/** How often the transcript is read for receipts. */
|
|
25
|
-
const SCAN_MS = 500;
|
|
26
|
-
/** How long after a push the parent's own status is judged, before one resend. */
|
|
27
|
-
const RESEND_AFTER_MS = 20_000;
|
|
28
|
-
|
|
29
|
-
const session = process.env['CLAUDE_CODE_SESSION_ID'] ?? `pid-${process.ppid}`;
|
|
30
|
-
const pane = process.env['HERDR_PANE_ID'];
|
|
31
|
-
const workspace = process.env['HERDR_WORKSPACE_ID'];
|
|
32
|
-
const cwd = process.env['CLAUDE_PROJECT_DIR'] ?? process.cwd();
|
|
33
|
-
const depth = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10) || 0;
|
|
34
|
-
const isChild = Boolean(process.env['BELLWETHER_PARENT']);
|
|
35
|
-
|
|
36
|
-
const tools = isChild ? [...parentTools, ...childTools] : parentTools;
|
|
37
|
-
|
|
38
|
-
const mcp = new Server(
|
|
39
|
-
{ name: 'bellwether', version: '0.1.0' },
|
|
40
|
-
{
|
|
41
|
-
capabilities: { experimental: { 'claude/channel': {} }, tools: {} },
|
|
42
|
-
instructions: [
|
|
43
|
-
'Events from this channel are Bellwether child-agent changes: a child reported, went idle, blocked on a dialog, stalled, or exited.',
|
|
44
|
-
'Each event names the child and carries its receipt. Read more with agent_read, and reply with agent_send.',
|
|
45
|
-
'Start children with agent_spawn, and give each one a concrete deliverable that tells it to call parent_report when done.',
|
|
46
|
-
'agent_list shows every child with its status and unread count.',
|
|
47
|
-
].join(' '),
|
|
48
|
-
},
|
|
49
|
-
);
|
|
50
|
-
|
|
51
|
-
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
52
|
-
tools: tools.map(({ name, description, schema }) => ({ name, description, inputSchema: schema })),
|
|
53
|
-
}));
|
|
54
|
-
|
|
55
|
-
let daemon: DaemonClient | undefined;
|
|
56
|
-
let connectFailure = 'Bellwether is not running: the daemon did not start for this session.';
|
|
57
|
-
/** The first connection attempt, awaited by any tool call that arrives early. */
|
|
58
|
-
let ready: Promise<void> = Promise.resolve();
|
|
59
|
-
|
|
60
|
-
mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
61
|
-
const text = (body: unknown): { content: { type: 'text'; text: string }[] } => ({
|
|
62
|
-
content: [{ type: 'text', text: typeof body === 'string' ? body : JSON.stringify(body, null, 2) }],
|
|
63
|
-
});
|
|
64
|
-
await ready;
|
|
65
|
-
if (!daemon) return { ...text(connectFailure), isError: true };
|
|
66
|
-
try {
|
|
67
|
-
return text(await daemon.tool(request.params.name, (request.params.arguments ?? {}) as Record<string, unknown>));
|
|
68
|
-
} catch (error) {
|
|
69
|
-
return { ...text((error as Error).message), isError: true };
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
/** One channel event's text. The receipt rides in the text, not only in meta. */
|
|
74
|
-
function compose(entry: OutboxEntry): string {
|
|
75
|
-
return `[bellwether] ${entry.name} (${entry.kind}, ${entry.paneId}) ${entry.event} — receipt ${entry.receipt}\n${entry.text}\n\nRead more with agent_read. Reply with agent_send.`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function push(entry: OutboxEntry): Promise<void> {
|
|
79
|
-
await mcp.notification({
|
|
80
|
-
method: 'notifications/claude/channel',
|
|
81
|
-
params: { content: compose(entry), meta: { child: entry.name, event: entry.event, receipt: entry.receipt } },
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// Receipts this server has already pushed, and those sent once more after the
|
|
86
|
-
// parent went idle without reading them.
|
|
87
|
-
const sent = new Set<string>();
|
|
88
|
-
const resent = new Set<string>();
|
|
89
|
-
const settleTimers = new Map<string, NodeJS.Timeout>();
|
|
90
|
-
let parentIdle: boolean | undefined;
|
|
91
|
-
let burst: NodeJS.Timeout | undefined;
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* A push that never reached the model leaves its receipt unread. If the parent
|
|
95
|
-
* is idle while the notice should already have started a turn, send it once
|
|
96
|
-
* more; after that, leave it for agent_list to show.
|
|
97
|
-
*/
|
|
98
|
-
async function resendOnce(entry: OutboxEntry): Promise<boolean> {
|
|
99
|
-
if (!parentIdle || entry.read || resent.has(entry.receipt) || !sent.has(entry.receipt)) return false;
|
|
100
|
-
resent.add(entry.receipt);
|
|
101
|
-
try {
|
|
102
|
-
await push(entry);
|
|
103
|
-
log('resent', entry.receipt, entry.name);
|
|
104
|
-
return true;
|
|
105
|
-
} catch (error) {
|
|
106
|
-
log('resend failed:', (error as Error).message);
|
|
107
|
-
return false;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async function resendWhenIdle(): Promise<void> {
|
|
112
|
-
if (!parentIdle || !daemon) return;
|
|
113
|
-
for (const entry of daemon.unread()) await resendOnce(entry);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function schedule(entries: OutboxEntry[]): void {
|
|
117
|
-
if (!entries.some((entry) => !entry.read && !sent.has(entry.receipt))) return;
|
|
118
|
-
if (burst) return;
|
|
119
|
-
burst = setTimeout(() => void flush(), SETTLE_MS);
|
|
120
|
-
burst.unref?.();
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async function flush(): Promise<void> {
|
|
124
|
-
burst = undefined;
|
|
125
|
-
if (!daemon) return;
|
|
126
|
-
const fresh = daemon.unread().filter((entry) => !entry.read && !sent.has(entry.receipt));
|
|
127
|
-
for (const entry of fresh) {
|
|
128
|
-
try {
|
|
129
|
-
await push(entry);
|
|
130
|
-
sent.add(entry.receipt);
|
|
131
|
-
log('pushed', entry.receipt, entry.name, entry.event);
|
|
132
|
-
armResendCheck(entry.receipt);
|
|
133
|
-
} catch (error) {
|
|
134
|
-
// A failed write leaves the receipt unsent, so the next event re-pushes it.
|
|
135
|
-
log('push failed:', (error as Error).message);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** Judge the parent's own status once, rather than polling it. */
|
|
141
|
-
function armResendCheck(receipt: string): void {
|
|
142
|
-
if (settleTimers.has(receipt)) return;
|
|
143
|
-
const timer = setTimeout(() => {
|
|
144
|
-
settleTimers.delete(receipt);
|
|
145
|
-
const entry = daemon?.unread().find((candidate) => candidate.receipt === receipt);
|
|
146
|
-
if (!entry) return;
|
|
147
|
-
void resendOnce(entry);
|
|
148
|
-
}, RESEND_AFTER_MS);
|
|
149
|
-
timer.unref?.();
|
|
150
|
-
settleTimers.set(receipt, timer);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
const scan = new ReceiptScan(session, cwd, claudeConfigDir());
|
|
154
|
-
|
|
155
|
-
/** Mark an entry read, and drop the bookkeeping for its resend. */
|
|
156
|
-
function readReceipt(receipt: string): void {
|
|
157
|
-
daemon?.receipts([receipt]);
|
|
158
|
-
resent.delete(receipt);
|
|
159
|
-
const timer = settleTimers.get(receipt);
|
|
160
|
-
if (timer) clearTimeout(timer);
|
|
161
|
-
settleTimers.delete(receipt);
|
|
162
|
-
log('read', receipt);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function scanReceipts(): void {
|
|
166
|
-
if (!daemon) return;
|
|
167
|
-
const unread = daemon.unread().filter((entry) => !entry.read);
|
|
168
|
-
if (!unread.length) return;
|
|
169
|
-
for (const receipt of scan.scan(unread.map((entry) => entry.receipt))) readReceipt(receipt);
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Announce whatever the previous server left unread. A receipt already in the
|
|
174
|
-
* transcript is marked read instead, so a restart does not repeat an event the
|
|
175
|
-
* model has received.
|
|
176
|
-
*/
|
|
177
|
-
function announcePending(): void {
|
|
178
|
-
if (!daemon) return;
|
|
179
|
-
const unread = daemon.unread().filter((entry) => !entry.read);
|
|
180
|
-
for (const receipt of scan.search(unread.map((entry) => entry.receipt))) readReceipt(receipt);
|
|
181
|
-
scan.start();
|
|
182
|
-
void flush();
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** The parent's own pane, watched through the daemon: idle means a queued notice should have started a turn. */
|
|
186
|
-
function watchParentPane(attempt = 0): void {
|
|
187
|
-
if (!pane || !daemon) return;
|
|
188
|
-
daemon.watchPane(pane, (status) => {
|
|
189
|
-
if (status.startsWith('unavailable:')) {
|
|
190
|
-
const delay = Math.min(500 * 2 ** attempt, 10_000);
|
|
191
|
-
const timer = setTimeout(() => {
|
|
192
|
-
if (stopping) return;
|
|
193
|
-
watchParentPane(attempt + 1);
|
|
194
|
-
}, delay);
|
|
195
|
-
timer.unref?.();
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
const wasIdle = parentIdle;
|
|
199
|
-
parentIdle = status === 'idle' || status === 'done';
|
|
200
|
-
if (parentIdle && !wasIdle) void resendWhenIdle();
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
let stopping = false;
|
|
205
|
-
function quit(): void {
|
|
206
|
-
if (stopping) return;
|
|
207
|
-
stopping = true;
|
|
208
|
-
if (burst) clearTimeout(burst);
|
|
209
|
-
burst = undefined;
|
|
210
|
-
for (const timer of settleTimers.values()) clearTimeout(timer);
|
|
211
|
-
settleTimers.clear();
|
|
212
|
-
void daemon?.close();
|
|
213
|
-
daemon = undefined;
|
|
214
|
-
process.exit(0);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// Exit with the session: a leftover server would show the session as listening.
|
|
218
|
-
process.stdin.on('end', quit);
|
|
219
|
-
process.stdin.on('close', quit);
|
|
220
|
-
process.on('SIGTERM', quit);
|
|
221
|
-
process.on('SIGINT', quit);
|
|
222
|
-
mcp.onclose = quit;
|
|
223
|
-
|
|
224
|
-
await mcp.connect(new StdioServerTransport());
|
|
225
|
-
ready = (async () => {
|
|
226
|
-
try {
|
|
227
|
-
daemon = await DaemonClient.connect({
|
|
228
|
-
harness: 'claude-code',
|
|
229
|
-
session,
|
|
230
|
-
cwd,
|
|
231
|
-
host: hostName() || os.hostname(),
|
|
232
|
-
paneId: pane,
|
|
233
|
-
workspaceId: workspace,
|
|
234
|
-
depth,
|
|
235
|
-
herdrSocket: resolveSocketPath(),
|
|
236
|
-
}, { log });
|
|
237
|
-
daemon.onEvents((entries) => schedule(entries));
|
|
238
|
-
} catch (error) {
|
|
239
|
-
connectFailure = `Bellwether could not reach its daemon: ${(error as Error).message}`;
|
|
240
|
-
log(connectFailure);
|
|
241
|
-
}
|
|
242
|
-
})();
|
|
243
|
-
await ready;
|
|
244
|
-
announcePending();
|
|
245
|
-
setInterval(scanReceipts, SCAN_MS).unref?.();
|
|
246
|
-
watchParentPane();
|
|
247
|
-
log('channel ready for', daemon?.parentId ?? 'no parent', 'in pane', pane ?? 'unknown');
|