@elecnix/bellwether 0.1.2 → 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.
@@ -3,9 +3,14 @@
3
3
  // to start the harness in the tab's root pane, then watch the new pane.
4
4
  import os from 'node:os';
5
5
  import { HerdrApiError } from './herdr-client.js';
6
+ import { LOCAL_HOST } from './machine.js';
6
7
  import { newChildId } from './outbox.js';
7
- import { updateChild, upsertChild } from './registry.js';
8
- import { resolveTranscript } from './transcript.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';
9
14
  /** How deep a Bellwether child may spawn. The design starts at 2. */
10
15
  export const DEFAULT_MAX_DEPTH = 2;
11
16
  export const AGENT_KINDS = ['pi', 'claude', 'codex', 'opencode', 'cline'];
@@ -16,23 +21,35 @@ export function harnessOf(kind) {
16
21
  return 'claude-code';
17
22
  return 'other';
18
23
  }
19
- /** The extra arguments a child harness needs to load Bellwether itself. */
20
- export function childArgs(kind, options) {
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) {
21
35
  const args = [];
22
36
  if (options.model)
23
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}`);
24
41
  // Claude Code reads this flag as a list and keeps taking values until the
25
42
  // next flag, so the two-argument form swallowed the prompt that follows it.
26
43
  // The equals form pins the flag to one value.
27
44
  if (kind === 'claude')
28
45
  args.push('--dangerously-load-development-channels=server:bellwether');
29
- if (options.prompt)
30
- args.push(options.prompt);
46
+ if (briefFile)
47
+ args.push(briefArgument(kind, briefFile));
31
48
  if (options.args?.length)
32
49
  args.push(...options.args);
33
50
  return args;
34
51
  }
35
- export async function spawnChild(client, parent, options, signal) {
52
+ export async function spawnChild(client, parent, options, signal, hooks = {}) {
36
53
  const depth = parent.depth + 1;
37
54
  const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
38
55
  if (depth > maxDepth)
@@ -44,6 +61,8 @@ export async function spawnChild(client, parent, options, signal) {
44
61
  kind: options.kind,
45
62
  harness: harnessOf(options.kind),
46
63
  paneId: '',
64
+ host: options.host ?? LOCAL_HOST,
65
+ origin: 'spawn',
47
66
  cwd: options.cwd,
48
67
  startedAt: now,
49
68
  lastStatus: 'unknown',
@@ -51,54 +70,133 @@ export async function spawnChild(client, parent, options, signal) {
51
70
  lastBusyAt: now,
52
71
  depth,
53
72
  stuckMs: options.stuckMinutes === undefined ? undefined : Math.max(1_000, Math.round(options.stuckMinutes * 60_000)),
73
+ inactiveMs: resolveInactiveMs(options.inactiveMinutes),
54
74
  };
55
75
  // 1. The record lands before herdr is asked for anything.
56
76
  upsertChild(parent.id, child);
57
- // 2. The tab carries the environment the child needs to find its parent.
58
- const env = {
59
- BELLWETHER_PARENT: parent.id,
60
- BELLWETHER_CHILD: child.id,
61
- BELLWETHER_CHILD_NAME: child.name,
62
- BELLWETHER_DEPTH: String(depth),
63
- BELLWETHER_HARNESS: child.harness,
64
- };
65
- const tab = await client.tabCreate({ workspaceId: options.workspaceId ?? parent.workspaceId, cwd: options.cwd, label: child.name, env, focus: options.focus ?? false }, signal);
66
- if (!tab.paneId)
67
- throw new Error('herdr created no pane for the child tab');
68
- child.tabId = tab.tabId;
69
- child.paneId = tab.paneId;
70
- child.workspaceId = options.workspaceId ?? parent.workspaceId;
71
- upsertChild(parent.id, child);
72
- // 3. Start the harness in the tab's root pane. A tab answers tab.create
73
- // before its shell is at a prompt, so herdr refuses the start with
74
- // agent_pane_busy until the shell is ready.
77
+ let tabId;
78
+ let startup;
75
79
  try {
76
- await startWithRetry(client, { name: child.name, kind: options.kind, paneId: tab.paneId, args: childArgs(options.kind, options) }, signal);
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);
77
105
  }
78
106
  catch (error) {
79
- await client.tabClose(tab.tabId ?? tab.paneId).catch(() => { });
107
+ startup?.close();
108
+ await abandon(client, parent.id, child.id, tabId, hooks);
80
109
  throw error;
81
110
  }
82
- // 4. Resolve the transcript, then hand back the child and its herdr link.
83
- // The registry is re-read rather than written from the caller's copy, which
84
- // would erase the child record that upsertChild just added.
85
- await new Promise((resolve) => setTimeout(resolve, 750));
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));
86
132
  try {
87
- const panes = await client.agentList(signal);
88
- const pane = panes.find((entry) => entry.paneId === child.paneId);
89
- if (pane) {
90
- child.transcript = resolveTranscript(child.harness, pane.agentSessionId, child.cwd);
91
- child.lastStatus = pane.agentStatus;
92
- updateChild(parent.id, child.id, (entry) => {
93
- entry.transcript = child.transcript;
94
- entry.lastStatus = child.lastStatus;
95
- });
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);
96
142
  }
143
+ const status = pane['agent_status'];
144
+ if (typeof status === 'string' && status)
145
+ child.lastStatus = status;
97
146
  }
98
147
  catch {
99
- // A missed session id only costs the transcript-based summary.
148
+ // A missed session id only costs the transcript-based summary until the
149
+ // watcher reads it.
100
150
  }
101
- return { child, link: herdrLink('pane', child.paneId) };
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
+ };
102
200
  }
103
201
  /** herdr refuses a start until the new tab's shell reaches its prompt. */
104
202
  const PANE_NOT_READY = new Set(['agent_pane_busy', 'agent_pane_not_ready', 'pane_busy']);
@@ -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
+ }
@@ -63,6 +63,14 @@ export function resolveTranscript(harness, sessionId, cwd) {
63
63
  }
64
64
  return undefined;
65
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
+ }
66
74
  /** The session value herdr reports for a pane, whatever shape it takes. */
67
75
  export function sessionValueFrom(agentSession) {
68
76
  if (typeof agentSession === 'string')
@@ -1 +1,2 @@
1
- export {};
1
+ /** The registry layout this code writes. Version 2 added the child host. */
2
+ export const REGISTRY_SCHEMA = 2;