@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
@@ -0,0 +1,226 @@
1
+ // Starting a child. The order follows the design: write the registry record
2
+ // first, then create the tab with the Bellwether environment, then ask herdr
3
+ // to start the harness in the tab's root pane, then watch the new pane.
4
+ import os from 'node:os';
5
+ import { HerdrApiError } from './herdr-client.js';
6
+ import { LOCAL_HOST } from './machine.js';
7
+ import { newChildId } from './outbox.js';
8
+ import { briefArgument, writeBrief } from './brief.js';
9
+ import { resolveInactiveMs } from './inactivity.js';
10
+ import { removeChildFiles, writeMcpConfig } from './mcp-config.js';
11
+ import { removeChild, updateChild, upsertChild } from './registry.js';
12
+ import { watchStartup } from './startup-dialogs.js';
13
+ import { resolveTranscript, sessionFrom } from './transcript.js';
14
+ /** How deep a Bellwether child may spawn. The design starts at 2. */
15
+ export const DEFAULT_MAX_DEPTH = 2;
16
+ export const AGENT_KINDS = ['pi', 'claude', 'codex', 'opencode', 'cline'];
17
+ export function harnessOf(kind) {
18
+ if (kind === 'pi')
19
+ return 'pi';
20
+ if (kind === 'claude')
21
+ return 'claude-code';
22
+ return 'other';
23
+ }
24
+ /** How long the watcher holds a new Claude Code child's events. Longer than the dialog wait. */
25
+ export const STARTUP_HOLD_MS = 45_000;
26
+ /** How long the spawn waits for a Claude Code child to get past its dialogs. */
27
+ export const STARTUP_TIMEOUT_MS = 30_000;
28
+ /**
29
+ * The arguments a child harness starts with. The brief is never one of them:
30
+ * `briefFile` names the private file that holds it, and the harness gets a
31
+ * one-line pointer to that file. `mcpConfigFile` names a Claude Code child's
32
+ * own Bellwether server.
33
+ */
34
+ export function childArgs(kind, options, briefFile, mcpConfigFile) {
35
+ const args = [];
36
+ if (options.model)
37
+ args.push('--model', options.model);
38
+ // --mcp-config is a list flag too, so it takes the equals form for the same reason.
39
+ if (kind === 'claude' && mcpConfigFile)
40
+ args.push(`--mcp-config=${mcpConfigFile}`);
41
+ // Claude Code reads this flag as a list and keeps taking values until the
42
+ // next flag, so the two-argument form swallowed the prompt that follows it.
43
+ // The equals form pins the flag to one value.
44
+ if (kind === 'claude')
45
+ args.push('--dangerously-load-development-channels=server:bellwether');
46
+ if (briefFile)
47
+ args.push(briefArgument(kind, briefFile));
48
+ if (options.args?.length)
49
+ args.push(...options.args);
50
+ return args;
51
+ }
52
+ export async function spawnChild(client, parent, options, signal, hooks = {}) {
53
+ const depth = parent.depth + 1;
54
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
55
+ if (depth > maxDepth)
56
+ throw new Error(`Bellwether is ${maxDepth} levels deep already, so ${options.name} would go one level too far. Raise max_depth on the spawn if that is what you want.`);
57
+ const now = new Date().toISOString();
58
+ const child = {
59
+ id: newChildId(),
60
+ name: options.name,
61
+ kind: options.kind,
62
+ harness: harnessOf(options.kind),
63
+ paneId: '',
64
+ host: options.host ?? LOCAL_HOST,
65
+ origin: 'spawn',
66
+ cwd: options.cwd,
67
+ startedAt: now,
68
+ lastStatus: 'unknown',
69
+ statusChangedAt: now,
70
+ lastBusyAt: now,
71
+ depth,
72
+ stuckMs: options.stuckMinutes === undefined ? undefined : Math.max(1_000, Math.round(options.stuckMinutes * 60_000)),
73
+ inactiveMs: resolveInactiveMs(options.inactiveMinutes),
74
+ };
75
+ // 1. The record lands before herdr is asked for anything.
76
+ upsertChild(parent.id, child);
77
+ let tabId;
78
+ let startup;
79
+ try {
80
+ const briefFile = options.prompt ? writeBrief(child.id, options.prompt) : undefined;
81
+ const mcpConfigFile = childMcpConfig(child);
82
+ // 2. The tab carries the environment the child needs to find its parent.
83
+ const env = childEnv(parent, child);
84
+ // The parent's workspace id means nothing to another machine's herdr.
85
+ const workspaceId = options.workspaceId ?? (child.host === LOCAL_HOST ? parent.workspaceId : undefined);
86
+ const tab = await client.tabCreate({ workspaceId, cwd: options.cwd, label: child.name, env, focus: options.focus ?? false }, signal);
87
+ tabId = tab.tabId ?? tab.paneId;
88
+ if (!tab.paneId)
89
+ throw new Error('herdr created no pane for the child tab');
90
+ child.tabId = tab.tabId;
91
+ child.paneId = tab.paneId;
92
+ child.workspaceId = workspaceId;
93
+ // Claude Code opens on dialogs the spawn answers, so the watcher holds the
94
+ // child's events until then, and the status watch opens before the start.
95
+ if (options.kind === 'claude') {
96
+ const timeoutMs = options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS;
97
+ child.startingUntil = new Date(Date.now() + Math.max(STARTUP_HOLD_MS, timeoutMs + 15_000)).toISOString();
98
+ startup = await watchStartup(client, tab.paneId, signal, { timeoutMs, redrawMs: options.redrawMs });
99
+ }
100
+ upsertChild(parent.id, child);
101
+ // 3. Start the harness in the tab's root pane. A tab answers tab.create
102
+ // before its shell is at a prompt, so herdr refuses the start with
103
+ // agent_pane_busy until the shell is ready.
104
+ await startWithRetry(client, { name: child.name, kind: options.kind, paneId: tab.paneId, args: childArgs(options.kind, options, briefFile, mcpConfigFile) }, signal);
105
+ }
106
+ catch (error) {
107
+ startup?.close();
108
+ await abandon(client, parent.id, child.id, tabId, hooks);
109
+ throw error;
110
+ }
111
+ // 4. Answer the startup dialogs, then let the watcher read the child. The
112
+ // spawn answers yes to the folder-trust question for any folder, because
113
+ // the operator approves every spawn by default. A child still on a dialog
114
+ // when the wait runs out is undone, and the error names the dialog.
115
+ let answered;
116
+ if (startup) {
117
+ try {
118
+ answered = await startup.answer();
119
+ }
120
+ catch (error) {
121
+ startup.close();
122
+ await abandon(client, parent.id, child.id, tabId, hooks);
123
+ throw error;
124
+ }
125
+ startup.close();
126
+ }
127
+ // 5. Record the session and transcript, then hand back the child and its
128
+ // herdr link. The registry is re-read rather than written from the caller's
129
+ // copy, which would erase the child record that upsertChild just added.
130
+ if (!startup)
131
+ await new Promise((resolve) => setTimeout(resolve, 750));
132
+ try {
133
+ const result = await client.request('agent.get', { target: child.paneId }, { signal });
134
+ const agent = typeof result === 'object' && result !== null ? result['agent'] : undefined;
135
+ const pane = typeof agent === 'object' && agent !== null ? agent : {};
136
+ const session = sessionFrom(pane['agent_session']);
137
+ if (session) {
138
+ child.session = session;
139
+ // A remote child's transcript sits on its own machine's disk.
140
+ if (child.host === LOCAL_HOST)
141
+ child.transcript = resolveTranscript(child.harness, session.value, child.cwd);
142
+ }
143
+ const status = pane['agent_status'];
144
+ if (typeof status === 'string' && status)
145
+ child.lastStatus = status;
146
+ }
147
+ catch {
148
+ // A missed session id only costs the transcript-based summary until the
149
+ // watcher reads it.
150
+ }
151
+ child.startingUntil = undefined;
152
+ updateChild(parent.id, child.id, (entry) => {
153
+ if (child.session)
154
+ entry.session = child.session;
155
+ if (child.transcript)
156
+ entry.transcript = child.transcript;
157
+ if (entry.lastStatus !== child.lastStatus)
158
+ entry.statusChangedAt = new Date().toISOString();
159
+ entry.lastStatus = child.lastStatus;
160
+ // The hold ends with the answers, which are activity. The inactivity clock
161
+ // starts here, not at spawn time, so a long dialog does not eat the window.
162
+ if (startup)
163
+ entry.lastBusyAt = new Date().toISOString();
164
+ delete entry.startingUntil;
165
+ });
166
+ return { child, link: herdrLink('pane', child.paneId), answered };
167
+ }
168
+ /**
169
+ * Undo a spawn that never produced a running child. The record goes first, so
170
+ * the watcher finds no child when the tab-closed event arrives and the parent
171
+ * hears nothing about a child that never ran.
172
+ */
173
+ async function abandon(client, parentId, childId, tabId, hooks) {
174
+ removeChild(parentId, childId);
175
+ hooks.forget?.(childId);
176
+ removeChildFiles(childId);
177
+ if (tabId)
178
+ await client.tabClose(tabId).catch(() => { });
179
+ }
180
+ /**
181
+ * Write a Claude Code child's MCP configuration, when its server can resolve
182
+ * the child. A server talks to the daemon on its own machine, and only this
183
+ * machine's daemon holds the child record, so a child on another machine gets
184
+ * none.
185
+ */
186
+ export function childMcpConfig(child) {
187
+ if (child.kind !== 'claude' || (child.host ?? LOCAL_HOST) !== LOCAL_HOST)
188
+ return undefined;
189
+ return writeMcpConfig(child.id);
190
+ }
191
+ /** The environment a child's tab carries, so the child can find its parent. */
192
+ export function childEnv(parent, child) {
193
+ return {
194
+ BELLWETHER_PARENT: parent.id,
195
+ BELLWETHER_CHILD: child.id,
196
+ BELLWETHER_CHILD_NAME: child.name,
197
+ BELLWETHER_DEPTH: String(child.depth),
198
+ BELLWETHER_HARNESS: child.harness,
199
+ };
200
+ }
201
+ /** herdr refuses a start until the new tab's shell reaches its prompt. */
202
+ const PANE_NOT_READY = new Set(['agent_pane_busy', 'agent_pane_not_ready', 'pane_busy']);
203
+ export async function startWithRetry(client, params, signal, totalMs = 60_000) {
204
+ const deadline = Date.now() + totalMs;
205
+ let delay = 400;
206
+ for (;;) {
207
+ try {
208
+ await client.agentStart(params, signal);
209
+ return;
210
+ }
211
+ catch (error) {
212
+ const code = error instanceof HerdrApiError ? error.code : undefined;
213
+ if (!code || !PANE_NOT_READY.has(code) || Date.now() > deadline)
214
+ throw error;
215
+ await new Promise((resolve) => setTimeout(resolve, delay));
216
+ delay = Math.min(delay * 2, 4_000);
217
+ }
218
+ }
219
+ }
220
+ export function herdrLink(kind, id) {
221
+ const fingerprint = process.env['HERDR_ENV'] === '1' ? '' : '';
222
+ return `https://herdr.invalid/v1/${fingerprint}${kind}/${id}`;
223
+ }
224
+ export function hostName() {
225
+ return os.hostname();
226
+ }
@@ -0,0 +1,120 @@
1
+ const TRUST = /Is this a project you created or one you trust|Accessing workspace:/;
2
+ const CHANNEL = /WARNING: Loading development channels/;
3
+ const TRUST_ACCEPT = 'Yes, I trust this folder';
4
+ const CHANNEL_ACCEPT = 'I am using this for local development';
5
+ const SELECTED = /^\s*[❯>]\s/;
6
+ /** What each dialog is called in a message to the person. */
7
+ export const DIALOG_NAMES = {
8
+ trust: 'the folder-trust question',
9
+ channel: 'the development-channel question',
10
+ };
11
+ /** herdr's statuses for a child that is past its dialogs. */
12
+ const READY = new Set(['idle', 'working', 'done']);
13
+ export function detectDialog(screen) {
14
+ if (TRUST.test(screen))
15
+ return 'trust';
16
+ if (CHANNEL.test(screen))
17
+ return 'channel';
18
+ return undefined;
19
+ }
20
+ /**
21
+ * The key that moves a selection list toward `wanted`, or confirms it once it
22
+ * is selected. Undefined when the screen shows neither the option nor a
23
+ * selection, which happens while a dialog is still drawing.
24
+ */
25
+ export function keyToward(screen, wanted) {
26
+ const lines = screen.split('\n');
27
+ const target = lines.findIndex((line) => line.includes(wanted));
28
+ const selected = lines.findIndex((line) => SELECTED.test(line));
29
+ if (target < 0 || selected < 0)
30
+ return undefined;
31
+ if (target === selected)
32
+ return 'Enter';
33
+ return target < selected ? 'Up' : 'Down';
34
+ }
35
+ /** The option the selection marker is on, for an error message. */
36
+ function selectedOption(screen) {
37
+ const line = screen.split('\n').find((candidate) => SELECTED.test(candidate));
38
+ return line?.replace(SELECTED, '').replace(/^\d+\.\s*/, '').trim() || undefined;
39
+ }
40
+ export class StartupDialogTimeout extends Error {
41
+ dialog;
42
+ constructor(message, dialog) {
43
+ super(message);
44
+ this.name = 'StartupDialogTimeout';
45
+ this.dialog = dialog;
46
+ }
47
+ }
48
+ /** Open the status watch for a Claude Code child. Call before agent.start. */
49
+ export async function watchStartup(client, paneId, signal, options = {}) {
50
+ const timeoutMs = options.timeoutMs ?? 30_000;
51
+ const redrawMs = options.redrawMs ?? 300;
52
+ const controller = new AbortController();
53
+ signal?.addEventListener('abort', () => controller.abort(), { once: true });
54
+ let status = 'unknown';
55
+ let wake;
56
+ const subscription = await client.subscribe([{ type: 'pane.agent_status_changed', pane_id: paneId }], (event) => {
57
+ const value = event.data['agent_status'];
58
+ if (event.data['pane_id'] !== paneId || typeof value !== 'string')
59
+ return;
60
+ status = value;
61
+ wake?.();
62
+ }, controller.signal);
63
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
64
+ /** Wait for the next status event, or `ms`, whichever comes first. */
65
+ const nextStatus = (ms) => new Promise((resolve) => {
66
+ const timer = setTimeout(done, ms);
67
+ function done() {
68
+ clearTimeout(timer);
69
+ wake = undefined;
70
+ resolve();
71
+ }
72
+ wake = done;
73
+ });
74
+ return {
75
+ async answer() {
76
+ const deadline = Date.now() + timeoutMs;
77
+ const answered = [];
78
+ let screen = '';
79
+ let dialog;
80
+ while (Date.now() < deadline && !controller.signal.aborted) {
81
+ screen = await client.paneRead({ paneId, source: 'visible', lines: 40 }).catch(() => screen);
82
+ dialog = detectDialog(screen);
83
+ if (dialog) {
84
+ const key = keyToward(screen, dialog === 'trust' ? TRUST_ACCEPT : CHANNEL_ACCEPT);
85
+ if (key) {
86
+ await client.sendKeys(paneId, [key]);
87
+ if (key === 'Enter' && !answered.includes(dialog))
88
+ answered.push(dialog);
89
+ }
90
+ await sleep(redrawMs);
91
+ continue;
92
+ }
93
+ // The channel confirmation comes last, so once it is answered and gone
94
+ // the child is at its prompt. A child started with no development
95
+ // channel never shows it, and herdr's status says when it is ready.
96
+ if (answered.includes('channel') || READY.has(status))
97
+ return answered;
98
+ // A blocked pane with no dialog on screen is still drawing it.
99
+ await nextStatus(status === 'blocked' ? redrawMs : Math.max(0, deadline - Date.now()));
100
+ }
101
+ if (controller.signal.aborted)
102
+ throw new Error(`the spawn was cancelled while Claude Code in pane ${paneId} was starting`);
103
+ throw timeoutError(paneId, timeoutMs, dialog, status, screen);
104
+ },
105
+ close() {
106
+ subscription.close();
107
+ controller.abort();
108
+ },
109
+ };
110
+ }
111
+ function timeoutError(paneId, timeoutMs, dialog, status, screen) {
112
+ const seconds = Math.round(timeoutMs / 1000);
113
+ const tail = screen.trim().split('\n').slice(-12).join('\n');
114
+ if (dialog) {
115
+ const selected = selectedOption(screen);
116
+ const where = selected ? `with "${selected}" selected` : 'with no option selected';
117
+ return new StartupDialogTimeout(`Claude Code in pane ${paneId} was still on ${DIALOG_NAMES[dialog]}, ${where}, when the spawn timed out after ${seconds} s. The screen:\n${tail}`, dialog);
118
+ }
119
+ return new StartupDialogTimeout(`Claude Code in pane ${paneId} never reached its prompt before the spawn timed out after ${seconds} s: herdr reported it ${status}, on a screen Bellwether does not answer. The screen:\n${tail}`, undefined);
120
+ }
@@ -0,0 +1,87 @@
1
+ // Finding a child's transcript. The watcher reads the last assistant message
2
+ // from it, which is where a finished child's answer already sits.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ /** Claude Code replaces every non-alphanumeric character of the cwd with a dash. */
7
+ export function claudeProjectDir(cwd) {
8
+ return cwd.replace(/[^A-Za-z0-9]/g, '-');
9
+ }
10
+ function newestFile(dir, matches, depth = 3) {
11
+ let best;
12
+ const walk = (current, remaining) => {
13
+ let entries;
14
+ try {
15
+ entries = fs.readdirSync(current, { withFileTypes: true });
16
+ }
17
+ catch {
18
+ return;
19
+ }
20
+ for (const entry of entries) {
21
+ const full = path.join(current, entry.name);
22
+ if (entry.isDirectory() && remaining > 0)
23
+ walk(full, remaining - 1);
24
+ else if (entry.isFile() && matches(entry.name)) {
25
+ try {
26
+ const mtime = fs.statSync(full).mtimeMs;
27
+ if (!best || mtime > best.mtime)
28
+ best = { file: full, mtime };
29
+ }
30
+ catch {
31
+ // A transcript that vanished is not an error here.
32
+ }
33
+ }
34
+ }
35
+ };
36
+ walk(dir, depth);
37
+ return best?.file;
38
+ }
39
+ /** Pi names a session file `<timestamp>_<session id>.jsonl`. */
40
+ const endsWith = (name) => (sessionId) => name.endsWith(`${sessionId}.jsonl`);
41
+ /**
42
+ * Locate the transcript for a harness session. Pi and Claude Code both keep
43
+ * one JSONL file per session, named after the session id, under a per-project
44
+ * directory.
45
+ */
46
+ export function resolveTranscript(harness, sessionId, cwd) {
47
+ if (!sessionId)
48
+ return undefined;
49
+ // Pi reports its session as a path, Claude Code as an id. Take a path as one.
50
+ if (sessionId.includes('/') || sessionId.endsWith('.jsonl'))
51
+ return fs.existsSync(sessionId) ? sessionId : undefined;
52
+ const home = os.homedir();
53
+ if (harness === 'claude-code') {
54
+ const root = path.join(home, '.claude', 'projects');
55
+ const direct = cwd ? path.join(root, claudeProjectDir(cwd), `${sessionId}.jsonl`) : undefined;
56
+ if (direct && fs.existsSync(direct))
57
+ return direct;
58
+ return newestFile(root, endsWith(sessionId));
59
+ }
60
+ if (harness === 'pi') {
61
+ const root = process.env['PI_CODING_AGENT_DIR'] ?? path.join(home, '.pi', 'agent');
62
+ return newestFile(path.join(root, 'sessions'), endsWith(sessionId));
63
+ }
64
+ return undefined;
65
+ }
66
+ /** herdr's agent_session for a pane, as a kind and a value. */
67
+ export function sessionFrom(agentSession) {
68
+ const value = sessionValueFrom(agentSession);
69
+ if (!value)
70
+ return undefined;
71
+ const kind = typeof agentSession === 'object' && agentSession !== null ? agentSession['kind'] : undefined;
72
+ return { kind: typeof kind === 'string' && kind ? kind : value.includes('/') ? 'path' : 'id', value };
73
+ }
74
+ /** The session value herdr reports for a pane, whatever shape it takes. */
75
+ export function sessionValueFrom(agentSession) {
76
+ if (typeof agentSession === 'string')
77
+ return agentSession;
78
+ if (typeof agentSession === 'object' && agentSession !== null) {
79
+ const value = agentSession['value'];
80
+ if (typeof value === 'string' && value.length > 0)
81
+ return value;
82
+ const id = agentSession['id'];
83
+ if (typeof id === 'string' && id.length > 0)
84
+ return id;
85
+ }
86
+ return undefined;
87
+ }
@@ -0,0 +1,2 @@
1
+ /** The registry layout this code writes. Version 2 added the child host. */
2
+ export const REGISTRY_SCHEMA = 2;