@elecnix/bellwether 0.1.0 → 0.1.3

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