@elecnix/bellwether 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -1
  2. package/dist/cli.js +295 -0
  3. package/dist/core/classifier.js +66 -0
  4. package/dist/core/herdr-client.js +368 -0
  5. package/dist/core/outbox.js +80 -0
  6. package/dist/core/paths.js +32 -0
  7. package/dist/core/registry.js +93 -0
  8. package/dist/core/report.js +50 -0
  9. package/dist/core/spawn.js +128 -0
  10. package/dist/core/transcript.js +79 -0
  11. package/dist/core/types.js +1 -0
  12. package/dist/core/watcher.js +593 -0
  13. package/dist/daemon/client.js +377 -0
  14. package/dist/daemon/lock.js +68 -0
  15. package/dist/daemon/main.js +34 -0
  16. package/dist/daemon/protocol.js +90 -0
  17. package/dist/daemon/server.js +244 -0
  18. package/dist/daemon/service.js +63 -0
  19. package/dist/integrations/claude/channel.js +245 -0
  20. package/dist/integrations/claude/transcript.js +135 -0
  21. package/dist/integrations/pi/extension.js +117 -0
  22. package/dist/integrations/tools.js +220 -0
  23. package/package.json +7 -6
  24. package/bin/bellwether-mcp.js +0 -4
  25. package/bin/bellwether.js +0 -2
  26. package/src/cli.ts +0 -293
  27. package/src/core/classifier.ts +0 -108
  28. package/src/core/herdr-client.ts +0 -410
  29. package/src/core/outbox.ts +0 -89
  30. package/src/core/paths.ts +0 -41
  31. package/src/core/registry.ts +0 -96
  32. package/src/core/report.ts +0 -54
  33. package/src/core/spawn.ts +0 -159
  34. package/src/core/transcript.ts +0 -74
  35. package/src/core/types.ts +0 -95
  36. package/src/core/watcher.ts +0 -590
  37. package/src/daemon/client.ts +0 -383
  38. package/src/daemon/lock.ts +0 -72
  39. package/src/daemon/main.ts +0 -38
  40. package/src/daemon/protocol.ts +0 -184
  41. package/src/daemon/server.ts +0 -275
  42. package/src/daemon/service.ts +0 -80
  43. package/src/integrations/claude/channel.ts +0 -247
  44. package/src/integrations/claude/transcript.ts +0 -124
  45. package/src/integrations/pi/extension.ts +0 -136
  46. package/src/integrations/tools.ts +0 -235
@@ -0,0 +1,244 @@
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 } from './protocol.js';
10
+ import { defaultServiceFactory, parentIdOf } from './service.js';
11
+ import { acquire, isAlive, readLock, release } from './lock.js';
12
+ /**
13
+ * Start the daemon on a socket. Another live daemon on the same home wins, and
14
+ * this call refuses rather than stealing its socket.
15
+ */
16
+ export async function startDaemon(options) {
17
+ const pid = options.pid ?? process.pid;
18
+ const home = options.home ?? path.dirname(options.socketPath);
19
+ const log = options.log ?? (() => { });
20
+ const now = options.now ?? (() => Date.now());
21
+ const factory = options.factory ?? defaultServiceFactory;
22
+ const idleMs = options.idleMs ?? 5 * 60_000;
23
+ const idleCheckMs = options.idleCheckMs ?? 30_000;
24
+ if (await canConnect(options.socketPath))
25
+ throw new Error(`a daemon already listens on ${options.socketPath}`);
26
+ const lock = acquire(home, options.socketPath, pid);
27
+ if (lock.kind === 'held' && lock.record.pid !== pid)
28
+ throw new Error(`a daemon with pid ${lock.record.pid} holds this home`);
29
+ fs.mkdirSync(path.dirname(options.socketPath), { recursive: true });
30
+ fs.rmSync(options.socketPath, { force: true });
31
+ const services = new Map();
32
+ const subscribers = new Map();
33
+ const sockets = new Set();
34
+ const paneWatches = new Map();
35
+ let lastActivity = now();
36
+ let closed = false;
37
+ let closing;
38
+ let closeResolve = () => { };
39
+ const closedPromise = new Promise((resolve) => {
40
+ closeResolve = resolve;
41
+ });
42
+ const forgetSocket = (socket) => {
43
+ sockets.delete(socket);
44
+ for (const stop of paneWatches.get(socket) ?? [])
45
+ stop();
46
+ paneWatches.delete(socket);
47
+ for (const [parentId, set] of subscribers) {
48
+ set.delete(socket);
49
+ if (set.size === 0)
50
+ subscribers.delete(parentId);
51
+ }
52
+ };
53
+ const push = (parentId, entries) => {
54
+ const set = subscribers.get(parentId);
55
+ if (!set || entries.length === 0)
56
+ return;
57
+ const line = formatReply({ type: 'events', entries });
58
+ for (const socket of set)
59
+ if (socket.writable)
60
+ socket.write(line);
61
+ };
62
+ const serviceFor = (parent) => {
63
+ const id = parentIdOf(parent);
64
+ const existing = services.get(id);
65
+ if (existing)
66
+ return { parentId: id, service: existing };
67
+ const service = factory(parent, id);
68
+ services.set(id, service);
69
+ service.onEvents((entries) => push(id, entries));
70
+ return { parentId: id, service };
71
+ };
72
+ const close = async () => {
73
+ if (closing)
74
+ return closing;
75
+ closed = true;
76
+ const serverClosed = new Promise((resolve) => server.close(() => resolve()));
77
+ for (const stops of paneWatches.values())
78
+ for (const stop of stops)
79
+ stop();
80
+ paneWatches.clear();
81
+ for (const socket of sockets)
82
+ socket.destroy();
83
+ sockets.clear();
84
+ subscribers.clear();
85
+ for (const service of services.values())
86
+ service.stop();
87
+ services.clear();
88
+ fs.rmSync(options.socketPath, { force: true });
89
+ release(home, pid);
90
+ await serverClosed;
91
+ closeResolve();
92
+ closing = Promise.resolve();
93
+ return closing;
94
+ };
95
+ const idle = setInterval(() => {
96
+ if (closed)
97
+ return;
98
+ if (sockets.size === 0 && now() - lastActivity >= idleMs) {
99
+ log('idle: closing the daemon');
100
+ void close();
101
+ }
102
+ }, idleCheckMs);
103
+ idle.unref?.();
104
+ const server = net.createServer((socket) => {
105
+ sockets.add(socket);
106
+ socket.setEncoding('utf8');
107
+ let buffer = '';
108
+ let session;
109
+ const reply = (value) => {
110
+ if (socket.writable)
111
+ socket.write(formatReply(value));
112
+ };
113
+ socket.on('data', (chunk) => {
114
+ if (closed)
115
+ return;
116
+ lastActivity = now();
117
+ buffer += chunk;
118
+ if (buffer.length > MAX_DAEMON_FRAME_BYTES) {
119
+ reply({ type: 'error', code: 'frame_too_large', message: 'the frame exceeds the daemon limit' });
120
+ socket.destroy();
121
+ return;
122
+ }
123
+ let index = buffer.indexOf('\n');
124
+ while (index >= 0) {
125
+ const line = buffer.slice(0, index);
126
+ buffer = buffer.slice(index + 1);
127
+ void handle(line);
128
+ index = buffer.indexOf('\n');
129
+ }
130
+ });
131
+ const handle = async (line) => {
132
+ if (!line.trim())
133
+ return;
134
+ let request;
135
+ try {
136
+ request = parseRequest(line);
137
+ }
138
+ catch (error) {
139
+ const fault = error;
140
+ reply({ type: 'error', code: fault.code, message: fault.message });
141
+ return;
142
+ }
143
+ if (request.type === 'hello') {
144
+ if (request.protocol !== DAEMON_PROTOCOL) {
145
+ reply({ type: 'error', code: 'protocol_mismatch', message: 'the client spoke another protocol', protocol: DAEMON_PROTOCOL });
146
+ socket.end();
147
+ return;
148
+ }
149
+ session = serviceFor(request.parent);
150
+ const set = subscribers.get(session.parentId) ?? new Set();
151
+ set.add(socket);
152
+ subscribers.set(session.parentId, set);
153
+ reply({ type: 'hello', protocol: DAEMON_PROTOCOL, parentId: session.parentId, pid, pending: session.service.pending() });
154
+ return;
155
+ }
156
+ if (request.type === 'bye') {
157
+ if (session) {
158
+ subscribers.get(session.parentId)?.delete(socket);
159
+ const remaining = subscribers.get(session.parentId);
160
+ if (!remaining || remaining.size === 0) {
161
+ session.service.stop();
162
+ services.delete(session.parentId);
163
+ subscribers.delete(session.parentId);
164
+ }
165
+ }
166
+ socket.end();
167
+ return;
168
+ }
169
+ if (request.type === 'drain') {
170
+ log('drain: closing after the current calls');
171
+ reply({ type: 'closed' });
172
+ socket.end();
173
+ void close();
174
+ return;
175
+ }
176
+ if (!session) {
177
+ if (request.type === 'call')
178
+ reply({ type: 'error', id: request.id, code: 'no_hello', message: 'say hello before calling a tool' });
179
+ return;
180
+ }
181
+ if (request.type === 'receipt') {
182
+ session.service.markRead(request.receipts);
183
+ return;
184
+ }
185
+ if (request.type === 'watch') {
186
+ const stop = session.service.watchPane(request.paneId, (status) => reply({ type: 'status', paneId: request.paneId, status }));
187
+ const stops = paneWatches.get(socket) ?? [];
188
+ stops.push(stop);
189
+ paneWatches.set(socket, stops);
190
+ return;
191
+ }
192
+ if (request.type === 'call') {
193
+ try {
194
+ const text = await session.service.tool(request.tool, request.args);
195
+ reply({ type: 'result', id: request.id, text });
196
+ }
197
+ catch (error) {
198
+ reply({ type: 'result', id: request.id, error: error.message });
199
+ }
200
+ }
201
+ };
202
+ socket.on('error', () => forgetSocket(socket));
203
+ socket.on('close', () => forgetSocket(socket));
204
+ });
205
+ await new Promise((resolve, reject) => {
206
+ server.once('error', reject);
207
+ server.listen(options.socketPath, () => {
208
+ server.off('error', reject);
209
+ resolve();
210
+ });
211
+ });
212
+ fs.chmodSync(options.socketPath, 0o600);
213
+ return {
214
+ socketPath: options.socketPath,
215
+ pid,
216
+ get closed() {
217
+ return closed;
218
+ },
219
+ close,
220
+ parents: () => [...services.keys()],
221
+ connections: () => sockets.size,
222
+ whenClosed: () => closedPromise,
223
+ };
224
+ }
225
+ /** Whether something answers on the socket, used to spot a live daemon. */
226
+ export async function canConnect(socketPath) {
227
+ if (!fs.existsSync(socketPath))
228
+ return false;
229
+ return new Promise((resolve) => {
230
+ const socket = net.createConnection(socketPath);
231
+ const done = (value) => {
232
+ socket.destroy();
233
+ resolve(value);
234
+ };
235
+ socket.once('connect', () => done(true));
236
+ socket.once('error', () => done(false));
237
+ setTimeout(() => done(false), 300).unref?.();
238
+ });
239
+ }
240
+ /** Whether a lock names a daemon that still runs. */
241
+ export function daemonIsLive(home) {
242
+ const record = readLock(home);
243
+ return Boolean(record && isAlive(record.pid));
244
+ }
@@ -0,0 +1,63 @@
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.js';
6
+ import { emptyParent, parentId, readParent, saveParent } from '../core/registry.js';
7
+ import { Watcher } from '../core/watcher.js';
8
+ import { runBellwetherTool } from '../integrations/tools.js';
9
+ /** The herdr-backed service, one per parent session. */
10
+ export function createHerdrService(parent, id) {
11
+ const existing = readParent(id);
12
+ const record = existing ?? saveParent(emptyParent(parent.harness, parent.session, parent.cwd, { host: parent.host, paneId: parent.paneId, workspaceId: parent.workspaceId, depth: parent.depth }));
13
+ if (!existing)
14
+ saveParent(record);
15
+ const client = new HerdrClient({ socketPath: parent.herdrSocket });
16
+ let handler;
17
+ const watcher = new Watcher({ client, parentId: record.id, onEntries: (entries) => handler?.(entries) });
18
+ const context = { client, parentId: record.id, watcher };
19
+ const paneWatches = new Set();
20
+ watcher.start();
21
+ return {
22
+ tool: (name, args) => runBellwetherTool(context, name, args),
23
+ markRead: (receipts) => {
24
+ for (const receipt of receipts)
25
+ watcher.markRead(receipt);
26
+ },
27
+ onEvents: (next) => {
28
+ handler = next;
29
+ },
30
+ pending: () => watcher.outboxEntries().filter((entry) => !entry.read).map((entry) => ({ ...entry, deliveredAt: undefined })),
31
+ watchPane: (paneId, handler) => {
32
+ const controller = new AbortController();
33
+ const watch = { close: () => controller.abort() };
34
+ paneWatches.add(watch);
35
+ void client
36
+ .subscribe([{ type: 'pane.agent_status_changed', pane_id: paneId }], (event) => {
37
+ const id = event.data['pane_id'];
38
+ const status = event.data['agent_status'];
39
+ if (id === paneId && typeof status === 'string')
40
+ handler(status);
41
+ }, controller.signal)
42
+ .catch((error) => {
43
+ paneWatches.delete(watch);
44
+ handler(`unavailable: ${String(error)}`);
45
+ });
46
+ return () => {
47
+ paneWatches.delete(watch);
48
+ controller.abort();
49
+ };
50
+ },
51
+ stop: () => {
52
+ for (const watch of paneWatches)
53
+ watch.close();
54
+ paneWatches.clear();
55
+ watcher.stop();
56
+ },
57
+ };
58
+ }
59
+ export const defaultServiceFactory = createHerdrService;
60
+ /** The parent id a hello stands for, so a resumed session finds its children. */
61
+ export function parentIdOf(parent) {
62
+ return parentId(parent.harness, parent.session);
63
+ }
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ // The Claude Code channel: an MCP server over stdio that gives the parent
3
+ // session the Bellwether tools, and pushes each child event into the session
4
+ // as a notifications/claude/channel event. The core runs in the daemon; this
5
+ // server is one client of it. A receipt id in the event text marks that event
6
+ // read once it reaches the session transcript, which is where Claude Code
7
+ // records what the model received.
8
+ //
9
+ // stdout carries the MCP protocol, so every log line goes to stderr.
10
+ import os from 'node:os';
11
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
12
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
14
+ import { DaemonClient } from '../../daemon/client.js';
15
+ import { resolveSocketPath } from '../../core/herdr-client.js';
16
+ import { hostName } from '../../core/spawn.js';
17
+ import { childTools, parentTools } from '../tools.js';
18
+ import { ReceiptScan, claudeConfigDir } from './transcript.js';
19
+ const log = (...args) => console.error('[bellwether]', ...args);
20
+ /** How long a burst of events settles before it is pushed, so churn collapses. */
21
+ const SETTLE_MS = 200;
22
+ /** How often the transcript is read for receipts. */
23
+ const SCAN_MS = 500;
24
+ /** How long after a push the parent's own status is judged, before one resend. */
25
+ const RESEND_AFTER_MS = 20_000;
26
+ const session = process.env['CLAUDE_CODE_SESSION_ID'] ?? `pid-${process.ppid}`;
27
+ const pane = process.env['HERDR_PANE_ID'];
28
+ const workspace = process.env['HERDR_WORKSPACE_ID'];
29
+ const cwd = process.env['CLAUDE_PROJECT_DIR'] ?? process.cwd();
30
+ const depth = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10) || 0;
31
+ const isChild = Boolean(process.env['BELLWETHER_PARENT']);
32
+ const tools = isChild ? [...parentTools, ...childTools] : parentTools;
33
+ const mcp = new Server({ name: 'bellwether', version: '0.1.0' }, {
34
+ capabilities: { experimental: { 'claude/channel': {} }, tools: {} },
35
+ instructions: [
36
+ 'Events from this channel are Bellwether child-agent changes: a child reported, went idle, blocked on a dialog, stalled, or exited.',
37
+ 'Each event names the child and carries its receipt. Read more with agent_read, and reply with agent_send.',
38
+ 'Start children with agent_spawn, and give each one a concrete deliverable that tells it to call parent_report when done.',
39
+ 'agent_list shows every child with its status and unread count.',
40
+ ].join(' '),
41
+ });
42
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
43
+ tools: tools.map(({ name, description, schema }) => ({ name, description, inputSchema: schema })),
44
+ }));
45
+ let daemon;
46
+ let connectFailure = 'Bellwether is not running: the daemon did not start for this session.';
47
+ /** The first connection attempt, awaited by any tool call that arrives early. */
48
+ let ready = Promise.resolve();
49
+ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
50
+ const text = (body) => ({
51
+ content: [{ type: 'text', text: typeof body === 'string' ? body : JSON.stringify(body, null, 2) }],
52
+ });
53
+ await ready;
54
+ if (!daemon)
55
+ return { ...text(connectFailure), isError: true };
56
+ try {
57
+ return text(await daemon.tool(request.params.name, (request.params.arguments ?? {})));
58
+ }
59
+ catch (error) {
60
+ return { ...text(error.message), isError: true };
61
+ }
62
+ });
63
+ /** One channel event's text. The receipt rides in the text, not only in meta. */
64
+ function compose(entry) {
65
+ 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.`;
66
+ }
67
+ async function push(entry) {
68
+ await mcp.notification({
69
+ method: 'notifications/claude/channel',
70
+ params: { content: compose(entry), meta: { child: entry.name, event: entry.event, receipt: entry.receipt } },
71
+ });
72
+ }
73
+ // Receipts this server has already pushed, and those sent once more after the
74
+ // parent went idle without reading them.
75
+ const sent = new Set();
76
+ const resent = new Set();
77
+ const settleTimers = new Map();
78
+ let parentIdle;
79
+ let burst;
80
+ /**
81
+ * A push that never reached the model leaves its receipt unread. If the parent
82
+ * is idle while the notice should already have started a turn, send it once
83
+ * more; after that, leave it for agent_list to show.
84
+ */
85
+ async function resendOnce(entry) {
86
+ if (!parentIdle || entry.read || resent.has(entry.receipt) || !sent.has(entry.receipt))
87
+ return false;
88
+ resent.add(entry.receipt);
89
+ try {
90
+ await push(entry);
91
+ log('resent', entry.receipt, entry.name);
92
+ return true;
93
+ }
94
+ catch (error) {
95
+ log('resend failed:', error.message);
96
+ return false;
97
+ }
98
+ }
99
+ async function resendWhenIdle() {
100
+ if (!parentIdle || !daemon)
101
+ return;
102
+ for (const entry of daemon.unread())
103
+ await resendOnce(entry);
104
+ }
105
+ function schedule(entries) {
106
+ if (!entries.some((entry) => !entry.read && !sent.has(entry.receipt)))
107
+ return;
108
+ if (burst)
109
+ return;
110
+ burst = setTimeout(() => void flush(), SETTLE_MS);
111
+ burst.unref?.();
112
+ }
113
+ async function flush() {
114
+ burst = undefined;
115
+ if (!daemon)
116
+ return;
117
+ const fresh = daemon.unread().filter((entry) => !entry.read && !sent.has(entry.receipt));
118
+ for (const entry of fresh) {
119
+ try {
120
+ await push(entry);
121
+ sent.add(entry.receipt);
122
+ log('pushed', entry.receipt, entry.name, entry.event);
123
+ armResendCheck(entry.receipt);
124
+ }
125
+ catch (error) {
126
+ // A failed write leaves the receipt unsent, so the next event re-pushes it.
127
+ log('push failed:', error.message);
128
+ }
129
+ }
130
+ }
131
+ /** Judge the parent's own status once, rather than polling it. */
132
+ function armResendCheck(receipt) {
133
+ if (settleTimers.has(receipt))
134
+ return;
135
+ const timer = setTimeout(() => {
136
+ settleTimers.delete(receipt);
137
+ const entry = daemon?.unread().find((candidate) => candidate.receipt === receipt);
138
+ if (!entry)
139
+ return;
140
+ void resendOnce(entry);
141
+ }, RESEND_AFTER_MS);
142
+ timer.unref?.();
143
+ settleTimers.set(receipt, timer);
144
+ }
145
+ const scan = new ReceiptScan(session, cwd, claudeConfigDir());
146
+ /** Mark an entry read, and drop the bookkeeping for its resend. */
147
+ function readReceipt(receipt) {
148
+ daemon?.receipts([receipt]);
149
+ resent.delete(receipt);
150
+ const timer = settleTimers.get(receipt);
151
+ if (timer)
152
+ clearTimeout(timer);
153
+ settleTimers.delete(receipt);
154
+ log('read', receipt);
155
+ }
156
+ function scanReceipts() {
157
+ if (!daemon)
158
+ return;
159
+ const unread = daemon.unread().filter((entry) => !entry.read);
160
+ if (!unread.length)
161
+ return;
162
+ for (const receipt of scan.scan(unread.map((entry) => entry.receipt)))
163
+ readReceipt(receipt);
164
+ }
165
+ /**
166
+ * Announce whatever the previous server left unread. A receipt already in the
167
+ * transcript is marked read instead, so a restart does not repeat an event the
168
+ * model has received.
169
+ */
170
+ function announcePending() {
171
+ if (!daemon)
172
+ return;
173
+ const unread = daemon.unread().filter((entry) => !entry.read);
174
+ for (const receipt of scan.search(unread.map((entry) => entry.receipt)))
175
+ readReceipt(receipt);
176
+ scan.start();
177
+ void flush();
178
+ }
179
+ /** The parent's own pane, watched through the daemon: idle means a queued notice should have started a turn. */
180
+ function watchParentPane(attempt = 0) {
181
+ if (!pane || !daemon)
182
+ return;
183
+ daemon.watchPane(pane, (status) => {
184
+ if (status.startsWith('unavailable:')) {
185
+ const delay = Math.min(500 * 2 ** attempt, 10_000);
186
+ const timer = setTimeout(() => {
187
+ if (stopping)
188
+ return;
189
+ watchParentPane(attempt + 1);
190
+ }, delay);
191
+ timer.unref?.();
192
+ return;
193
+ }
194
+ const wasIdle = parentIdle;
195
+ parentIdle = status === 'idle' || status === 'done';
196
+ if (parentIdle && !wasIdle)
197
+ void resendWhenIdle();
198
+ });
199
+ }
200
+ let stopping = false;
201
+ function quit() {
202
+ if (stopping)
203
+ return;
204
+ stopping = true;
205
+ if (burst)
206
+ clearTimeout(burst);
207
+ burst = undefined;
208
+ for (const timer of settleTimers.values())
209
+ clearTimeout(timer);
210
+ settleTimers.clear();
211
+ void daemon?.close();
212
+ daemon = undefined;
213
+ process.exit(0);
214
+ }
215
+ // Exit with the session: a leftover server would show the session as listening.
216
+ process.stdin.on('end', quit);
217
+ process.stdin.on('close', quit);
218
+ process.on('SIGTERM', quit);
219
+ process.on('SIGINT', quit);
220
+ mcp.onclose = quit;
221
+ await mcp.connect(new StdioServerTransport());
222
+ ready = (async () => {
223
+ try {
224
+ daemon = await DaemonClient.connect({
225
+ harness: 'claude-code',
226
+ session,
227
+ cwd,
228
+ host: hostName() || os.hostname(),
229
+ paneId: pane,
230
+ workspaceId: workspace,
231
+ depth,
232
+ herdrSocket: resolveSocketPath(),
233
+ }, { log });
234
+ daemon.onEvents((entries) => schedule(entries));
235
+ }
236
+ catch (error) {
237
+ connectFailure = `Bellwether could not reach its daemon: ${error.message}`;
238
+ log(connectFailure);
239
+ }
240
+ })();
241
+ await ready;
242
+ announcePending();
243
+ setInterval(scanReceipts, SCAN_MS).unref?.();
244
+ watchParentPane();
245
+ log('channel ready for', daemon?.parentId ?? 'no parent', 'in pane', pane ?? 'unknown');
@@ -0,0 +1,135 @@
1
+ // The receipt scan. Claude Code writes one JSONL line per event to
2
+ // ~/.claude/projects/<slug>/<session>.jsonl, and a channel notification lands
3
+ // there once the model receives it. An entry counts as read when its receipt
4
+ // id appears in the file, which is the same trick your-attention uses for its
5
+ // answers.
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { claudeProjectDir } from '../../core/transcript.js';
10
+ /** Claude Code's state root, which a lab overrides with CLAUDE_CONFIG_DIR. */
11
+ export function claudeConfigDir() {
12
+ return process.env['CLAUDE_CONFIG_DIR'] ?? path.join(os.homedir(), '.claude');
13
+ }
14
+ export function findTranscript(session, cwd, configDir) {
15
+ const root = path.join(configDir ?? claudeConfigDir(), 'projects');
16
+ if (cwd) {
17
+ const direct = path.join(root, claudeProjectDir(cwd), `${session}.jsonl`);
18
+ if (fs.existsSync(direct))
19
+ return direct;
20
+ }
21
+ try {
22
+ for (const dir of fs.readdirSync(root)) {
23
+ const file = path.join(root, dir, `${session}.jsonl`);
24
+ if (fs.existsSync(file))
25
+ return file;
26
+ }
27
+ }
28
+ catch {
29
+ // A missing projects directory is not an error: the scan simply waits.
30
+ }
31
+ return undefined;
32
+ }
33
+ /** Read a byte range in pieces, so a long session log never sits in memory whole. */
34
+ function readRange(file, from, to) {
35
+ const pieces = [];
36
+ const fd = fs.openSync(file, 'r');
37
+ try {
38
+ const size = 4 * 1024 * 1024;
39
+ let at = from;
40
+ while (at < to) {
41
+ const length = Math.min(size, to - at);
42
+ const buffer = Buffer.alloc(length);
43
+ const read = fs.readSync(fd, buffer, 0, length, at);
44
+ if (read <= 0)
45
+ break;
46
+ pieces.push(buffer.toString('utf8', 0, read));
47
+ at += read;
48
+ }
49
+ }
50
+ finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ return pieces.join('');
54
+ }
55
+ /**
56
+ * Incremental reader over one transcript. The offset starts at the file size
57
+ * when the server connects, so only later bytes count: a receipt id from an
58
+ * earlier run of the same session must not mark a new entry read.
59
+ */
60
+ export class ReceiptScan {
61
+ session;
62
+ cwd;
63
+ configDir;
64
+ transcript;
65
+ offset = 0;
66
+ constructor(session, cwd, configDir) {
67
+ this.session = session;
68
+ this.cwd = cwd;
69
+ this.configDir = configDir;
70
+ }
71
+ /** Anchor at the current end of the transcript, wherever it is. */
72
+ start() {
73
+ this.transcript = findTranscript(this.session, this.cwd, this.configDir);
74
+ if (!this.transcript)
75
+ return;
76
+ try {
77
+ this.offset = fs.statSync(this.transcript).size;
78
+ }
79
+ catch {
80
+ this.offset = 0;
81
+ }
82
+ }
83
+ /**
84
+ * Receipts already present anywhere in the file. Run once at startup, so an
85
+ * event the previous server pushed is not pushed a second time.
86
+ */
87
+ search(receipts) {
88
+ const found = new Set();
89
+ const wanted = [...receipts];
90
+ if (!wanted.length)
91
+ return found;
92
+ const file = this.transcript ?? findTranscript(this.session, this.cwd, this.configDir);
93
+ if (!file)
94
+ return found;
95
+ let size;
96
+ try {
97
+ size = fs.statSync(file).size;
98
+ }
99
+ catch {
100
+ return found;
101
+ }
102
+ if (size === 0)
103
+ return found;
104
+ const content = readRange(file, 0, size);
105
+ for (const receipt of wanted)
106
+ if (content.includes(receipt))
107
+ found.add(receipt);
108
+ return found;
109
+ }
110
+ /** The receipt ids that reached the transcript since the last scan. */
111
+ scan(receipts) {
112
+ const seen = new Set();
113
+ const wanted = [...receipts];
114
+ if (!wanted.length)
115
+ return seen;
116
+ this.transcript ??= findTranscript(this.session, this.cwd, this.configDir);
117
+ if (!this.transcript)
118
+ return seen;
119
+ let size;
120
+ try {
121
+ size = fs.statSync(this.transcript).size;
122
+ }
123
+ catch {
124
+ return seen;
125
+ }
126
+ if (size <= this.offset)
127
+ return seen;
128
+ const added = readRange(this.transcript, this.offset, size);
129
+ this.offset = size;
130
+ for (const receipt of wanted)
131
+ if (added.includes(receipt))
132
+ seen.add(receipt);
133
+ return seen;
134
+ }
135
+ }