@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.
@@ -0,0 +1,134 @@
1
+ // Reaching a herdr server on another machine. herdr's own `--machine` prefix
2
+ // runs `herdr --session <s> remote-api-bridge` over SSH on the saved profile's
3
+ // target, and speaks the socket protocol over that process's stdio. Bellwether
4
+ // does the same, so a subscription to a remote pane works like a local one.
5
+ import { execFile, spawn } from 'node:child_process';
6
+ import { EventEmitter } from 'node:events';
7
+ import { HerdrClient } from './herdr-client.js';
8
+ /** The host a child runs on when no machine was named: this machine's herdr. */
9
+ export const LOCAL_HOST = 'local';
10
+ /** The capability string a bridge-capable herdr prints for `remote-api-bridge --check`. */
11
+ const BRIDGE_CAPABILITY = 'herdr-api-bridge-v1';
12
+ /**
13
+ * The remote side: find a herdr that can bridge, the way herdr's own forwarding
14
+ * does, because a non-interactive SSH shell often has no herdr on its PATH.
15
+ */
16
+ const BRIDGE_SCRIPT = [
17
+ 'for c in "$(command -v herdr 2>/dev/null)" "$HOME/.local/bin/herdr" /home/linuxbrew/.linuxbrew/bin/herdr /opt/homebrew/bin/herdr /usr/local/bin/herdr; do',
18
+ ' [ -n "$c" ] && [ -x "$c" ] || continue',
19
+ ` if [ "$("$c" --session "$1" remote-api-bridge --check </dev/null 2>/dev/null)" = ${BRIDGE_CAPABILITY} ]; then exec "$c" --session "$1" remote-api-bridge; fi`,
20
+ 'done',
21
+ "echo 'no herdr on this machine can bridge the API; update herdr there' >&2",
22
+ 'exit 78',
23
+ ].join('\n');
24
+ function shellQuote(value) {
25
+ return `'${value.replace(/'/g, `'\\''`)}'`;
26
+ }
27
+ /** The command line SSH runs on the remote machine. */
28
+ export function bridgeCommand(session) {
29
+ return `sh -c ${shellQuote(BRIDGE_SCRIPT)} bellwether-bridge ${shellQuote(session)}`;
30
+ }
31
+ /** Dial a machine's herdr through an SSH process whose stdio is the connection. */
32
+ export function bridgeDialer(profile, ssh = 'ssh') {
33
+ return (onReady) => {
34
+ const child = spawn(ssh, ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-T', profile.target, bridgeCommand(profile.session)], { stdio: ['pipe', 'pipe', 'pipe'] });
35
+ const events = new EventEmitter();
36
+ let stderr = '';
37
+ let failed = false;
38
+ const fail = (error) => {
39
+ if (failed)
40
+ return;
41
+ failed = true;
42
+ events.emit('error', error);
43
+ };
44
+ child.on('spawn', onReady);
45
+ child.on('error', fail);
46
+ child.stdin.on('error', () => { });
47
+ child.stdout.on('data', (chunk) => events.emit('data', chunk));
48
+ child.stderr.on('data', (chunk) => {
49
+ stderr = `${stderr}${chunk.toString('utf8')}`.slice(-2000);
50
+ });
51
+ // Wait for the process to close rather than for stdout to end, so a failed
52
+ // bridge reports its stderr instead of a bare closed connection.
53
+ child.on('close', (code, signal) => {
54
+ if (code === 0 || signal === 'SIGTERM')
55
+ events.emit('end');
56
+ else
57
+ fail(new Error(`the herdr bridge to machine ${profile.label} exited with ${code ?? signal}${stderr.trim() ? `: ${stderr.trim()}` : ''}`));
58
+ });
59
+ const connection = {
60
+ write: (line) => child.stdin.write(line),
61
+ on: (event, listener) => events.on(event, listener),
62
+ destroy: () => {
63
+ if (child.exitCode === null)
64
+ child.kill('SIGTERM');
65
+ },
66
+ unref: () => {
67
+ child.unref();
68
+ for (const stream of [child.stdin, child.stdout, child.stderr])
69
+ stream.unref?.();
70
+ },
71
+ };
72
+ return connection;
73
+ };
74
+ }
75
+ function isRecord(value) {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+ /** Parse `herdr machine list --json`. */
79
+ export function parseMachineList(text) {
80
+ const value = JSON.parse(text);
81
+ if (!Array.isArray(value))
82
+ throw new Error('herdr machine list did not print a list');
83
+ return value.filter(isRecord).flatMap((entry) => {
84
+ const { id, label, target, session, enabled } = entry;
85
+ if (typeof id !== 'string' || typeof label !== 'string' || typeof target !== 'string')
86
+ return [];
87
+ return [{ id, label, target, session: typeof session === 'string' && session ? session : 'default', enabled: enabled !== false }];
88
+ });
89
+ }
90
+ /** Pick a profile the way herdr does: by id, or by a unique, case-sensitive label. */
91
+ export function pickMachine(profiles, selector) {
92
+ const byId = profiles.find((profile) => profile.id === selector);
93
+ const byLabel = profiles.filter((profile) => profile.label === selector);
94
+ const profile = byId ?? (byLabel.length === 1 ? byLabel[0] : undefined);
95
+ if (!profile) {
96
+ const known = profiles.map((entry) => entry.label).join(', ') || 'none';
97
+ throw new Error(byLabel.length > 1 ? `more than one saved herdr machine is labelled ${selector}; name it by id` : `herdr has no saved machine ${selector}. Saved machines: ${known}.`);
98
+ }
99
+ if (!profile.enabled)
100
+ throw new Error(`the herdr machine ${selector} is disabled`);
101
+ return profile;
102
+ }
103
+ /** Ask the local herdr for its saved machines. */
104
+ export const resolveMachine = (selector) => new Promise((resolve, reject) => {
105
+ execFile('herdr', ['machine', 'list', '--json'], { timeout: 10_000 }, (error, stdout) => {
106
+ if (error)
107
+ return reject(new Error(`herdr machine list failed: ${error.message}`));
108
+ try {
109
+ resolve(pickMachine(parseMachineList(stdout), selector));
110
+ }
111
+ catch (fault) {
112
+ reject(fault);
113
+ }
114
+ });
115
+ });
116
+ export function machineClients(local, resolve = resolveMachine) {
117
+ const clients = new Map();
118
+ return (host) => {
119
+ if (host === LOCAL_HOST)
120
+ return Promise.resolve(local);
121
+ let client = clients.get(host);
122
+ if (!client) {
123
+ client = resolve(host).then((profile) => new HerdrClient({ dial: bridgeDialer(profile), label: `machine:${profile.label}` }));
124
+ // A failed lookup is not cached, so a machine saved later still works.
125
+ client.catch(() => clients.delete(host));
126
+ clients.set(host, client);
127
+ }
128
+ return client;
129
+ };
130
+ }
131
+ /** The host a child record names, with an older record read as local. */
132
+ export function hostOf(child) {
133
+ return child.host ?? LOCAL_HOST;
134
+ }
@@ -0,0 +1,47 @@
1
+ // A Claude Code child's own Bellwether MCP server. The spawn writes a private
2
+ // configuration that names this package's channel entry point and the child
3
+ // id, and starts the child with --mcp-config pointing at it. The server is a
4
+ // client of the machine's one daemon: it sends the child id and its pane with
5
+ // every call, and the daemon resolves them against the child record it holds.
6
+ // Nothing about the child's identity rides in the server's environment.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { removeBrief } from './brief.js';
11
+ import { mcpConfigPath, mcpDir } from './paths.js';
12
+ /** The name the child's channel flag loads, `server:bellwether`. */
13
+ export const MCP_SERVER_NAME = 'bellwether';
14
+ /**
15
+ * The packaged channel entry point. From the sources this file is
16
+ * mcp-config.ts and the entry is channel.ts; from the build, both end in .js.
17
+ */
18
+ export function channelEntry() {
19
+ return fileURLToPath(new URL(`../integrations/claude/channel${path.extname(import.meta.url)}`, import.meta.url));
20
+ }
21
+ /** The configuration that starts one child's server: this Node, the channel entry, the child id. */
22
+ export function mcpConfig(childId) {
23
+ return {
24
+ mcpServers: {
25
+ [MCP_SERVER_NAME]: { type: 'stdio', command: process.execPath, args: ['--disable-warning=ExperimentalWarning', channelEntry(), '--child', childId] },
26
+ },
27
+ };
28
+ }
29
+ /** Write the child's configuration with mode 0600 in a 0700 directory, and return its path. */
30
+ export function writeMcpConfig(childId) {
31
+ const dir = mcpDir();
32
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
33
+ fs.chmodSync(dir, 0o700);
34
+ const file = mcpConfigPath(childId);
35
+ fs.writeFileSync(file, `${JSON.stringify(mcpConfig(childId), null, 2)}\n`, { mode: 0o600 });
36
+ fs.chmodSync(file, 0o600);
37
+ return file;
38
+ }
39
+ /** Remove a child's configuration. One that is already gone is not an error. */
40
+ export function removeMcpConfig(childId) {
41
+ fs.rmSync(mcpConfigPath(childId), { force: true });
42
+ }
43
+ /** Remove every file a spawn wrote for a child: its brief and its MCP configuration. */
44
+ export function removeChildFiles(childId) {
45
+ removeBrief(childId);
46
+ removeMcpConfig(childId);
47
+ }
@@ -12,8 +12,39 @@ export function newReceipt() {
12
12
  export function newChildId() {
13
13
  return crypto.randomBytes(8).toString('hex');
14
14
  }
15
+ /**
16
+ * Whether a newer state has made an unread entry stale. A blocked entry is
17
+ * stale once the child has left the blocked state, which is how a dialog that
18
+ * someone already answered stopped being reported minutes later. A stuck entry
19
+ * is stale once the child moves. An inactive entry is stale once the child
20
+ * shows activity after it was written. When herdr reported a state_change_seq for
21
+ * both, the child's must also be the newer one. A report, an idle event and an
22
+ * exit carry what the child said or did, so they are never dropped.
23
+ */
24
+ export function isSuperseded(entry, child) {
25
+ if (!child || entry.read)
26
+ return false;
27
+ const newer = entry.stateChangeSeq === undefined || child.stateChangeSeq === undefined || child.stateChangeSeq > entry.stateChangeSeq;
28
+ if (entry.event === 'blocked')
29
+ return Boolean(child.exitedAt) || (child.lastStatus !== 'blocked' && newer);
30
+ if (entry.event === 'stuck') {
31
+ if (child.exitedAt)
32
+ return true;
33
+ const moved = Date.parse(child.lastBusyAt) > Date.parse(entry.at);
34
+ return moved || (child.lastStatus !== 'working' && child.lastStatus !== 'unknown' && newer);
35
+ }
36
+ // An inactive notice says the child was quiet. Activity after it was written
37
+ // makes it false, so the notice is dropped rather than delivered late.
38
+ if (entry.event === 'inactive') {
39
+ const at = Date.parse(entry.at);
40
+ return Date.parse(child.lastBusyAt) > at || Date.parse(child.statusChangedAt) > at;
41
+ }
42
+ return false;
43
+ }
15
44
  export class Outbox {
16
45
  entries = [];
46
+ /** Entries settled without a receipt since the last takeSettled. */
47
+ settled = [];
17
48
  constructor(entries) {
18
49
  this.entries = entries;
19
50
  }
@@ -35,16 +66,43 @@ export class Outbox {
35
66
  }
36
67
  /**
37
68
  * Offer an event for a child. A newer event replaces an older unread one, so
38
- * a child that goes quiet then blocked produces one message, not two.
69
+ * a child that goes quiet then blocked produces one message, not two. The
70
+ * older entry keeps its receipt and is settled as superseded, so a client
71
+ * that already holds it learns to drop it rather than send it again.
39
72
  */
40
73
  offer(entry) {
41
- const existing = this.entries.find((candidate) => candidate.childId === entry.childId && !candidate.read);
42
74
  const next = { ...entry, receipt: newReceipt(), read: false };
43
- if (existing)
44
- Object.assign(existing, next);
45
- else
46
- this.entries.push(next);
47
- return existing ?? next;
75
+ for (const existing of this.entries) {
76
+ if (existing.childId !== entry.childId || existing.read)
77
+ continue;
78
+ this.settle(existing, next.receipt);
79
+ }
80
+ this.entries.push(next);
81
+ return next;
82
+ }
83
+ /**
84
+ * Settle every unread entry a newer child state has made stale. Called at
85
+ * delivery, so a queued entry is checked against the child as it is now.
86
+ */
87
+ settleSuperseded(children) {
88
+ const settled = [];
89
+ for (const entry of this.entries) {
90
+ const child = children.find((candidate) => candidate.id === entry.childId);
91
+ if (!isSuperseded(entry, child))
92
+ continue;
93
+ this.settle(entry, `state:${child?.exitedAt ? 'exited' : child?.lastStatus ?? 'unknown'}`);
94
+ settled.push(entry);
95
+ }
96
+ return settled;
97
+ }
98
+ /** The entries settled without a receipt since the last call, once each. */
99
+ takeSettled() {
100
+ return this.settled.splice(0);
101
+ }
102
+ settle(entry, by) {
103
+ entry.read = true;
104
+ entry.supersededBy = by;
105
+ this.settled.push(entry);
48
106
  }
49
107
  add(entry) {
50
108
  if (this.entries.some((candidate) => candidate.receipt === entry.receipt))
@@ -64,6 +122,13 @@ export class Outbox {
64
122
  if (entry)
65
123
  entry.deliveredAt = at;
66
124
  }
125
+ /** Drop every entry for a child, for one whose spawn failed. */
126
+ drop(childId) {
127
+ const before = this.entries.length;
128
+ this.entries = this.entries.filter((entry) => entry.childId !== childId);
129
+ this.settled = this.settled.filter((entry) => entry.childId !== childId);
130
+ return this.entries.length !== before;
131
+ }
67
132
  pending() {
68
133
  return this.entries.filter((entry) => !entry.read);
69
134
  }
@@ -13,6 +13,20 @@ export function outboxDir() {
13
13
  export function spoolDir() {
14
14
  return path.join(bellwetherHome(), 'spool');
15
15
  }
16
+ /** Each child's brief, kept off the command line. */
17
+ export function promptsDir() {
18
+ return path.join(bellwetherHome(), 'prompts');
19
+ }
20
+ export function promptPath(childId) {
21
+ return path.join(promptsDir(), `${slug(childId)}.md`);
22
+ }
23
+ /** Each Claude Code child's MCP configuration, passed with --mcp-config. */
24
+ export function mcpDir() {
25
+ return path.join(bellwetherHome(), 'mcp');
26
+ }
27
+ export function mcpConfigPath(childId) {
28
+ return path.join(mcpDir(), `${slug(childId)}.json`);
29
+ }
16
30
  /** One registry file per parent session, so a resumed parent reads the same file. */
17
31
  export function parentId(harness, session) {
18
32
  return `${harness}-${slug(session)}`;
@@ -5,12 +5,16 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { parentId, parentsDir, registryPath, slug } from './paths.js';
8
+ import { REGISTRY_SCHEMA } from './types.js';
9
+ /** The host of a child started before the registry recorded one. */
10
+ const LOCAL_HOST = 'local';
8
11
  export { parentId, slug };
9
12
  function ensure(dir) {
10
13
  fs.mkdirSync(dir, { recursive: true });
11
14
  }
12
15
  export function emptyParent(harness, session, cwd, extra = {}) {
13
16
  return {
17
+ schema: REGISTRY_SCHEMA,
14
18
  id: parentId(harness, session),
15
19
  harness,
16
20
  session,
@@ -28,15 +32,29 @@ export function readParent(id) {
28
32
  const parsed = JSON.parse(raw);
29
33
  if (typeof parsed !== 'object' || parsed === null)
30
34
  return undefined;
31
- const record = parsed;
32
- if (!Array.isArray(record.children))
33
- record.children = [];
34
- return record;
35
+ return migrateParent(parsed);
35
36
  }
36
37
  catch {
37
38
  return undefined;
38
39
  }
39
40
  }
41
+ /**
42
+ * Bring a record written by an older Bellwether up to the current layout. It
43
+ * only adds what is missing and never rewrites a field that is set, so it can
44
+ * run on every read. The file changes on the next write, not on the read.
45
+ */
46
+ export function migrateParent(record) {
47
+ if (!Array.isArray(record.children))
48
+ record.children = [];
49
+ for (const child of record.children) {
50
+ // Every child before version 2 ran on the parent's own herdr.
51
+ if (typeof child.host !== 'string' || !child.host)
52
+ child.host = LOCAL_HOST;
53
+ }
54
+ if (typeof record.schema !== 'number' || record.schema < REGISTRY_SCHEMA)
55
+ record.schema = REGISTRY_SCHEMA;
56
+ return record;
57
+ }
40
58
  export function listParents() {
41
59
  let files;
42
60
  try {
@@ -77,6 +95,12 @@ export function upsertChild(id, child) {
77
95
  record.children[index] = child;
78
96
  });
79
97
  }
98
+ /** Drop a child's record, for a spawn that never produced a running child. */
99
+ export function removeChild(id, childId) {
100
+ return mutateParent(id, (record) => {
101
+ record.children = record.children.filter((entry) => entry.id !== childId);
102
+ });
103
+ }
80
104
  export function updateChild(id, childId, change) {
81
105
  let updated;
82
106
  mutateParent(id, (record) => {
@@ -91,3 +115,15 @@ export function updateChild(id, childId, change) {
91
115
  export function childById(record, childId) {
92
116
  return record.children.find((child) => child.id === childId || child.name === childId || child.paneId === childId);
93
117
  }
118
+ /**
119
+ * The parent that watches a live pane on a host, if any. A child that exited
120
+ * no longer holds its pane, so it does not count.
121
+ */
122
+ export function watcherOfPane(host, paneId) {
123
+ for (const parent of listParents()) {
124
+ const child = parent.children.find((entry) => !entry.exitedAt && entry.paneId === paneId && (entry.host ?? LOCAL_HOST) === host);
125
+ if (child)
126
+ return { parent, child };
127
+ }
128
+ return undefined;
129
+ }
@@ -3,8 +3,9 @@
3
3
  // and the report still waits for the other one.
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { spoolPath } from './paths.js';
7
- import { readParent } from './registry.js';
6
+ import { LOCAL_HOST } from './machine.js';
7
+ import { mcpDir, spoolPath } from './paths.js';
8
+ import { listParents, readParent } from './registry.js';
8
9
  export function harnessForEnv() {
9
10
  if (process.env['BELLWETHER_HARNESS'])
10
11
  return process.env['BELLWETHER_HARNESS'];
@@ -32,7 +33,51 @@ export function writeReport(report) {
32
33
  fs.appendFileSync(target, `${JSON.stringify(entry)}\n`);
33
34
  return entry;
34
35
  }
35
- /** Report to the parent named in this session's environment. */
36
+ /**
37
+ * Find the child a caller speaks for, from the records this machine holds: by
38
+ * the child id its spawn handed it, or by the live pane it runs in. A child id
39
+ * whose record holds another pane is refused, because one of the two is wrong.
40
+ */
41
+ export function childOfCaller(caller) {
42
+ const parents = listParents();
43
+ if (caller.childId) {
44
+ for (const parent of parents) {
45
+ const child = parent.children.find((entry) => entry.id === caller.childId);
46
+ if (!child)
47
+ continue;
48
+ if (caller.paneId && child.paneId && child.paneId !== caller.paneId) {
49
+ throw new Error(`parent_report was called for child ${child.id}, whose record holds pane ${child.paneId}, from pane ${caller.paneId}. One of the two is stale, so nothing was reported. Resume the child with agent_spawn and resume, which writes a new MCP config for its new pane.`);
50
+ }
51
+ return { parent, child };
52
+ }
53
+ }
54
+ if (!caller.paneId)
55
+ return undefined;
56
+ for (const parent of parents) {
57
+ const child = parent.children.find((entry) => !entry.exitedAt && entry.paneId === caller.paneId && (entry.host ?? LOCAL_HOST) === LOCAL_HOST);
58
+ if (child)
59
+ return { parent, child };
60
+ }
61
+ return undefined;
62
+ }
63
+ /**
64
+ * Report for the child a daemon call came from. The daemon serves every
65
+ * session on the machine, so the parent comes from the child record the
66
+ * daemon holds, never from an environment variable.
67
+ */
68
+ export function reportForCaller(caller, status, text) {
69
+ const found = childOfCaller(caller);
70
+ if (!found) {
71
+ const where = caller.paneId ? `pane ${caller.paneId}` : 'a session that is not in a herdr pane';
72
+ const asked = caller.childId ? `child id ${caller.childId}, which no registry on this machine holds` : 'no child id';
73
+ throw new Error(`parent_report has nobody to report to: it was called from ${where} with ${asked}, and no Bellwether child runs in that pane. ` +
74
+ `A spawn starts each Claude Code child with --mcp-config=${path.join(mcpDir(), '<child id>.json')}, which names the child to its server. ` +
75
+ 'A server loaded from a user-level mcpServers entry in a pane Bellwether did not start, or a child on another machine, has no record here.');
76
+ }
77
+ const { parent, child } = found;
78
+ return writeReport({ parentId: parent.id, parentPaneId: parent.paneId, childId: child.id, childName: child.name, paneId: child.paneId || caller.paneId, status, text });
79
+ }
80
+ /** Report to the parent named in this session's environment. The CLI uses it from a child's own shell. */
36
81
  export function reportToParent(status, text) {
37
82
  const parentId = parentFromEnv();
38
83
  if (!parentId)
@@ -0,0 +1,210 @@
1
+ // Bringing a child back. A child that exited keeps its record, so a spawn with
2
+ // a resume target (see spawn-resume.ts) opens a new tab on the host the child ran on, starts the harness with its
3
+ // session's resume flag, and puts the new pane under the same child id. The
4
+ // child's outbox entries and receipts are keyed by that id, so they continue.
5
+ import path from 'node:path';
6
+ import { writeBrief } from './brief.js';
7
+ import { removeChildFiles } from './mcp-config.js';
8
+ import { LOCAL_HOST } from './machine.js';
9
+ import { newChildId } from './outbox.js';
10
+ import { readParent, removeChild, updateChild, upsertChild } from './registry.js';
11
+ import { clearRetirement } from './retire.js';
12
+ import { STARTUP_HOLD_MS, STARTUP_TIMEOUT_MS, childArgs, childEnv, childMcpConfig, harnessOf, herdrLink, startWithRetry } from './spawn.js';
13
+ import { watchStartup } from './startup-dialogs.js';
14
+ import { resolveTranscript, sessionFrom } from './transcript.js';
15
+ import { resolveInactiveMs } from './inactivity.js';
16
+ /**
17
+ * The session a child record names: the one herdr reported, kept after exit.
18
+ * A record written before Bellwether kept it still has the transcript, which
19
+ * names the session too: Claude Code names the file after the session id, and
20
+ * Pi takes the file itself.
21
+ */
22
+ export function sessionOf(child) {
23
+ if (child.session?.value)
24
+ return { value: child.session.value, kind: child.session.kind === 'path' ? 'path' : 'id' };
25
+ if (!child.transcript)
26
+ return undefined;
27
+ if (child.harness === 'claude-code')
28
+ return { value: path.basename(child.transcript, '.jsonl'), kind: 'id' };
29
+ if (child.harness === 'pi')
30
+ return { value: child.transcript, kind: 'path' };
31
+ return undefined;
32
+ }
33
+ /** The arguments that make a harness reopen a session, or an error for one that cannot. */
34
+ export function resumeArgs(kind, session) {
35
+ if (kind === 'claude')
36
+ return ['--resume', session.kind === 'path' ? path.basename(session.value, '.jsonl') : session.value];
37
+ if (kind === 'pi')
38
+ return ['--session', session.value];
39
+ throw new Error(`Bellwether cannot resume a ${kind} agent: only claude and pi have a resume flag it knows. Call agent_spawn without resume to start a fresh ${kind} child.`);
40
+ }
41
+ /** Whether a live pane holds this session. Pi may report the path where a caller gave the id. */
42
+ export function holdsSession(pane, session) {
43
+ const live = pane.agentSessionId;
44
+ if (!live)
45
+ return false;
46
+ if (live === session.value)
47
+ return true;
48
+ const id = (value) => path.basename(value, '.jsonl');
49
+ return id(live) === id(session.value) || id(live).endsWith(`_${id(session.value)}`) || id(session.value).endsWith(`_${id(live)}`);
50
+ }
51
+ /** Find the child a resume names: by id, name or pane, then by the session it ran. */
52
+ export function findResumable(record, target) {
53
+ const direct = record.children.find((child) => child.id === target || child.name === target || child.paneId === target);
54
+ if (direct)
55
+ return direct;
56
+ return record.children.find((child) => {
57
+ const session = sessionOf(child);
58
+ return session !== undefined && (session.value === target || path.basename(session.value, '.jsonl') === target || session.value.endsWith(`_${target}.jsonl`));
59
+ });
60
+ }
61
+ export async function resumeChild(client, parent, target, options = {}, signal) {
62
+ const now = new Date().toISOString();
63
+ const existing = target.child;
64
+ const kind = existing?.kind ?? target.kind;
65
+ if (!kind)
66
+ throw new Error('A session no child of this parent ran needs a kind, claude or pi, to resume it.');
67
+ // A harness with no resume flag fails here, before anything is written.
68
+ resumeArgs(kind, { value: '', kind: 'id' });
69
+ const session = target.session ?? (existing ? sessionOf(existing) : undefined);
70
+ if (!session) {
71
+ throw new Error(existing ? `${existing.name} has no recorded session, so there is nothing to resume. Pass resume with the session id and kind to reopen it as a new child.` : 'A resume needs a child of this session or a session id.');
72
+ }
73
+ const args = resumeArgs(kind, session);
74
+ // Refuse a second copy of a session that still runs, here or in any pane.
75
+ const panes = await client.agentList(signal);
76
+ if (existing && !existing.exitedAt) {
77
+ const pane = panes.find((entry) => entry.paneId === existing.paneId);
78
+ if (pane?.agent)
79
+ throw new Error(`${existing.name} is still alive in pane ${existing.paneId}, so Bellwether refused to start a second copy. Talk to it with agent_send.`);
80
+ }
81
+ const holder = panes.find((pane) => holdsSession(pane, session));
82
+ if (holder)
83
+ throw new Error(`Session ${session.value} is still alive in pane ${holder.paneId}${holder.name ? ` (${holder.name})` : ''}, so Bellwether refused to start a second copy.`);
84
+ const child = existing
85
+ ? { ...existing }
86
+ : {
87
+ id: newChildId(),
88
+ name: target.name ?? `resumed-${path.basename(session.value, '.jsonl').slice(-8)}`,
89
+ kind,
90
+ harness: harnessOf(kind),
91
+ paneId: '',
92
+ host: target.host ?? LOCAL_HOST,
93
+ origin: 'resume',
94
+ cwd: target.cwd,
95
+ startedAt: now,
96
+ lastStatus: 'unknown',
97
+ statusChangedAt: now,
98
+ lastBusyAt: now,
99
+ depth: parent.depth + 1,
100
+ inactiveMs: resolveInactiveMs(undefined),
101
+ };
102
+ const previous = existing ? { paneId: existing.paneId, tabId: existing.tabId, exitedAt: existing.exitedAt ?? now, exitCode: existing.exitCode } : undefined;
103
+ // 1. The record lands first, with no pane, so a crash still says what was asked.
104
+ child.paneId = '';
105
+ delete child.tabId;
106
+ delete child.exitedAt;
107
+ delete child.exitCode;
108
+ delete child.reportPending;
109
+ // A child brought back did not ask for this run to end its worktree.
110
+ clearRetirement(child);
111
+ child.lastStatus = 'unknown';
112
+ child.statusChangedAt = now;
113
+ child.lastBusyAt = now;
114
+ child.resumedAt = now;
115
+ upsertChild(parent.id, child);
116
+ const restore = () => {
117
+ removeChildFiles(child.id);
118
+ // A resume of a session no child ran made the record, so a failure drops
119
+ // it, as a failed spawn does: the parent hears nothing of a child that never ran.
120
+ if (!previous) {
121
+ removeChild(parent.id, child.id);
122
+ return;
123
+ }
124
+ updateChild(parent.id, child.id, (entry) => {
125
+ delete entry.startingUntil;
126
+ entry.paneId = previous.paneId;
127
+ entry.tabId = previous.tabId;
128
+ entry.exitedAt = previous.exitedAt;
129
+ entry.exitCode = previous.exitCode;
130
+ });
131
+ };
132
+ // 2. A new tab, with the same environment the child first started with.
133
+ // The prompt goes to a private file, like a spawn's brief, never into argv.
134
+ const workspaceId = options.workspaceId ?? (child.host === LOCAL_HOST ? parent.workspaceId : undefined);
135
+ let tabId;
136
+ let startup;
137
+ try {
138
+ const briefFile = options.prompt ? writeBrief(child.id, options.prompt) : undefined;
139
+ // The same child id as before, so the server resolves to the same record.
140
+ const mcpConfigFile = childMcpConfig({ id: child.id, kind, host: child.host });
141
+ const tab = await client.tabCreate({ workspaceId, cwd: child.cwd, label: child.name, env: childEnv(parent, child), focus: options.focus ?? false }, signal);
142
+ tabId = tab.tabId ?? tab.paneId;
143
+ if (!tab.paneId)
144
+ throw new Error('herdr created no pane for the resumed tab');
145
+ child.tabId = tab.tabId;
146
+ child.paneId = tab.paneId;
147
+ child.workspaceId = workspaceId;
148
+ // A resumed Claude Code child paints the same development-channel dialog
149
+ // as a new one, so the watcher holds its events while the resume answers.
150
+ if (kind === 'claude') {
151
+ const timeoutMs = options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS;
152
+ child.startingUntil = new Date(Date.now() + Math.max(STARTUP_HOLD_MS, timeoutMs + 15_000)).toISOString();
153
+ startup = await watchStartup(client, tab.paneId, signal, { timeoutMs, redrawMs: options.redrawMs });
154
+ }
155
+ upsertChild(parent.id, child);
156
+ // 3. Start the harness on the session.
157
+ await startWithRetry(client, { name: child.name, kind, paneId: tab.paneId, args: childArgs(kind, { kind, name: child.name, model: options.model, args: [...args, ...(options.args ?? [])] }, briefFile, mcpConfigFile) }, signal);
158
+ }
159
+ catch (error) {
160
+ startup?.close();
161
+ if (tabId)
162
+ await client.tabClose(tabId).catch(() => { });
163
+ delete child.startingUntil;
164
+ restore();
165
+ throw error;
166
+ }
167
+ // 3b. Answer the startup dialogs. A child still on one when the wait runs
168
+ // out is undone, as a spawn's is, and the error names the dialog.
169
+ let answered;
170
+ if (startup) {
171
+ try {
172
+ answered = await startup.answer();
173
+ }
174
+ catch (error) {
175
+ startup.close();
176
+ await client.tabClose(tabId ?? child.paneId).catch(() => { });
177
+ restore();
178
+ throw error;
179
+ }
180
+ startup.close();
181
+ }
182
+ // 4. Record the session herdr reports, the transcript on this machine, and
183
+ // the live status, and lift the hold.
184
+ let reported = undefined;
185
+ let status;
186
+ try {
187
+ const result = await client.request('agent.get', { target: child.paneId }, { signal });
188
+ const agent = typeof result === 'object' && result !== null ? result['agent'] : undefined;
189
+ const pane = typeof agent === 'object' && agent !== null ? agent : {};
190
+ reported = sessionFrom(pane['agent_session']);
191
+ if (typeof pane['agent_status'] === 'string' && pane['agent_status'])
192
+ status = pane['agent_status'];
193
+ }
194
+ catch {
195
+ // The watcher reads the status and session on its next pass.
196
+ }
197
+ const kept = reported ?? { kind: session.kind, value: session.value };
198
+ updateChild(parent.id, child.id, (entry) => {
199
+ entry.session = kept;
200
+ if (child.host === LOCAL_HOST)
201
+ entry.transcript = resolveTranscript(child.harness, kept.value, child.cwd) ?? entry.transcript;
202
+ if (status && entry.lastStatus !== status) {
203
+ entry.statusChangedAt = new Date().toISOString();
204
+ entry.lastStatus = status;
205
+ }
206
+ delete entry.startingUntil;
207
+ });
208
+ const saved = readParent(parent.id)?.children.find((entry) => entry.id === child.id) ?? child;
209
+ return { child: saved, session, link: herdrLink('pane', child.paneId), answered };
210
+ }