@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
package/README.md CHANGED
@@ -95,7 +95,8 @@ src/daemon/ the daemon: protocol, server, client, lock, parent service
95
95
  src/integrations/ the tool list, shared by both adapters
96
96
  src/integrations/pi/ the Pi extension
97
97
  src/integrations/claude/ the Claude Code MCP channel server
98
- bin/ the bellwether command
98
+ bin/ the bellwether command and MCP server, run from the sources in a checkout
99
+ dist/ the compiled JavaScript that npm publishes, built by `npm run build`
99
100
  docs/ probe results and notes
100
101
  test/unit/ tier 1: fake clock, in-memory registry
101
102
  test/integration/ tier 2: a fake herdr socket and the daemon, tier 3: a real isolated herdr server
package/dist/cli.js ADDED
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env node
2
+ // The bellwether command.
3
+ //
4
+ // `watch` is the dogfood driver: it runs the same core the Pi extension and the
5
+ // Claude channel run, and prints one line per child event, so a supervisor can
6
+ // read the stream instead of polling herdr.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { HerdrClient, resolveSocketPath } from './core/herdr-client.js';
10
+ import { bellwetherHome } from './core/paths.js';
11
+ import { emptyParent, listParents, readParent, saveParent } from './core/registry.js';
12
+ import { reportToParent, writeReport } from './core/report.js';
13
+ import { DaemonClient } from './daemon/client.js';
14
+ import { daemonIsLive, startDaemon } from './daemon/server.js';
15
+ function parseArgs(argv) {
16
+ const positional = [];
17
+ const flags = {};
18
+ for (let index = 0; index < argv.length; index += 1) {
19
+ const token = argv[index];
20
+ if (!token.startsWith('--')) {
21
+ positional.push(token);
22
+ continue;
23
+ }
24
+ const key = token.slice(2);
25
+ const next = argv[index + 1];
26
+ if (next === undefined || next.startsWith('--')) {
27
+ flags[key] = true;
28
+ continue;
29
+ }
30
+ if (key === 'keys' || key === 'args') {
31
+ flags[key] = next;
32
+ }
33
+ else if (key === 'stuck-minutes' || key === 'max-depth' || key === 'lines') {
34
+ flags[key] = Number(next);
35
+ }
36
+ else {
37
+ flags[key] = next;
38
+ }
39
+ index += 1;
40
+ }
41
+ return { positional, flags };
42
+ }
43
+ function str(flags, key) {
44
+ const value = flags[key];
45
+ return typeof value === 'string' && value.length ? value : undefined;
46
+ }
47
+ function num(flags, key) {
48
+ const value = flags[key];
49
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
50
+ }
51
+ /** The registry this CLI run works against: an explicit id, the environment, or the newest. */
52
+ function parentFor(flags) {
53
+ const explicit = str(flags, 'parent') ?? process.env['BELLWETHER_PARENT'];
54
+ if (explicit)
55
+ return { id: explicit, created: false };
56
+ const name = `cli-${path.basename(process.cwd())}`;
57
+ const existing = readParent(name);
58
+ if (existing)
59
+ return { id: existing.id, created: false };
60
+ saveParent({
61
+ ...emptyParent('pi', name, process.cwd(), { host: process.env['HOSTNAME'] ?? '', paneId: process.env['HERDR_PANE_ID'], workspaceId: process.env['HERDR_WORKSPACE_ID'] }),
62
+ id: name,
63
+ });
64
+ return { id: name, created: true };
65
+ }
66
+ function clientFrom(flags) {
67
+ return new HerdrClient({ socketPath: str(flags, 'socket'), session: str(flags, 'session') });
68
+ }
69
+ function ok(label, detail) {
70
+ console.log(` ok ${label}: ${detail}`);
71
+ }
72
+ function bad(label, detail) {
73
+ console.log(` fail ${label}: ${detail}`);
74
+ }
75
+ /** The package root, found by walking up from this file to its package.json. */
76
+ function packageRoot() {
77
+ let dir = import.meta.dirname;
78
+ for (let depth = 0; depth < 4; depth += 1) {
79
+ if (fs.existsSync(path.join(dir, 'package.json')))
80
+ return dir;
81
+ const parent = path.dirname(dir);
82
+ if (parent === dir)
83
+ return undefined;
84
+ dir = parent;
85
+ }
86
+ return undefined;
87
+ }
88
+ /** Harnesses load these two paths by name, so a missing one fails at load time.
89
+ * doctor names it here, before a user meets it inside a session. */
90
+ function checkPackaging() {
91
+ const root = packageRoot();
92
+ if (!root) {
93
+ bad('package root', 'no package.json above the CLI');
94
+ return 1;
95
+ }
96
+ let failures = 0;
97
+ let manifest;
98
+ try {
99
+ manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
100
+ }
101
+ catch (error) {
102
+ bad('package.json', String(error));
103
+ return 1;
104
+ }
105
+ const extensions = manifest.pi?.extensions ?? [];
106
+ if (!extensions.length) {
107
+ bad('pi extension', 'package.json declares none');
108
+ failures += 1;
109
+ }
110
+ for (const entry of extensions) {
111
+ const file = path.resolve(root, entry);
112
+ if (fs.existsSync(file)) {
113
+ ok('pi extension', path.relative(root, file));
114
+ }
115
+ else {
116
+ bad('pi extension', `${entry} does not exist`);
117
+ failures += 1;
118
+ }
119
+ }
120
+ const declared = manifest.bin?.['bellwether-mcp'];
121
+ if (!declared) {
122
+ bad('mcp entry', 'package.json declares no bellwether-mcp bin');
123
+ return failures + 1;
124
+ }
125
+ const mcpEntry = path.resolve(root, declared);
126
+ const label = path.relative(root, mcpEntry);
127
+ if (!fs.existsSync(mcpEntry)) {
128
+ bad('mcp entry', `${label} does not exist`);
129
+ failures += 1;
130
+ }
131
+ else if (!(fs.statSync(mcpEntry).mode & 0o111)) {
132
+ bad('mcp entry', `${label} is not executable`);
133
+ failures += 1;
134
+ }
135
+ else {
136
+ ok('mcp entry', label);
137
+ }
138
+ return failures;
139
+ }
140
+ async function doctor() {
141
+ let failures = 0;
142
+ console.log(`bellwether home ${bellwetherHome()}`);
143
+ const daemonSocket = path.join(bellwetherHome(), 'daemon.sock');
144
+ const daemonLive = daemonIsLive(bellwetherHome());
145
+ console.log(` ${daemonLive ? 'ok ' : 'info '} daemon: ${daemonLive ? 'running' : 'idle, starts on demand'} (${daemonSocket})`);
146
+ failures += checkPackaging();
147
+ const socket = resolveSocketPath();
148
+ if (!fs.existsSync(socket)) {
149
+ console.log(` fail herdr socket: ${socket} does not exist`);
150
+ return 1;
151
+ }
152
+ console.log(` ok herdr socket: ${socket}`);
153
+ try {
154
+ const panes = await new HerdrClient({ socketPath: socket }).paneList();
155
+ console.log(` ok herdr api: ${panes.length} panes`);
156
+ }
157
+ catch (error) {
158
+ console.log(` fail herdr api: ${String(error)}`);
159
+ failures += 1;
160
+ }
161
+ for (const parent of listParents()) {
162
+ const live = parent.children.filter((child) => !child.exitedAt);
163
+ console.log(` ${parent.id}: ${live.length} live of ${parent.children.length} children, updated ${parent.updatedAt}`);
164
+ }
165
+ return failures;
166
+ }
167
+ async function main() {
168
+ const [command = 'help', ...rest] = process.argv.slice(2);
169
+ const { positional, flags } = parseArgs(rest);
170
+ if (command === 'help' || command === '--help') {
171
+ console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
172
+ console.log(' daemon [--socket PATH] run the local daemon in the foreground');
173
+ console.log(' spawn --kind KIND --name NAME [--cwd DIR] [--prompt TEXT] [--model M] [--parent ID] [--focus]');
174
+ console.log(' watch [--parent ID] [--tick-ms N] one line per child event, then keeps reading');
175
+ console.log(' list [--parent ID]');
176
+ console.log(' read CHILD [--lines N]');
177
+ console.log(' send CHILD [--text TEXT | --keys KEY,...]');
178
+ console.log(' stop CHILD [--force]');
179
+ console.log(' report --status done|needs-input|progress --text TEXT');
180
+ return 0;
181
+ }
182
+ if (command === 'doctor')
183
+ return doctor();
184
+ if (command === 'daemon') {
185
+ const socketPath = str(flags, 'socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(bellwetherHome(), 'daemon.sock');
186
+ const daemon = await startDaemon({ socketPath, home: bellwetherHome(), log: (message) => console.error('[bellwether-daemon]', message) });
187
+ console.error(`[bellwether-daemon] listening on ${socketPath} with pid ${daemon.pid}`);
188
+ const stop = () => void daemon.close().then(() => process.exit(0));
189
+ process.on('SIGTERM', stop);
190
+ process.on('SIGINT', stop);
191
+ await daemon.whenClosed();
192
+ return 0;
193
+ }
194
+ if (command === 'parents') {
195
+ for (const parent of listParents())
196
+ console.log(`${parent.id}\t${parent.children.length} children\t${parent.updatedAt}\t${parent.cwd}`);
197
+ return 0;
198
+ }
199
+ if (command === 'report') {
200
+ const status = (str(flags, 'status') ?? 'progress');
201
+ const text = str(flags, 'text') ?? '';
202
+ if (!text)
203
+ throw new Error('report needs --text');
204
+ if (!reportToParent(status, text)) {
205
+ const parentId = str(flags, 'parent');
206
+ if (!parentId)
207
+ throw new Error('report needs BELLWETHER_PARENT or --parent');
208
+ writeReport({ parentId, childName: process.env['BELLWETHER_CHILD_NAME'] ?? 'child', status, text });
209
+ }
210
+ return 0;
211
+ }
212
+ const { id: parentId } = parentFor(flags);
213
+ const parent = readParent(parentId);
214
+ if (!parent)
215
+ throw new Error(`No parent registry ${parentId}. Run bellwether list once to create it.`);
216
+ const daemon = await DaemonClient.connect({
217
+ harness: parent.harness,
218
+ session: parent.session,
219
+ cwd: parent.cwd,
220
+ host: parent.host,
221
+ paneId: parent.paneId,
222
+ workspaceId: parent.workspaceId,
223
+ depth: parent.depth,
224
+ herdrSocket: resolveSocketPath({ socketPath: str(flags, 'socket'), session: str(flags, 'session') }),
225
+ }, { log: (message) => console.error('[bellwether]', message) });
226
+ if (command === 'watch') {
227
+ const printed = new Set();
228
+ const emit = (entry) => {
229
+ if (printed.has(entry.receipt) || entry.read)
230
+ return;
231
+ printed.add(entry.receipt);
232
+ console.log(`CHILD ${entry.event} ${entry.name} ${entry.paneId} unread=${entry.receipt} at=${entry.at}`);
233
+ console.log(` ${entry.text.split('\n').join('\n ')}`);
234
+ };
235
+ daemon.onEvents((entries) => entries.forEach(emit));
236
+ (await daemon.pending()).forEach(emit);
237
+ console.log(`READY watch parent=${parentId} home=${bellwetherHome()}`);
238
+ const keepAlive = setInterval(() => { }, 60_000);
239
+ process.on('SIGINT', () => {
240
+ clearInterval(keepAlive);
241
+ void daemon.close().then(() => process.exit(0));
242
+ });
243
+ await new Promise(() => { });
244
+ return 0;
245
+ }
246
+ try {
247
+ if (command === 'spawn') {
248
+ const name = str(flags, 'name');
249
+ if (!name)
250
+ throw new Error('spawn needs --name');
251
+ console.log(await daemon.tool('agent_spawn', {
252
+ kind: str(flags, 'kind') ?? 'pi',
253
+ name,
254
+ cwd: str(flags, 'cwd'),
255
+ prompt: str(flags, 'prompt'),
256
+ model: str(flags, 'model'),
257
+ focus: flags['focus'] === true,
258
+ stuckMinutes: num(flags, 'stuck-minutes'),
259
+ maxDepth: num(flags, 'max-depth'),
260
+ args: str(flags, 'args')?.split('\u0000'),
261
+ }));
262
+ }
263
+ else if (command === 'list') {
264
+ console.log(await daemon.tool('agent_list', {}));
265
+ }
266
+ else if (command === 'read') {
267
+ const child = positional[0];
268
+ if (!child)
269
+ throw new Error('read needs a child');
270
+ console.log(await daemon.tool('agent_read', { child, lines: num(flags, 'lines') }));
271
+ }
272
+ else if (command === 'send') {
273
+ const child = positional[0];
274
+ if (!child)
275
+ throw new Error('send needs a child');
276
+ const keys = str(flags, 'keys')?.split(',').map((key) => key.trim()).filter(Boolean);
277
+ console.log(await daemon.tool('agent_send', { child, text: str(flags, 'text'), keys }));
278
+ }
279
+ else if (command === 'stop') {
280
+ const child = positional[0];
281
+ if (!child)
282
+ throw new Error('stop needs a child');
283
+ console.log(await daemon.tool('agent_stop', { child, force: flags['force'] === true }));
284
+ }
285
+ else {
286
+ console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
287
+ return 1;
288
+ }
289
+ }
290
+ finally {
291
+ await daemon.close();
292
+ }
293
+ return 0;
294
+ }
295
+ process.exitCode = await main();
@@ -0,0 +1,66 @@
1
+ /** Starting values. The lab tunes these; they are not measurements. */
2
+ export const DEFAULT_LIMITS = {
3
+ idleMs: 5_000,
4
+ blockedMs: 3_000,
5
+ stuckMs: 10 * 60_000,
6
+ };
7
+ export function initialState(status, now) {
8
+ return { status, statusSince: now, lastBusyAt: now };
9
+ }
10
+ export function isReady(status) {
11
+ return status === 'idle' || status === 'done';
12
+ }
13
+ /**
14
+ * Fold one observation into the state and say whether an event is due.
15
+ * The returned state is a new object; the classifier never mutates its input.
16
+ */
17
+ export function advance(state, observation, now, limits = DEFAULT_LIMITS) {
18
+ const next = { ...state };
19
+ if (observation.status !== state.status) {
20
+ next.status = observation.status;
21
+ next.statusSince = now;
22
+ next.firedStuckSince = undefined;
23
+ next.firedBlocked = undefined;
24
+ }
25
+ const becameReady = isReady(observation.status) && !isReady(state.status);
26
+ if (observation.completionSeq !== undefined && observation.completionSeq !== state.completionSeq) {
27
+ next.completionSeq = observation.completionSeq;
28
+ next.statusSince = now;
29
+ }
30
+ else if (observation.completionSeq === undefined && becameReady) {
31
+ // herdr reports completion_seq on AgentInfo, and the watcher reads that
32
+ // projection, so a reconciled child normally carries one. The field is
33
+ // still absent before the first reconcile finishes, and on a pane herdr
34
+ // has not observed working for: a turn that ends faster than screen
35
+ // detection catches it leaves the value unchanged. A turn that ends is
36
+ // also visible as a status change into idle or done, so count those.
37
+ next.completionSeq = (state.completionSeq ?? 0) + 1;
38
+ next.statusSince = now;
39
+ }
40
+ if (observation.busy) {
41
+ next.lastBusyAt = now;
42
+ next.firedStuckSince = undefined;
43
+ next.firedBlocked = undefined;
44
+ }
45
+ // A blocked child stays blocked until someone answers it, so report the
46
+ // dialog once and then wait for the status to move rather than repeating it
47
+ // on every tick.
48
+ if (next.status === 'blocked' && now - next.statusSince >= limits.blockedMs && !next.firedBlocked) {
49
+ return { state: { ...next, firedBlocked: true }, event: 'blocked' };
50
+ }
51
+ if (isReady(next.status) && next.completionSeq !== undefined && next.completionSeq !== next.reportedFor && now - next.statusSince >= limits.idleMs) {
52
+ return { state: { ...next, reportedFor: next.completionSeq }, event: 'idle' };
53
+ }
54
+ // A child first seen already settled still owes its parent one message.
55
+ if (isReady(next.status) && next.completionSeq === undefined && state.status !== next.status && now - next.statusSince >= limits.idleMs) {
56
+ return { state: { ...next, completionSeq: 1, reportedFor: 1 }, event: 'idle' };
57
+ }
58
+ if ((next.status === 'working' || next.status === 'unknown') && next.firedStuckSince !== next.lastBusyAt && now - next.lastBusyAt >= limits.stuckMs) {
59
+ return { state: { ...next, firedStuckSince: next.lastBusyAt }, event: 'stuck' };
60
+ }
61
+ return { state: next };
62
+ }
63
+ /** Mark the newest turn as covered by a report, so no idle event follows it. */
64
+ export function markReported(state, now) {
65
+ return { ...state, reportedFor: state.completionSeq, lastBusyAt: now, statusSince: now };
66
+ }