@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.
@@ -12,6 +12,31 @@ import { canConnect } from './server.js';
12
12
  const DEFAULT_TIMEOUT_MS = 60_000;
13
13
  const START_TIMEOUT_MS = 10_000;
14
14
  const RECONNECT_DELAY_MS = 200;
15
+ /**
16
+ * The variables that name one session. The daemon serves every session on the
17
+ * machine, so it starts without the identity of whichever session started it.
18
+ */
19
+ export const SESSION_IDENTITY = ['BELLWETHER_PARENT', 'BELLWETHER_CHILD', 'BELLWETHER_CHILD_NAME', 'BELLWETHER_DEPTH', 'BELLWETHER_HARNESS', 'HERDR_PANE_ID', 'CLAUDE_CODE_SESSION_ID'];
20
+ /** The environment a daemon starts with: the caller's, less any session identity. */
21
+ export function daemonEnv(env, home) {
22
+ const next = { ...env, BELLWETHER_HOME: home };
23
+ for (const key of SESSION_IDENTITY)
24
+ delete next[key];
25
+ return next;
26
+ }
27
+ /** A daemon that speaks another protocol, and the one it speaks. */
28
+ class ProtocolMismatch extends Error {
29
+ daemonProtocol;
30
+ constructor(message, daemonProtocol) {
31
+ super(`protocol_mismatch: ${message}`);
32
+ this.daemonProtocol = daemonProtocol;
33
+ this.name = 'ProtocolMismatch';
34
+ }
35
+ }
36
+ /** The daemon socket a client uses when none is given: the one under its home. */
37
+ export function defaultDaemonSocket(home) {
38
+ return path.join(home, 'daemon.sock');
39
+ }
15
40
  export class DaemonClient {
16
41
  connection;
17
42
  waiting = new Map();
@@ -46,7 +71,7 @@ export class DaemonClient {
46
71
  timeoutMs;
47
72
  static async connect(parent, options = {}) {
48
73
  const home = options.home ?? process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
49
- const socketPath = options.socketPath ?? path.join(home, 'daemon.sock');
74
+ const socketPath = options.socketPath ?? defaultDaemonSocket(home);
50
75
  const client = new DaemonClient(parent, home, socketPath, options);
51
76
  const hello = await client.establish();
52
77
  return Object.assign(client, { parentId: hello.parentId, pid: hello.pid });
@@ -83,7 +108,10 @@ export class DaemonClient {
83
108
  throw new Error('the daemon client is closed');
84
109
  await this.ensure();
85
110
  const id = `c${++this.sequence}`;
86
- const line = formatRequest({ type: 'call', id, tool: name, args });
111
+ // The caller identity travels with every call, so the daemon routes by its
112
+ // own records whichever client process asked.
113
+ const caller = { ...(this.parent.paneId ? { paneId: this.parent.paneId } : {}), ...(this.parent.childId ? { childId: this.parent.childId } : {}) };
114
+ const line = formatRequest({ type: 'call', id, tool: name, args, caller });
87
115
  return new Promise((resolve, reject) => {
88
116
  const timer = setTimeout(() => {
89
117
  this.waiting.delete(id);
@@ -143,12 +171,25 @@ export class DaemonClient {
143
171
  waiting.reject(new Error('the daemon client closed'));
144
172
  this.waiting.clear();
145
173
  }
146
- /** Connect, starting a daemon when nothing answers and spawning is allowed. */
174
+ /**
175
+ * Connect, starting a daemon when nothing answers and spawning is allowed.
176
+ * A daemon from an older release is drained first, so the newer protocol
177
+ * takes over; a newer daemon is left running, and the error says to update.
178
+ */
147
179
  async establish() {
148
180
  try {
149
181
  return await this.handshake();
150
182
  }
151
183
  catch (error) {
184
+ if (error instanceof ProtocolMismatch) {
185
+ if (error.daemonProtocol === undefined || error.daemonProtocol > DAEMON_PROTOCOL) {
186
+ throw new Error(`the running daemon speaks protocol ${error.daemonProtocol ?? 'unknown'}, newer than this client's ${DAEMON_PROTOCOL}. Update this Bellwether install.`);
187
+ }
188
+ this.log(`draining the daemon on protocol ${error.daemonProtocol}, older than ${DAEMON_PROTOCOL}`);
189
+ const replaced = await this.drainOlder();
190
+ if (replaced)
191
+ return replaced;
192
+ }
152
193
  if (!this.spawnAllowed)
153
194
  throw error;
154
195
  await this.startDaemon();
@@ -179,6 +220,8 @@ export class DaemonClient {
179
220
  const reply = await this.ask(connection, formatRequest(hello));
180
221
  if (reply.type === 'error') {
181
222
  connection.socket.destroy();
223
+ if (reply.code === 'protocol_mismatch')
224
+ throw new ProtocolMismatch(reply.message, reply.protocol);
182
225
  throw new Error(`${reply.code}: ${reply.message}`);
183
226
  }
184
227
  if (reply.type !== 'hello') {
@@ -194,6 +237,33 @@ export class DaemonClient {
194
237
  handler(reply.pending);
195
238
  return { parentId: reply.parentId, pid: reply.pid };
196
239
  }
240
+ /**
241
+ * Ask an older daemon to drain, and wait until its socket stops answering,
242
+ * or answers with this protocol because another client started the new daemon first.
243
+ */
244
+ async drainOlder() {
245
+ const connection = await this.open();
246
+ await new Promise((resolve) => {
247
+ connection.socket.once('close', () => resolve());
248
+ connection.socket.write(formatRequest({ type: 'drain' }));
249
+ setTimeout(() => resolve(), START_TIMEOUT_MS).unref?.();
250
+ });
251
+ connection.socket.destroy();
252
+ const deadline = Date.now() + START_TIMEOUT_MS;
253
+ while (await canConnect(this.socketPath)) {
254
+ try {
255
+ return await this.handshake();
256
+ }
257
+ catch (error) {
258
+ if (!(error instanceof ProtocolMismatch))
259
+ throw error;
260
+ }
261
+ if (Date.now() > deadline)
262
+ throw new Error(`the daemon on ${this.socketPath} did not drain within ${START_TIMEOUT_MS} ms`);
263
+ await new Promise((resolve) => setTimeout(resolve, 50));
264
+ }
265
+ return undefined;
266
+ }
197
267
  open() {
198
268
  return new Promise((resolve, reject) => {
199
269
  const socket = net.createConnection(this.socketPath);
@@ -272,10 +342,20 @@ export class DaemonClient {
272
342
  }
273
343
  dispatch(reply) {
274
344
  if (reply.type === 'events') {
275
- for (const entry of reply.entries)
276
- this.received.set(entry.receipt, entry);
277
- for (const handler of this.handlers)
278
- handler(reply.entries);
345
+ // An entry that arrives read was settled in the daemon, by a newer state
346
+ // or a newer event for the same child. Drop it, so no resend repeats it.
347
+ const unread = [];
348
+ for (const entry of reply.entries) {
349
+ if (entry.read)
350
+ this.received.delete(entry.receipt);
351
+ else {
352
+ this.received.set(entry.receipt, entry);
353
+ unread.push(entry);
354
+ }
355
+ }
356
+ if (unread.length)
357
+ for (const handler of this.handlers)
358
+ handler(unread);
279
359
  return;
280
360
  }
281
361
  if (reply.type === 'status') {
@@ -315,7 +395,9 @@ export class DaemonClient {
315
395
  const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', entry, '--socket', this.socketPath], {
316
396
  detached: true,
317
397
  stdio: 'ignore',
318
- env: { ...process.env, BELLWETHER_HOME: this.home },
398
+ // Never the caller's directory, which for a child is its worktree.
399
+ cwd: this.home,
400
+ env: daemonEnv(process.env, this.home),
319
401
  });
320
402
  child.unref();
321
403
  try {
@@ -1,5 +1,6 @@
1
1
  // The daemon process entry point. A client starts it detached with the socket
2
2
  // path, and it exits on drain, on an idle timeout, or on a signal.
3
+ import fs from 'node:fs';
3
4
  import os from 'node:os';
4
5
  import path from 'node:path';
5
6
  import { startDaemon } from './server.js';
@@ -12,6 +13,11 @@ async function main() {
12
13
  const argv = process.argv.slice(2);
13
14
  const home = process.env['BELLWETHER_HOME'] ?? path.join(os.homedir(), '.bellwether');
14
15
  const socketPath = flag(argv, '--socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(home, 'daemon.sock');
16
+ // Whichever session starts the daemon lends it its working directory, and a
17
+ // child's is the worktree the daemon may later remove. Work from the home,
18
+ // so the daemon never counts as a process inside a worktree.
19
+ fs.mkdirSync(home, { recursive: true });
20
+ process.chdir(home);
15
21
  const idleMs = Number.parseInt(process.env['BELLWETHER_DAEMON_IDLE_MS'] ?? '', 10);
16
22
  const daemon = await startDaemon({
17
23
  socketPath,
@@ -1,4 +1,5 @@
1
- export const DAEMON_PROTOCOL = 1;
1
+ // 2: a call carries the caller identity, and parent_report routes by it.
2
+ export const DAEMON_PROTOCOL = 2;
2
3
  /** The largest line a daemon or client will read, matching the herdr client. */
3
4
  export const MAX_DAEMON_FRAME_BYTES = 4 * 1024 * 1024;
4
5
  export class ProtocolError extends Error {
@@ -35,7 +36,8 @@ export function parseRequest(line) {
35
36
  if (!id || !tool)
36
37
  throw new ProtocolError('invalid_call', 'a call needs an id and a tool');
37
38
  const args = isRecord(value['args']) ? value['args'] : {};
38
- return { type: 'call', id, tool, args };
39
+ const caller = parseCaller(value['caller']);
40
+ return caller ? { type: 'call', id, tool, args, caller } : { type: 'call', id, tool, args };
39
41
  }
40
42
  case 'receipt': {
41
43
  const receipts = Array.isArray(value['receipts']) ? value['receipts'].filter((entry) => typeof entry === 'string' && entry.length > 0) : [];
@@ -55,6 +57,18 @@ export function parseRequest(line) {
55
57
  throw new ProtocolError('unknown_type', `unknown request type ${JSON.stringify(value['type'])}`);
56
58
  }
57
59
  }
60
+ function parseCaller(value) {
61
+ if (!isRecord(value))
62
+ return undefined;
63
+ const caller = {};
64
+ const childId = text(value['childId']);
65
+ const paneId = text(value['paneId']);
66
+ if (childId)
67
+ caller.childId = childId;
68
+ if (paneId)
69
+ caller.paneId = paneId;
70
+ return caller;
71
+ }
58
72
  function parseHello(value) {
59
73
  const protocol = value['protocol'];
60
74
  const parent = value['parent'];
@@ -77,7 +91,7 @@ function parseHello(value) {
77
91
  type: 'hello',
78
92
  protocol,
79
93
  client: text(value['client']) || 'unknown',
80
- parent: { harness, session, cwd, host, depth, herdrSocket, paneId: optional('paneId'), workspaceId: optional('workspaceId') },
94
+ parent: { harness, session, cwd, host, depth, herdrSocket, paneId: optional('paneId'), workspaceId: optional('workspaceId'), childId: optional('childId') },
81
95
  };
82
96
  }
83
97
  /** One reply line, without its newline. */
@@ -191,7 +191,7 @@ export async function startDaemon(options) {
191
191
  }
192
192
  if (request.type === 'call') {
193
193
  try {
194
- const text = await session.service.tool(request.tool, request.args);
194
+ const text = await session.service.tool(request.tool, request.args, request.caller ?? {});
195
195
  reply({ type: 'result', id: request.id, text });
196
196
  }
197
197
  catch (error) {
@@ -3,6 +3,7 @@
3
3
  // adapters used to run in-process; the daemon now runs it once for every
4
4
  // client of the session, and tests pass a fake in its place.
5
5
  import { HerdrClient } from '../core/herdr-client.js';
6
+ import { machineClients } from '../core/machine.js';
6
7
  import { emptyParent, parentId, readParent, saveParent } from '../core/registry.js';
7
8
  import { Watcher } from '../core/watcher.js';
8
9
  import { runBellwetherTool } from '../integrations/tools.js';
@@ -14,12 +15,15 @@ export function createHerdrService(parent, id) {
14
15
  saveParent(record);
15
16
  const client = new HerdrClient({ socketPath: parent.herdrSocket });
16
17
  let handler;
17
- const watcher = new Watcher({ client, parentId: record.id, onEntries: (entries) => handler?.(entries) });
18
- const context = { client, parentId: record.id, watcher };
18
+ // One client per herdr host, shared by the tools and the watcher, so a
19
+ // machine's bridge is dialled per request and its profile looked up once.
20
+ const clientFor = machineClients(client);
21
+ const watcher = new Watcher({ client, clientFor, parentId: record.id, onEntries: (entries) => handler?.(entries) });
22
+ const context = { client, clientFor, parentId: record.id, watcher };
19
23
  const paneWatches = new Set();
20
24
  watcher.start();
21
25
  return {
22
- tool: (name, args) => runBellwetherTool(context, name, args),
26
+ tool: (name, args, caller) => runBellwetherTool(context, name, args, caller),
23
27
  markRead: (receipts) => {
24
28
  for (const receipt of receipts)
25
29
  watcher.markRead(receipt);
@@ -27,7 +31,7 @@ export function createHerdrService(parent, id) {
27
31
  onEvents: (next) => {
28
32
  handler = next;
29
33
  },
30
- pending: () => watcher.outboxEntries().filter((entry) => !entry.read).map((entry) => ({ ...entry, deliveredAt: undefined })),
34
+ pending: () => watcher.pendingEntries().map((entry) => ({ ...entry, deliveredAt: undefined })),
31
35
  watchPane: (paneId, handler) => {
32
36
  const controller = new AbortController();
33
37
  const watch = { close: () => controller.abort() };
@@ -14,7 +14,8 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
14
14
  import { DaemonClient } from '../../daemon/client.js';
15
15
  import { resolveSocketPath } from '../../core/herdr-client.js';
16
16
  import { hostName } from '../../core/spawn.js';
17
- import { childTools, parentTools } from '../tools.js';
17
+ import { childLabel } from '../../core/label.js';
18
+ import { toolsFor } from '../tools.js';
18
19
  import { ReceiptScan, claudeConfigDir } from './transcript.js';
19
20
  const log = (...args) => console.error('[bellwether]', ...args);
20
21
  /** How long a burst of events settles before it is pushed, so churn collapses. */
@@ -28,8 +29,18 @@ const pane = process.env['HERDR_PANE_ID'];
28
29
  const workspace = process.env['HERDR_WORKSPACE_ID'];
29
30
  const cwd = process.env['CLAUDE_PROJECT_DIR'] ?? process.cwd();
30
31
  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;
32
+ /** The value after a flag, in the `--child <id>` or `--child=<id>` form. */
33
+ function argument(argv, flag) {
34
+ const index = argv.indexOf(flag);
35
+ if (index >= 0)
36
+ return argv[index + 1];
37
+ return argv.find((arg) => arg.startsWith(`${flag}=`))?.slice(flag.length + 1);
38
+ }
39
+ // The spawn's MCP config names the child with --child. A server loaded some
40
+ // other way may still sit in a child's pane, so it passes the id its tab
41
+ // carries, and the daemon checks either one against the record it holds.
42
+ const childId = argument(process.argv.slice(2), '--child') ?? process.env['BELLWETHER_CHILD'];
43
+ const tools = toolsFor({ parent: process.env['BELLWETHER_PARENT'], child: childId });
33
44
  const mcp = new Server({ name: 'bellwether', version: '0.1.0' }, {
34
45
  capabilities: { experimental: { 'claude/channel': {} }, tools: {} },
35
46
  instructions: [
@@ -62,12 +73,12 @@ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
62
73
  });
63
74
  /** One channel event's text. The receipt rides in the text, not only in meta. */
64
75
  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.`;
76
+ return `[bellwether] ${childLabel({ name: entry.name, paneId: entry.paneId, id: entry.childId })} ${entry.event}, a ${entry.kind} agent — receipt ${entry.receipt}\n${entry.text}\n\nRead more with agent_read. Reply with agent_send.`;
66
77
  }
67
78
  async function push(entry) {
68
79
  await mcp.notification({
69
80
  method: 'notifications/claude/channel',
70
- params: { content: compose(entry), meta: { child: entry.name, event: entry.event, receipt: entry.receipt } },
81
+ params: { content: compose(entry), meta: { child: entry.name, pane: entry.paneId, child_id: entry.childId, event: entry.event, receipt: entry.receipt } },
71
82
  });
72
83
  }
73
84
  // Receipts this server has already pushed, and those sent once more after the
@@ -230,6 +241,7 @@ ready = (async () => {
230
241
  workspaceId: workspace,
231
242
  depth,
232
243
  herdrSocket: resolveSocketPath(),
244
+ childId,
233
245
  }, { log });
234
246
  daemon.onEvents((entries) => schedule(entries));
235
247
  }
@@ -7,7 +7,8 @@ import os from 'node:os';
7
7
  import { DaemonClient } from '../../daemon/client.js';
8
8
  import { resolveSocketPath } from '../../core/herdr-client.js';
9
9
  import { hostName } from '../../core/spawn.js';
10
- import { childTools, parentTools } from '../tools.js';
10
+ import { childLabel } from '../../core/label.js';
11
+ import { toolsFor } from '../tools.js';
11
12
  const result = (text) => ({ content: [{ type: 'text', text }], details: undefined });
12
13
  /** How many Bellwether generations deep this session sits. */
13
14
  function depthFromEnv() {
@@ -20,7 +21,7 @@ function compose(entries) {
20
21
  return '';
21
22
  const head = entries.length === 1 ? '[bellwether]' : `[bellwether] ${entries.length} children changed`;
22
23
  const body = entries
23
- .map((entry) => `${entry.name} (${entry.kind}, ${entry.paneId}) ${entry.event} — receipt ${entry.receipt}\n${entry.text}`)
24
+ .map((entry) => `${childLabel({ name: entry.name, paneId: entry.paneId, id: entry.childId })} ${entry.event}, a ${entry.kind} agent — receipt ${entry.receipt}\n${entry.text}`)
24
25
  .join('\n\n');
25
26
  return `${head}\n${body}\n\nRead more with agent_read. Reply with agent_send.`;
26
27
  }
@@ -65,6 +66,7 @@ export default function bellwether(pi) {
65
66
  workspaceId: process.env['HERDR_WORKSPACE_ID'],
66
67
  depth: depthFromEnv(),
67
68
  herdrSocket: resolveSocketPath(),
69
+ childId: process.env['BELLWETHER_CHILD'],
68
70
  }, { log: (message) => console.error('[bellwether]', message) });
69
71
  daemon.onEvents(onEntries);
70
72
  const missed = await daemon.pending();
@@ -93,7 +95,7 @@ export default function bellwether(pi) {
93
95
  if (receipts.length)
94
96
  daemon.receipts(receipts);
95
97
  });
96
- const tools = process.env['BELLWETHER_PARENT'] ? [...parentTools, ...childTools] : parentTools;
98
+ const tools = toolsFor({ parent: process.env['BELLWETHER_PARENT'], child: process.env['BELLWETHER_CHILD'] });
97
99
  for (const tool of tools) {
98
100
  pi.registerTool({
99
101
  name: tool.name,
@@ -1,31 +1,58 @@
1
- // The six Bellwether tools, in one list, so the Pi extension and the Claude
1
+ // The Bellwether tools, in one list, so the Pi extension and the Claude
2
2
  // MCP channel server register exactly the same names and schemas.
3
3
  import os from 'node:os';
4
4
  import fs from 'node:fs';
5
- import { HerdrApiError } from '../core/herdr-client.js';
6
5
  import { AGENT_KINDS, DEFAULT_MAX_DEPTH, spawnChild } from '../core/spawn.js';
7
- import { reportToParent } from '../core/report.js';
6
+ import { removeChildFiles } from '../core/mcp-config.js';
7
+ import { reportForCaller } from '../core/report.js';
8
8
  import { childById, readParent, updateChild } from '../core/registry.js';
9
+ import { adoptPane } from '../core/adopt.js';
10
+ import { LOCAL_HOST, hostOf } from '../core/machine.js';
11
+ import { spawnResume } from '../core/spawn-resume.js';
12
+ import { promptChild } from '../core/send.js';
13
+ import { RETIRE_TOOL, realRetireOps, requestRetirement } from '../core/retire.js';
14
+ function clientFor(ctx, host) {
15
+ if (ctx.clientFor)
16
+ return ctx.clientFor(host);
17
+ return host === LOCAL_HOST ? Promise.resolve(ctx.client) : Promise.reject(new Error(`This session cannot reach herdr machine ${host}.`));
18
+ }
19
+ const MACHINE_DESCRIPTION = 'A saved herdr machine, by label or id as `herdr machine list` shows it. Omit it for this machine. A child on another machine cannot call parent_report, because its report lands on that machine\'s disk, so Bellwether follows it through herdr status alone.';
9
20
  const optionalString = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
10
- /** The five tools any session gets. */
21
+ /** The tools any session gets. */
11
22
  export const parentTools = [
12
23
  {
13
24
  name: 'agent_spawn',
14
- description: 'Start a child coding agent in its own herdr tab, of any kind herdr can start. Bellwether watches it and starts your next turn when it reports, goes idle, blocks, stalls or exits. Give the prompt a concrete deliverable, and tell the child to call parent_report when it is done.',
25
+ description: 'Start a child coding agent in its own herdr tab, of any kind herdr can start. Bellwether watches it and starts your next turn when it reports, goes idle, blocks, stalls or exits. Give the prompt a concrete deliverable, and tell the child to call parent_report when it is done. With resume, the call is a message to an earlier child instead: a child herdr still shows gets the prompt as an ordinary message, with no new tab, and a retired one comes back in a new tab with its harness reopening the same session, under the same child id, so its history and unread events continue. Resume works for claude and pi children.',
15
26
  schema: {
16
27
  type: 'object',
17
28
  properties: {
18
- kind: { type: 'string', enum: [...AGENT_KINDS], description: 'The harness to start: pi, claude, codex, opencode or cline.' },
19
- name: { type: 'string', description: 'A short handle for the child, unique in this session. Used as the herdr agent name and the tab label.' },
29
+ resume: { type: 'string', description: 'Message an earlier child rather than start a new one: its name, its id, or its session id. herdr decides whether it is alive. A session id no child of this session ran also takes kind, name, cwd and machine, and comes back as a new child. Omit it to start a new child.' },
30
+ kind: { type: 'string', enum: [...AGENT_KINDS], description: 'The harness to start: pi, claude, codex, opencode or cline. Required without resume.' },
31
+ name: { type: 'string', description: 'A short handle for the child, unique in this session. Used as the herdr agent name and the tab label. Required without resume.' },
20
32
  cwd: { type: 'string', description: 'The directory to start the child in. Use an absolute path, ideally a git worktree of its own.' },
21
- prompt: { type: 'string', description: 'The first message the child receives. The whole prompt, not a path.' },
33
+ prompt: { type: 'string', description: 'The first message the child receives, or with resume the message for the earlier child. The whole prompt, not a path. Line breaks and any length are fine: Bellwether hands a new or resumed child the prompt through a private file.' },
22
34
  model: { type: 'string', description: 'The model or tier to pass to the child harness.' },
23
35
  args: { type: 'array', items: { type: 'string' }, description: 'Extra arguments for the child harness, passed through unchanged and appended last.' },
24
36
  focus: { type: 'boolean', description: 'Move your view to the new tab. Defaults to false, so the child does not steal focus.' },
25
37
  stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
38
+ inactive_minutes: { type: 'number', description: 'How long the child may show no activity of any kind, blocked included, before you are told. Defaults to 5. Clamped to between 1 and 1440. It cannot be turned off.' },
26
39
  max_depth: { type: 'number', description: 'How deep children may spawn children. Defaults to 2.' },
40
+ machine: { type: 'string', description: `${MACHINE_DESCRIPTION} With resume, a known child always goes back to its own machine.` },
41
+ },
42
+ },
43
+ },
44
+ {
45
+ name: 'agent_adopt',
46
+ description: 'Make a running agent that this session did not start into its child, such as one herdr-spawn.sh or a person started. Bellwether then watches it like a spawned child. Refuses a pane another session already watches, and a pane with no agent herdr recognizes. An adopted child has no BELLWETHER_PARENT, so it cannot call parent_report.',
47
+ schema: {
48
+ type: 'object',
49
+ properties: {
50
+ target: { type: 'string', description: 'The pane id, or the herdr name of the live agent.' },
51
+ name: { type: 'string', description: 'The handle to use for the child. Defaults to its herdr name.' },
52
+ machine: { type: 'string', description: MACHINE_DESCRIPTION },
53
+ stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
27
54
  },
28
- required: ['kind', 'name'],
55
+ required: ['target'],
29
56
  },
30
57
  },
31
58
  {
@@ -86,8 +113,29 @@ export const childTools = [
86
113
  },
87
114
  },
88
115
  ];
116
+ /** The tool a child Bellwether spawned gets, when its environment carries BELLWETHER_CHILD. */
117
+ export const retireTools = [
118
+ {
119
+ name: RETIRE_TOOL,
120
+ description: 'Ask to be retired once you exit: the Bellwether daemon then removes your worktree and deletes your branch, but only after your pane and tab are gone, the worktree is not a main worktree, is clean and has no stash, the branch is merged or pushed with its pull request merged or closed, and no process works inside it. The call removes nothing. It runs the checks it can run now and says which pass, records the request, and leaves the rest to the daemon. Close your tab afterwards.',
121
+ schema: {
122
+ type: 'object',
123
+ properties: {
124
+ reason: { type: 'string', description: 'Why the work is finished, kept on your record and in the retire log.' },
125
+ },
126
+ },
127
+ },
128
+ ];
129
+ /**
130
+ * The tools a session gets, from its environment: every session gets the
131
+ * parent tools, a session with a parent also gets parent_report, and only a
132
+ * session with a child id gets the retirement request.
133
+ */
134
+ export function toolsFor(env) {
135
+ return [...parentTools, ...(env.parent || env.child ? childTools : []), ...(env.child ? retireTools : [])];
136
+ }
89
137
  export function toolSchema(name) {
90
- return [...parentTools, ...childTools].find((tool) => tool.name === name)?.schema;
138
+ return [...parentTools, ...childTools, ...retireTools].find((tool) => tool.name === name)?.schema;
91
139
  }
92
140
  function resolve(record, child) {
93
141
  return record ? childById(record, child) : undefined;
@@ -95,22 +143,55 @@ function resolve(record, child) {
95
143
  function describeChild(child, watcher) {
96
144
  const unread = watcher.outboxEntries().filter((entry) => !entry.read && entry.childId === child.id).length;
97
145
  const age = Math.max(0, Math.round((Date.now() - Date.parse(child.startedAt)) / 1000));
98
- const state = child.exitedAt ? `exited${child.exitCode === undefined ? '' : ` (${child.exitCode})`}` : child.lastStatus;
99
- return `${child.name}\t${child.kind}\t${state}\t${age}s\t${child.paneId}\tunread ${unread}\t${child.cwd ?? ''}`;
146
+ const retire = child.retireOutcome === 'removed' ? ', retired' : child.retireOutcome === 'refused' ? ', retirement refused' : child.retireRequestedAt ? ', retirement requested' : '';
147
+ const state = `${child.exitedAt ? `exited${child.exitCode === undefined ? '' : ` (${child.exitCode})`}` : child.lastStatus}${retire}`;
148
+ return `${child.name}\t${child.kind}\t${state}\t${age}s\t${hostOf(child)}\t${child.paneId}\tunread ${unread}\t${child.cwd ?? ''}`;
100
149
  }
101
- export async function runBellwetherTool(ctx, name, args) {
102
- const record = readParent(ctx.parentId);
103
- if (!record)
104
- throw new Error(`No Bellwether registry for ${ctx.parentId}. Start a session with the Bellwether extension loaded.`);
150
+ /**
151
+ * Run one tool for a session. `caller` is the identity the session's adapter
152
+ * sent with the call; parent_report routes by it and by the child records
153
+ * this daemon holds, never by the daemon's own environment.
154
+ */
155
+ export async function runBellwetherTool(ctx, name, args, caller = {}) {
105
156
  if (name === 'parent_report') {
106
157
  const status = optionalString(args['status']);
107
158
  const text = optionalString(args['text']);
108
159
  if (!status || !text)
109
160
  throw new Error('parent_report needs both status and text');
110
- const written = reportToParent(status, text);
111
- if (!written)
112
- throw new Error('This session has no BELLWETHER_PARENT, so there is nobody to report to.');
113
- return `Reported ${status} to the parent.`;
161
+ const written = reportForCaller(caller, status, text);
162
+ return `Reported ${status} to the parent, as ${written.childName}.`;
163
+ }
164
+ if (name === RETIRE_TOOL) {
165
+ // Routed by the caller's identity and this daemon's records, like parent_report.
166
+ return requestRetirement(caller, ctx.retireOps ?? realRetireOps(), optionalString(args['reason']));
167
+ }
168
+ const record = readParent(ctx.parentId);
169
+ if (!record)
170
+ throw new Error(`No Bellwether registry for ${ctx.parentId}. Start a session with the Bellwether extension loaded.`);
171
+ if (name === 'agent_spawn' && optionalString(args['resume'])) {
172
+ const result = await spawnResume((host) => clientFor(ctx, host), ctx.parentId, {
173
+ target: optionalString(args['resume']) ?? '',
174
+ prompt: optionalString(args['prompt']),
175
+ kind: optionalString(args['kind']),
176
+ name: optionalString(args['name']),
177
+ cwd: optionalString(args['cwd']),
178
+ host: optionalString(args['machine']),
179
+ model: optionalString(args['model']),
180
+ args: Array.isArray(args['args']) ? args['args'] : undefined,
181
+ focus: args['focus'] === true,
182
+ });
183
+ const { child } = result;
184
+ const lines = result.corrected ? [result.corrected] : [];
185
+ if (result.action === 'messaged') {
186
+ if (result.corrected)
187
+ ctx.watcher.reset(child.id);
188
+ lines.push(`${child.name} is still alive in pane ${child.paneId}, so the prompt went to it as a message, with no new tab.`, result.reply, `herdr link: ${result.link}`);
189
+ return lines.join('\n');
190
+ }
191
+ ctx.watcher.reset(child.id);
192
+ const where = child.host === LOCAL_HOST ? '' : ` on machine ${child.host}`;
193
+ lines.push(`${child.name} resumed session ${result.session.value}${where} in pane ${child.paneId}, as the same child ${child.id}.`, 'Bellwether watches it again, and its earlier events and receipts carry on.', `herdr link: ${result.link}`);
194
+ return lines.join('\n');
114
195
  }
115
196
  if (name === 'agent_spawn') {
116
197
  const options = {
@@ -122,17 +203,37 @@ export async function runBellwetherTool(ctx, name, args) {
122
203
  args: Array.isArray(args['args']) ? args['args'] : undefined,
123
204
  focus: args['focus'] === true,
124
205
  stuckMinutes: typeof args['stuck_minutes'] === 'number' ? args['stuck_minutes'] : undefined,
206
+ inactiveMinutes: typeof args['inactive_minutes'] === 'number' ? args['inactive_minutes'] : undefined,
125
207
  maxDepth: typeof args['max_depth'] === 'number' ? args['max_depth'] : DEFAULT_MAX_DEPTH,
208
+ host: optionalString(args['machine']) ?? LOCAL_HOST,
126
209
  };
210
+ if (!optionalString(args['kind']))
211
+ throw new Error('agent_spawn needs a kind for a new child, or resume to message an earlier one.');
127
212
  if (!options.name)
128
- throw new Error('agent_spawn needs a name');
129
- const { child, link } = await spawnChild(ctx.client, record, options);
130
- return [`${child.name} started as a ${child.kind} agent in pane ${child.paneId}, tab ${child.tabId ?? child.paneId}.`, `Bellwether watches it, and your next turn starts when it changes state.`, `herdr link: ${link}`].join('\n');
213
+ throw new Error('agent_spawn needs a name for a new child, or resume to message an earlier one.');
214
+ // Resolve the machine before anything is written, so a typo leaves no record.
215
+ const client = await clientFor(ctx, options.host ?? LOCAL_HOST);
216
+ const { child, link } = await spawnChild(client, record, options, undefined, { forget: (childId) => ctx.watcher.forget(childId) });
217
+ const where = child.host === LOCAL_HOST ? '' : ` on machine ${child.host}`;
218
+ const lines = [`${child.name} started as a ${child.kind} agent${where} in pane ${child.paneId}, tab ${child.tabId ?? child.paneId}.`, `Bellwether watches it, and your next turn starts when it changes state.`, `herdr link: ${link}`];
219
+ return lines.join('\n');
220
+ }
221
+ if (name === 'agent_adopt') {
222
+ const target = optionalString(args['target']);
223
+ if (!target)
224
+ throw new Error('agent_adopt needs a target: a pane id or a live agent name');
225
+ const host = optionalString(args['machine']) ?? LOCAL_HOST;
226
+ const client = await clientFor(ctx, host);
227
+ const { child, link, already } = await adoptPane(client, record, { target, host, name: optionalString(args['name']), stuckMinutes: typeof args['stuck_minutes'] === 'number' ? args['stuck_minutes'] : undefined });
228
+ if (already)
229
+ return `${child.name} in pane ${child.paneId} is already a child of this session.`;
230
+ const where = host === LOCAL_HOST ? '' : ` on machine ${host}`;
231
+ return [`Adopted ${child.name}, a ${child.kind} agent${where} in pane ${child.paneId}. Bellwether watches it from now on.`, 'It was not started by Bellwether, so it cannot call parent_report; its status changes still start your turns.', `herdr link: ${link}`].join('\n');
131
232
  }
132
233
  if (name === 'agent_list') {
133
234
  if (!record.children.length)
134
235
  return 'No children yet. Start one with agent_spawn.';
135
- const header = 'name\tkind\tstate\tage\tpane\tunread\tcwd';
236
+ const header = 'name\tkind\tstate\tage\thost\tpane\tunread\tcwd';
136
237
  return [header, ...record.children.map((child) => describeChild(child, ctx.watcher))].join('\n');
137
238
  }
138
239
  const target = optionalString(args['child']);
@@ -141,10 +242,12 @@ export async function runBellwetherTool(ctx, name, args) {
141
242
  const child = resolve(record, target);
142
243
  if (!child)
143
244
  throw new Error(`No child of this session matches "${target}". Call agent_list to see them.`);
245
+ // Pane ids are scoped to one herdr server, so every call goes to the child's host.
246
+ const herdr = await clientFor(ctx, hostOf(child));
144
247
  if (name === 'agent_read') {
145
248
  const lines = typeof args['lines'] === 'number' ? args['lines'] : undefined;
146
249
  if (lines)
147
- return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines })).trim();
250
+ return (await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines })).trim();
148
251
  if (child.transcript) {
149
252
  try {
150
253
  const content = fs.readFileSync(child.transcript, 'utf8');
@@ -176,41 +279,32 @@ export async function runBellwetherTool(ctx, name, args) {
176
279
  // Fall through to the screen.
177
280
  }
178
281
  }
179
- return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 })).trim();
282
+ return (await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 })).trim();
180
283
  }
181
284
  if (name === 'agent_send') {
182
285
  const text = optionalString(args['text']);
183
286
  const keys = Array.isArray(args['keys']) ? args['keys'] : undefined;
184
287
  if (keys?.length) {
185
- await ctx.client.sendKeys(child.paneId, keys);
288
+ await herdr.sendKeys(child.paneId, keys);
186
289
  return `Sent ${keys.join(' ')} to ${child.name}.`;
187
290
  }
188
291
  if (!text)
189
292
  throw new Error('agent_send needs text or keys');
190
- try {
191
- await ctx.client.agentPrompt(child.paneId, text);
192
- return `Prompted ${child.name}.`;
193
- }
194
- catch (error) {
195
- if (error instanceof HerdrApiError && child.lastStatus === 'blocked') {
196
- const dialog = await ctx.client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }).catch(() => '');
197
- return `herdr refused the prompt because ${child.name} is blocked. The dialog:\n${dialog.trim()}\n\nReply with agent_send keys, for example ["enter"] or ["down","enter"].`;
198
- }
199
- throw error;
200
- }
293
+ return promptChild(herdr, child, text);
201
294
  }
202
295
  if (name === 'agent_stop') {
203
296
  if (!args['force'] && (child.lastStatus === 'working' || child.lastStatus === 'blocked')) {
204
- const tail = await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 20 }).catch(() => '');
297
+ const tail = await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 20 }).catch(() => '');
205
298
  return `${child.name} is ${child.lastStatus}, so agent_stop refused to close it. Pass force to close it anyway.\n${tail.trim()}`;
206
299
  }
207
300
  if (child.tabId)
208
- await ctx.client.tabClose(child.tabId);
301
+ await herdr.tabClose(child.tabId);
209
302
  else
210
- await ctx.client.paneClose(child.paneId);
303
+ await herdr.paneClose(child.paneId);
211
304
  updateChild(ctx.parentId, child.id, (entry) => {
212
305
  entry.exitedAt = new Date().toISOString();
213
306
  });
307
+ removeChildFiles(child.id);
214
308
  return `Closed ${child.name}.`;
215
309
  }
216
310
  throw new Error(`Bellwether has no tool named ${name}`);