@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.
- package/README.md +58 -7
- package/dist/cli.js +296 -0
- package/dist/core/adopt.js +59 -0
- package/dist/core/brief.js +61 -0
- package/dist/core/child-lock.js +84 -0
- package/dist/core/classifier.js +100 -0
- package/dist/core/herdr-client.js +382 -0
- package/dist/core/inactivity.js +31 -0
- package/dist/core/label.js +7 -0
- package/dist/core/machine.js +134 -0
- package/dist/core/mcp-config.js +47 -0
- package/dist/core/outbox.js +145 -0
- package/dist/core/paths.js +46 -0
- package/dist/core/registry.js +129 -0
- package/dist/core/report.js +95 -0
- package/dist/core/resume.js +210 -0
- package/dist/core/retire.js +416 -0
- package/dist/core/send.js +17 -0
- package/dist/core/spawn-resume.js +96 -0
- package/dist/core/spawn.js +226 -0
- package/dist/core/startup-dialogs.js +120 -0
- package/dist/core/transcript.js +87 -0
- package/dist/core/types.js +2 -0
- package/dist/core/watcher.js +821 -0
- package/dist/daemon/client.js +459 -0
- package/dist/daemon/lock.js +68 -0
- package/dist/daemon/main.js +40 -0
- package/dist/daemon/protocol.js +104 -0
- package/dist/daemon/server.js +244 -0
- package/dist/daemon/service.js +67 -0
- package/dist/integrations/claude/channel.js +257 -0
- package/dist/integrations/claude/transcript.js +135 -0
- package/dist/integrations/pi/extension.js +119 -0
- package/dist/integrations/tools.js +314 -0
- package/package.json +10 -9
- package/bin/bellwether-mcp.js +0 -4
- package/bin/bellwether.js +0 -2
- package/src/cli.ts +0 -293
- package/src/core/classifier.ts +0 -108
- package/src/core/herdr-client.ts +0 -410
- package/src/core/outbox.ts +0 -89
- package/src/core/paths.ts +0 -41
- package/src/core/registry.ts +0 -96
- package/src/core/report.ts +0 -54
- package/src/core/spawn.ts +0 -159
- package/src/core/transcript.ts +0 -74
- package/src/core/types.ts +0 -95
- package/src/core/watcher.ts +0 -590
- package/src/daemon/client.ts +0 -383
- package/src/daemon/lock.ts +0 -72
- package/src/daemon/main.ts +0 -38
- package/src/daemon/protocol.ts +0 -184
- package/src/daemon/server.ts +0 -275
- package/src/daemon/service.ts +0 -80
- package/src/integrations/claude/channel.ts +0 -247
- package/src/integrations/claude/transcript.ts +0 -124
- package/src/integrations/pi/extension.ts +0 -136
- package/src/integrations/tools.ts +0 -235
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ The MVP covers Pi and Claude Code, each as a parent and as a child.
|
|
|
8
8
|
|
|
9
9
|
A parent session runs an adapter: a Pi extension, or a Claude Code MCP channel server. Both are clients of one local daemon that runs the Bellwether core. The daemon starts on demand from the first session that needs it, and one daemon serves every session on the machine. When a session resumes, it receives the events it missed. With nothing left to watch, the daemon exits.
|
|
10
10
|
|
|
11
|
-
- **Daemon.** One per machine, on a socket under the Bellwether home. A lock file and a version handshake keep a second client from starting a second daemon. When a client is newer than the daemon it found, the client sends a drain request and the old daemon exits once no call is in flight. `bellwether daemon` runs it in the foreground when you want to watch it.
|
|
11
|
+
- **Daemon.** One per machine, on a socket under the Bellwether home. It is the only process that holds state: the registry, the outbox and the herdr subscriptions. An adapter keeps none of that. It starts without the identity variables of the session that launched it, so its own environment never decides who a call came from. A lock file and a version handshake keep a second client from starting a second daemon. When a client is newer than the daemon it found, the client sends a drain request and the old daemon exits once no call is in flight. `bellwether daemon` runs it in the foreground when you want to watch it.
|
|
12
12
|
- **herdr client.** Newline-delimited JSON on the herdr socket, one connection per request and one held open for the subscription. The subscription checks the `subscription_started` acknowledgement and buffers any event that arrives with it.
|
|
13
13
|
- **Registry.** One JSON file per parent session, under `~/.bellwether/parents/`, written by the daemon. Each child record stores its name, kind, pane, tab, start time, last status, last `completion_seq` and transcript path. Bellwether writes the record before it asks herdr for anything, so a crash mid-spawn still says what it asked herdr for.
|
|
14
14
|
- **Watcher.** It subscribes to `pane.agent_status_changed` for each child pane, plus `pane.exited`, `pane.closed` and `pane.agent_detected`. On connect it subscribes first, then reads a snapshot on a second connection, then reconciles. A dropped subscription reconnects with backoff and takes a fresh snapshot, because herdr does not replay events.
|
|
@@ -21,22 +21,68 @@ A parent session runs an adapter: a Pi extension, or a Claude Code MCP channel s
|
|
|
21
21
|
| -- | -- | -- |
|
|
22
22
|
| report | The child calls `parent_report`. | none |
|
|
23
23
|
| idle | herdr reports `idle` or `done` with a new `completion_seq`, and no report covered that turn. | 5 s |
|
|
24
|
-
| blocked | herdr reports `blocked
|
|
24
|
+
| blocked | herdr reports `blocked`, on a question other than Claude Code's startup questions. | 3 s |
|
|
25
25
|
| stuck | herdr reports `working` or `unknown` and the child has been quiet past the threshold. | 10 min |
|
|
26
|
+
| inactive | The child has shown no status change, output, new turn or report for its inactivity threshold. Any status counts, `blocked` included. | none |
|
|
26
27
|
| exited | `pane.exited`, `pane.closed`, or herdr stops detecting the agent. | none |
|
|
27
28
|
|
|
29
|
+
A Claude Code child asks two questions before its prompt: whether to trust the folder, and whether to load the development channel. `agent_spawn` answers both before it returns. It moves the selection to "Yes, I trust this folder" and to "I am using this for local development", checks each on screen, and then presses Enter. It says yes to the folder question for any folder, which gives the child write access to whatever directory the spawn names. When a question is still on screen after the spawn's 30 seconds, the spawn fails, and the error names that question. The parent hears about neither question. A resumed session shows the channel question again, and the watcher answers it the same way.
|
|
30
|
+
|
|
31
|
+
At delivery, the watcher drops an unread `blocked` or `stuck` event once the child has moved on. A dialog someone already answered stays out of the parent's next turn.
|
|
32
|
+
|
|
33
|
+
The registry keeps each child's harness session, `session.kind` and `session.value`, and its transcript path after the child exits. To resume a retired child, call `agent_spawn` with `resume`. By hand, a retired Claude Code child resumes with `claude --resume <value>`.
|
|
34
|
+
|
|
35
|
+
The inactivity threshold defaults to 5 minutes. `agent_spawn` takes `inactive_minutes` to set it for one child. A value is clamped to 1 minute through 24 hours, and no value turns the notice off. The notice fires once per quiet period. Output or a report starts a new one.
|
|
36
|
+
|
|
28
37
|
## Tools
|
|
29
38
|
|
|
30
39
|
| Tool | Who gets it | What it does |
|
|
31
40
|
| -- | -- | -- |
|
|
32
|
-
| `agent_spawn` | any session | starts a child in a new tab |
|
|
41
|
+
| `agent_spawn` | any session | starts a child in a new tab, on this machine or on a saved herdr machine named by `machine`, or with `resume` messages an earlier child, reopening its session in a new tab when herdr no longer has it |
|
|
42
|
+
| `agent_adopt` | any session | makes a running agent this session did not start into its child, such as one `herdr-spawn.sh` started, and refuses a pane another session watches |
|
|
33
43
|
| `agent_list` | any session | lists this session's children with status, age and unread events |
|
|
34
44
|
| `agent_read` | any session | returns a child's last assistant message, or its screen when you pass `lines` |
|
|
35
45
|
| `agent_send` | any session | prompts a child, or sends keys when herdr refuses a blocked one |
|
|
36
46
|
| `agent_stop` | any session | closes a child's tab, refusing a working child unless you pass `force` |
|
|
37
|
-
| `parent_report` | a child
|
|
47
|
+
| `parent_report` | a child Bellwether started or resumed on this machine | sends `done`, `needs-input` or `progress` to the parent that holds the child's record |
|
|
48
|
+
| `request_retirement` | a session whose environment carries `BELLWETHER_CHILD` | asks the daemon to remove the child's worktree and branch after herdr drops its pane, and doesn't remove anything itself |
|
|
49
|
+
|
|
50
|
+
Bellwether sends input only to panes that belong to this parent: the ones it started, resumed or adopted.
|
|
51
|
+
|
|
52
|
+
Each adapter sends its session's identity with every tool call: the herdr pane it runs in, and the child id its spawn gave it. The daemon matches that identity against the child records it keeps, so a `parent_report` reaches the parent whose registry lists the child, whichever client process made the call. Adapters read the parent from the daemon's records, never from an environment variable. When no record matches, the error gives the pane and the path of the MCP config file the spawn should have written.
|
|
53
|
+
|
|
54
|
+
### Retirement
|
|
55
|
+
|
|
56
|
+
A child that has finished its work calls `request_retirement`, then closes its own tab. The call runs while the child is alive, so the child hears which checks pass now. Those cover uncommitted changes, stashes on the branch, and whether its commits exist anywhere else. On the child record go `retireRequestedAt` and `retireIntent` (worktree, repository, branch, commit), and nothing on disk changes. Bellwether refuses, and leaves the record as it was, for a caller with no child record, an adopted child, a child on another machine, a detached HEAD, or a main worktree.
|
|
57
|
+
|
|
58
|
+
The daemon does the cleaning. It already holds the registry, watches every pane and keeps running after each child exits, so no other process takes part. When the watcher sees the child's pane exit, it runs these steps in order, and it doesn't remove anything until each one holds:
|
|
59
|
+
|
|
60
|
+
1. herdr lists neither the pane nor any pane in its tab. Otherwise the retirement waits for the next exit event.
|
|
61
|
+
2. The worktree must not be a main worktree. It must also match what the child asked about, with a clean status and no stash on its branch.
|
|
62
|
+
3. The default branch contains the branch, or GitHub shows a merged or closed pull request whose head is the branch's commit.
|
|
63
|
+
4. No process has its working directory inside the worktree.
|
|
64
|
+
5. `git worktree remove`, then `git branch -D`, then a check against git and the filesystem that neither remains.
|
|
38
65
|
|
|
39
|
-
|
|
66
|
+
The daemon writes the outcome to the child record as `retiredAt` and `retireOutcome` (`removed` or `refused`). A refusal also gets `retireReason`, which states the failed condition and what a person would do about it. One JSON line per outcome goes to `~/.bellwether/retire.log`. `retireStage` records each removal as it completes, so a daemon that starts again finishes an unfinished retirement without repeating a step. Bellwether treats a worktree as main when its git directory is the repository itself or git lists it first. The checkout of the default branch counts too, as does any worktree named `main` or `master`. Resuming a child clears its request.
|
|
67
|
+
|
|
68
|
+
### Resume through `agent_spawn`
|
|
69
|
+
|
|
70
|
+
`agent_spawn` accepts a `resume` target: a child's name, its id or its session id. It also takes the same `prompt` as any spawn. herdr, not the registry, decides what happens next.
|
|
71
|
+
|
|
72
|
+
- When herdr shows the child's session in the pane this parent started for it, the prompt goes to that pane as an ordinary message. No tab opens, and the child keeps its id.
|
|
73
|
+
- When herdr has no pane for the session, Bellwether treats the child as retired. It opens a tab on the child's original machine and starts the harness with `--resume` for Claude Code or `--session` for Pi. The child keeps its id, so its events and receipts continue, and Bellwether passes the prompt in a file with mode 0600.
|
|
74
|
+
- When the registry and herdr disagree, herdr wins, and the reply opens with a line that says so. Bellwether resumes a record still marked running whose session herdr no longer has. For a record marked exited whose session herdr still shows in its own pane, Bellwether sends the message and clears the exit mark.
|
|
75
|
+
- When the session runs in a pane this parent did not start, Bellwether refuses. The refusal gives the child, the pane and `agent_adopt`. Bellwether never types into that pane.
|
|
76
|
+
|
|
77
|
+
When the call passes `kind` with a session id that this parent's children did not run, Bellwether starts a new child, with `name`, `cwd` and `machine` as for a spawn.
|
|
78
|
+
|
|
79
|
+
Bellwether also refuses a live agent that isn't a child, a harness without a resume flag, or a retired child whose session was never recorded, along with a target that doesn't match any child or session. Each refusal tells the caller what to pass instead.
|
|
80
|
+
|
|
81
|
+
A lock file under `~/.bellwether/locks/`, one per child, covers the decision and the resume. A second call for the same child fails at once with the process that holds the lock, so two callers open one tab between them. Bellwether takes over a lock whose process has exited or that is older than five minutes.
|
|
82
|
+
|
|
83
|
+
A child on another machine runs on that machine's herdr. Bellwether reaches it the way `herdr --machine` does, through `herdr remote-api-bridge` over SSH to the saved profile's target, so the profile must exist in `herdr machine list` and SSH must log in without a prompt. That child's `parent_report` writes to its own machine's disk, which the parent never reads, so Bellwether follows it through herdr status alone.
|
|
84
|
+
|
|
85
|
+
Each child record keeps its `host` after the child exits, so a resume goes back to the same machine. A registry file written before version 2 gains `host: local` for each child the next time Bellwether writes it.
|
|
40
86
|
|
|
41
87
|
## Install
|
|
42
88
|
|
|
@@ -65,6 +111,10 @@ claude --dangerously-load-development-channels plugin:bellwether@bellwether
|
|
|
65
111
|
|
|
66
112
|
The plugin runs `bin/bellwether-mcp.js` as an MCP server and enables it as a channel, and that declaration is what delivers child events. Load the server as a plain MCP server and the tools arrive, with events waiting in the outbox.
|
|
67
113
|
|
|
114
|
+
The plugin is for a parent session, one you start yourself. You don't set anything up for a child: `agent_spawn`, with or without `resume`, starts each Claude Code child with its own server, passed as `--mcp-config=~/.bellwether/mcp/<child id>.json`. The file has mode 0600 and lists one server, which runs this package's channel entry point with `--child <child id>`. Bellwether deletes it when the child exits or the spawn fails. A child on another machine doesn't get a file, because the daemon on that machine doesn't store a record of it.
|
|
115
|
+
|
|
116
|
+
You don't need a `mcpServers` entry in your Claude Code settings for children. A user-level `bellwether` entry is harmless, and children don't use it. For the tools in a session you start by hand, install the plugin above.
|
|
117
|
+
|
|
68
118
|
The server speaks MCP over stdio, so each log line goes to stderr and stdout carries only the protocol. It exits when stdin closes, which keeps a leftover process from showing the session as listening.
|
|
69
119
|
|
|
70
120
|
### Check the install
|
|
@@ -77,7 +127,7 @@ It reports the herdr socket, the herdr API version, the Pi extension path, the M
|
|
|
77
127
|
|
|
78
128
|
## Environment
|
|
79
129
|
|
|
80
|
-
A child started by `agent_spawn` receives these variables in its tab
|
|
130
|
+
A child started by `agent_spawn` receives these variables in its tab, for its own scripts and for the `bellwether report` command. The MCP server identifies its child with `--child` instead, and the daemon looks up the parent in its records.
|
|
81
131
|
|
|
82
132
|
| Variable | Meaning |
|
|
83
133
|
| -- | -- |
|
|
@@ -95,7 +145,8 @@ src/daemon/ the daemon: protocol, server, client, lock, parent service
|
|
|
95
145
|
src/integrations/ the tool list, shared by both adapters
|
|
96
146
|
src/integrations/pi/ the Pi extension
|
|
97
147
|
src/integrations/claude/ the Claude Code MCP channel server
|
|
98
|
-
bin/ the bellwether command
|
|
148
|
+
bin/ the bellwether command and MCP server, run from the sources in a checkout
|
|
149
|
+
dist/ the compiled JavaScript that npm publishes, built by `npm run build`
|
|
99
150
|
docs/ probe results and notes
|
|
100
151
|
test/unit/ tier 1: fake clock, in-memory registry
|
|
101
152
|
test/integration/ tier 2: a fake herdr socket and the daemon, tier 3: a real isolated herdr server
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The bellwether command.
|
|
3
|
+
//
|
|
4
|
+
// `watch` is the dogfood driver: it runs the same core the Pi extension and the
|
|
5
|
+
// Claude channel run, and prints one line per child event, so a supervisor can
|
|
6
|
+
// read the stream instead of polling herdr.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { HerdrClient, resolveSocketPath } from './core/herdr-client.js';
|
|
10
|
+
import { bellwetherHome } from './core/paths.js';
|
|
11
|
+
import { emptyParent, listParents, readParent, saveParent } from './core/registry.js';
|
|
12
|
+
import { reportToParent, writeReport } from './core/report.js';
|
|
13
|
+
import { DaemonClient } from './daemon/client.js';
|
|
14
|
+
import { daemonIsLive, startDaemon } from './daemon/server.js';
|
|
15
|
+
function parseArgs(argv) {
|
|
16
|
+
const positional = [];
|
|
17
|
+
const flags = {};
|
|
18
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
19
|
+
const token = argv[index];
|
|
20
|
+
if (!token.startsWith('--')) {
|
|
21
|
+
positional.push(token);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const key = token.slice(2);
|
|
25
|
+
const next = argv[index + 1];
|
|
26
|
+
if (next === undefined || next.startsWith('--')) {
|
|
27
|
+
flags[key] = true;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (key === 'keys' || key === 'args') {
|
|
31
|
+
flags[key] = next;
|
|
32
|
+
}
|
|
33
|
+
else if (key === 'stuck-minutes' || key === 'inactive-minutes' || key === 'max-depth' || key === 'lines') {
|
|
34
|
+
flags[key] = Number(next);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
flags[key] = next;
|
|
38
|
+
}
|
|
39
|
+
index += 1;
|
|
40
|
+
}
|
|
41
|
+
return { positional, flags };
|
|
42
|
+
}
|
|
43
|
+
function str(flags, key) {
|
|
44
|
+
const value = flags[key];
|
|
45
|
+
return typeof value === 'string' && value.length ? value : undefined;
|
|
46
|
+
}
|
|
47
|
+
function num(flags, key) {
|
|
48
|
+
const value = flags[key];
|
|
49
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
50
|
+
}
|
|
51
|
+
/** The registry this CLI run works against: an explicit id, the environment, or the newest. */
|
|
52
|
+
function parentFor(flags) {
|
|
53
|
+
const explicit = str(flags, 'parent') ?? process.env['BELLWETHER_PARENT'];
|
|
54
|
+
if (explicit)
|
|
55
|
+
return { id: explicit, created: false };
|
|
56
|
+
const name = `cli-${path.basename(process.cwd())}`;
|
|
57
|
+
const existing = readParent(name);
|
|
58
|
+
if (existing)
|
|
59
|
+
return { id: existing.id, created: false };
|
|
60
|
+
saveParent({
|
|
61
|
+
...emptyParent('pi', name, process.cwd(), { host: process.env['HOSTNAME'] ?? '', paneId: process.env['HERDR_PANE_ID'], workspaceId: process.env['HERDR_WORKSPACE_ID'] }),
|
|
62
|
+
id: name,
|
|
63
|
+
});
|
|
64
|
+
return { id: name, created: true };
|
|
65
|
+
}
|
|
66
|
+
function clientFrom(flags) {
|
|
67
|
+
return new HerdrClient({ socketPath: str(flags, 'socket'), session: str(flags, 'session') });
|
|
68
|
+
}
|
|
69
|
+
function ok(label, detail) {
|
|
70
|
+
console.log(` ok ${label}: ${detail}`);
|
|
71
|
+
}
|
|
72
|
+
function bad(label, detail) {
|
|
73
|
+
console.log(` fail ${label}: ${detail}`);
|
|
74
|
+
}
|
|
75
|
+
/** The package root, found by walking up from this file to its package.json. */
|
|
76
|
+
function packageRoot() {
|
|
77
|
+
let dir = import.meta.dirname;
|
|
78
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
79
|
+
if (fs.existsSync(path.join(dir, 'package.json')))
|
|
80
|
+
return dir;
|
|
81
|
+
const parent = path.dirname(dir);
|
|
82
|
+
if (parent === dir)
|
|
83
|
+
return undefined;
|
|
84
|
+
dir = parent;
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
/** Harnesses load these two paths by name, so a missing one fails at load time.
|
|
89
|
+
* doctor names it here, before a user meets it inside a session. */
|
|
90
|
+
function checkPackaging() {
|
|
91
|
+
const root = packageRoot();
|
|
92
|
+
if (!root) {
|
|
93
|
+
bad('package root', 'no package.json above the CLI');
|
|
94
|
+
return 1;
|
|
95
|
+
}
|
|
96
|
+
let failures = 0;
|
|
97
|
+
let manifest;
|
|
98
|
+
try {
|
|
99
|
+
manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
bad('package.json', String(error));
|
|
103
|
+
return 1;
|
|
104
|
+
}
|
|
105
|
+
const extensions = manifest.pi?.extensions ?? [];
|
|
106
|
+
if (!extensions.length) {
|
|
107
|
+
bad('pi extension', 'package.json declares none');
|
|
108
|
+
failures += 1;
|
|
109
|
+
}
|
|
110
|
+
for (const entry of extensions) {
|
|
111
|
+
const file = path.resolve(root, entry);
|
|
112
|
+
if (fs.existsSync(file)) {
|
|
113
|
+
ok('pi extension', path.relative(root, file));
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
bad('pi extension', `${entry} does not exist`);
|
|
117
|
+
failures += 1;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const declared = manifest.bin?.['bellwether-mcp'];
|
|
121
|
+
if (!declared) {
|
|
122
|
+
bad('mcp entry', 'package.json declares no bellwether-mcp bin');
|
|
123
|
+
return failures + 1;
|
|
124
|
+
}
|
|
125
|
+
const mcpEntry = path.resolve(root, declared);
|
|
126
|
+
const label = path.relative(root, mcpEntry);
|
|
127
|
+
if (!fs.existsSync(mcpEntry)) {
|
|
128
|
+
bad('mcp entry', `${label} does not exist`);
|
|
129
|
+
failures += 1;
|
|
130
|
+
}
|
|
131
|
+
else if (!(fs.statSync(mcpEntry).mode & 0o111)) {
|
|
132
|
+
bad('mcp entry', `${label} is not executable`);
|
|
133
|
+
failures += 1;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
ok('mcp entry', label);
|
|
137
|
+
}
|
|
138
|
+
return failures;
|
|
139
|
+
}
|
|
140
|
+
async function doctor() {
|
|
141
|
+
let failures = 0;
|
|
142
|
+
console.log(`bellwether home ${bellwetherHome()}`);
|
|
143
|
+
const daemonSocket = path.join(bellwetherHome(), 'daemon.sock');
|
|
144
|
+
const daemonLive = daemonIsLive(bellwetherHome());
|
|
145
|
+
console.log(` ${daemonLive ? 'ok ' : 'info '} daemon: ${daemonLive ? 'running' : 'idle, starts on demand'} (${daemonSocket})`);
|
|
146
|
+
failures += checkPackaging();
|
|
147
|
+
const socket = resolveSocketPath();
|
|
148
|
+
if (!fs.existsSync(socket)) {
|
|
149
|
+
console.log(` fail herdr socket: ${socket} does not exist`);
|
|
150
|
+
return 1;
|
|
151
|
+
}
|
|
152
|
+
console.log(` ok herdr socket: ${socket}`);
|
|
153
|
+
try {
|
|
154
|
+
const panes = await new HerdrClient({ socketPath: socket }).paneList();
|
|
155
|
+
console.log(` ok herdr api: ${panes.length} panes`);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
console.log(` fail herdr api: ${String(error)}`);
|
|
159
|
+
failures += 1;
|
|
160
|
+
}
|
|
161
|
+
for (const parent of listParents()) {
|
|
162
|
+
const live = parent.children.filter((child) => !child.exitedAt);
|
|
163
|
+
console.log(` ${parent.id}: ${live.length} live of ${parent.children.length} children, updated ${parent.updatedAt}`);
|
|
164
|
+
}
|
|
165
|
+
return failures;
|
|
166
|
+
}
|
|
167
|
+
async function main() {
|
|
168
|
+
const [command = 'help', ...rest] = process.argv.slice(2);
|
|
169
|
+
const { positional, flags } = parseArgs(rest);
|
|
170
|
+
if (command === 'help' || command === '--help') {
|
|
171
|
+
console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
|
|
172
|
+
console.log(' daemon [--socket PATH] run the local daemon in the foreground');
|
|
173
|
+
console.log(' spawn --kind KIND --name NAME [--cwd DIR] [--prompt TEXT] [--model M] [--parent ID] [--focus]');
|
|
174
|
+
console.log(' watch [--parent ID] [--tick-ms N] one line per child event, then keeps reading');
|
|
175
|
+
console.log(' list [--parent ID]');
|
|
176
|
+
console.log(' read CHILD [--lines N]');
|
|
177
|
+
console.log(' send CHILD [--text TEXT | --keys KEY,...]');
|
|
178
|
+
console.log(' stop CHILD [--force]');
|
|
179
|
+
console.log(' report --status done|needs-input|progress --text TEXT');
|
|
180
|
+
return 0;
|
|
181
|
+
}
|
|
182
|
+
if (command === 'doctor')
|
|
183
|
+
return doctor();
|
|
184
|
+
if (command === 'daemon') {
|
|
185
|
+
const socketPath = str(flags, 'socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(bellwetherHome(), 'daemon.sock');
|
|
186
|
+
const daemon = await startDaemon({ socketPath, home: bellwetherHome(), log: (message) => console.error('[bellwether-daemon]', message) });
|
|
187
|
+
console.error(`[bellwether-daemon] listening on ${socketPath} with pid ${daemon.pid}`);
|
|
188
|
+
const stop = () => void daemon.close().then(() => process.exit(0));
|
|
189
|
+
process.on('SIGTERM', stop);
|
|
190
|
+
process.on('SIGINT', stop);
|
|
191
|
+
await daemon.whenClosed();
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
if (command === 'parents') {
|
|
195
|
+
for (const parent of listParents())
|
|
196
|
+
console.log(`${parent.id}\t${parent.children.length} children\t${parent.updatedAt}\t${parent.cwd}`);
|
|
197
|
+
return 0;
|
|
198
|
+
}
|
|
199
|
+
if (command === 'report') {
|
|
200
|
+
const status = (str(flags, 'status') ?? 'progress');
|
|
201
|
+
const text = str(flags, 'text') ?? '';
|
|
202
|
+
if (!text)
|
|
203
|
+
throw new Error('report needs --text');
|
|
204
|
+
if (!reportToParent(status, text)) {
|
|
205
|
+
const parentId = str(flags, 'parent');
|
|
206
|
+
if (!parentId)
|
|
207
|
+
throw new Error('report needs BELLWETHER_PARENT or --parent');
|
|
208
|
+
writeReport({ parentId, childName: process.env['BELLWETHER_CHILD_NAME'] ?? 'child', status, text });
|
|
209
|
+
}
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
|
212
|
+
const { id: parentId } = parentFor(flags);
|
|
213
|
+
const parent = readParent(parentId);
|
|
214
|
+
if (!parent)
|
|
215
|
+
throw new Error(`No parent registry ${parentId}. Run bellwether list once to create it.`);
|
|
216
|
+
const daemon = await DaemonClient.connect({
|
|
217
|
+
harness: parent.harness,
|
|
218
|
+
session: parent.session,
|
|
219
|
+
cwd: parent.cwd,
|
|
220
|
+
host: parent.host,
|
|
221
|
+
paneId: parent.paneId,
|
|
222
|
+
workspaceId: parent.workspaceId,
|
|
223
|
+
depth: parent.depth,
|
|
224
|
+
herdrSocket: resolveSocketPath({ socketPath: str(flags, 'socket'), session: str(flags, 'session') }),
|
|
225
|
+
}, { log: (message) => console.error('[bellwether]', message) });
|
|
226
|
+
if (command === 'watch') {
|
|
227
|
+
const printed = new Set();
|
|
228
|
+
const emit = (entry) => {
|
|
229
|
+
if (printed.has(entry.receipt) || entry.read)
|
|
230
|
+
return;
|
|
231
|
+
printed.add(entry.receipt);
|
|
232
|
+
console.log(`CHILD ${entry.event} ${entry.name} ${entry.paneId} unread=${entry.receipt} at=${entry.at}`);
|
|
233
|
+
console.log(` ${entry.text.split('\n').join('\n ')}`);
|
|
234
|
+
};
|
|
235
|
+
daemon.onEvents((entries) => entries.forEach(emit));
|
|
236
|
+
(await daemon.pending()).forEach(emit);
|
|
237
|
+
console.log(`READY watch parent=${parentId} home=${bellwetherHome()}`);
|
|
238
|
+
const keepAlive = setInterval(() => { }, 60_000);
|
|
239
|
+
process.on('SIGINT', () => {
|
|
240
|
+
clearInterval(keepAlive);
|
|
241
|
+
void daemon.close().then(() => process.exit(0));
|
|
242
|
+
});
|
|
243
|
+
await new Promise(() => { });
|
|
244
|
+
return 0;
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
if (command === 'spawn') {
|
|
248
|
+
const name = str(flags, 'name');
|
|
249
|
+
if (!name)
|
|
250
|
+
throw new Error('spawn needs --name');
|
|
251
|
+
console.log(await daemon.tool('agent_spawn', {
|
|
252
|
+
kind: str(flags, 'kind') ?? 'pi',
|
|
253
|
+
name,
|
|
254
|
+
cwd: str(flags, 'cwd'),
|
|
255
|
+
prompt: str(flags, 'prompt'),
|
|
256
|
+
model: str(flags, 'model'),
|
|
257
|
+
focus: flags['focus'] === true,
|
|
258
|
+
stuckMinutes: num(flags, 'stuck-minutes'),
|
|
259
|
+
inactive_minutes: num(flags, 'inactive-minutes'),
|
|
260
|
+
maxDepth: num(flags, 'max-depth'),
|
|
261
|
+
args: str(flags, 'args')?.split('\u0000'),
|
|
262
|
+
}));
|
|
263
|
+
}
|
|
264
|
+
else if (command === 'list') {
|
|
265
|
+
console.log(await daemon.tool('agent_list', {}));
|
|
266
|
+
}
|
|
267
|
+
else if (command === 'read') {
|
|
268
|
+
const child = positional[0];
|
|
269
|
+
if (!child)
|
|
270
|
+
throw new Error('read needs a child');
|
|
271
|
+
console.log(await daemon.tool('agent_read', { child, lines: num(flags, 'lines') }));
|
|
272
|
+
}
|
|
273
|
+
else if (command === 'send') {
|
|
274
|
+
const child = positional[0];
|
|
275
|
+
if (!child)
|
|
276
|
+
throw new Error('send needs a child');
|
|
277
|
+
const keys = str(flags, 'keys')?.split(',').map((key) => key.trim()).filter(Boolean);
|
|
278
|
+
console.log(await daemon.tool('agent_send', { child, text: str(flags, 'text'), keys }));
|
|
279
|
+
}
|
|
280
|
+
else if (command === 'stop') {
|
|
281
|
+
const child = positional[0];
|
|
282
|
+
if (!child)
|
|
283
|
+
throw new Error('stop needs a child');
|
|
284
|
+
console.log(await daemon.tool('agent_stop', { child, force: flags['force'] === true }));
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
await daemon.close();
|
|
293
|
+
}
|
|
294
|
+
return 0;
|
|
295
|
+
}
|
|
296
|
+
process.exitCode = await main();
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { LOCAL_HOST } from './machine.js';
|
|
2
|
+
import { newChildId } from './outbox.js';
|
|
3
|
+
import { upsertChild, watcherOfPane } from './registry.js';
|
|
4
|
+
import { AGENT_KINDS, harnessOf, herdrLink } from './spawn.js';
|
|
5
|
+
import { resolveTranscript } from './transcript.js';
|
|
6
|
+
import { resolveInactiveMs } from './inactivity.js';
|
|
7
|
+
export async function adoptPane(client, parent, options, signal) {
|
|
8
|
+
const host = options.host ?? LOCAL_HOST;
|
|
9
|
+
const agents = await client.agentList(signal);
|
|
10
|
+
const byPane = agents.find((pane) => pane.paneId === options.target);
|
|
11
|
+
const byName = agents.filter((pane) => pane.name === options.target);
|
|
12
|
+
if (!byPane && byName.length > 1)
|
|
13
|
+
throw new Error(`More than one live agent on ${host} is named ${options.target}. Adopt it by pane id: ${byName.map((pane) => pane.paneId).join(', ')}.`);
|
|
14
|
+
const pane = byPane ?? byName[0];
|
|
15
|
+
if (!pane || !pane.agent) {
|
|
16
|
+
const panes = await client.paneList(signal).catch(() => []);
|
|
17
|
+
const bare = panes.find((entry) => entry.paneId === options.target);
|
|
18
|
+
if (bare)
|
|
19
|
+
throw new Error(`Pane ${options.target} on ${host} holds no agent herdr recognizes, so there is nothing to adopt.`);
|
|
20
|
+
throw new Error(`No pane or live agent on ${host} matches ${options.target}.`);
|
|
21
|
+
}
|
|
22
|
+
if (!AGENT_KINDS.includes(pane.agent))
|
|
23
|
+
throw new Error(`Pane ${pane.paneId} on ${host} runs ${pane.agent}, which is not an agent kind Bellwether supervises.`);
|
|
24
|
+
if (host === LOCAL_HOST && pane.paneId === parent.paneId)
|
|
25
|
+
throw new Error('A session cannot adopt its own pane.');
|
|
26
|
+
const owner = watcherOfPane(host, pane.paneId);
|
|
27
|
+
if (owner && owner.parent.id === parent.id)
|
|
28
|
+
return { child: owner.child, link: herdrLink('pane', pane.paneId), already: true };
|
|
29
|
+
if (owner)
|
|
30
|
+
throw new Error(`Pane ${pane.paneId} on ${host} is already a child of ${owner.parent.id} as ${owner.child.name}, so this session cannot adopt it.`);
|
|
31
|
+
const now = new Date().toISOString();
|
|
32
|
+
const kind = pane.agent;
|
|
33
|
+
const harness = harnessOf(kind);
|
|
34
|
+
const child = {
|
|
35
|
+
id: newChildId(),
|
|
36
|
+
name: options.name ?? pane.name ?? pane.label ?? pane.paneId,
|
|
37
|
+
kind,
|
|
38
|
+
harness,
|
|
39
|
+
paneId: pane.paneId,
|
|
40
|
+
tabId: pane.tabId,
|
|
41
|
+
workspaceId: pane.workspaceId,
|
|
42
|
+
host,
|
|
43
|
+
origin: 'adopt',
|
|
44
|
+
cwd: pane.cwd,
|
|
45
|
+
startedAt: now,
|
|
46
|
+
lastStatus: pane.agentStatus,
|
|
47
|
+
statusChangedAt: now,
|
|
48
|
+
completionSeq: pane.completionSeq,
|
|
49
|
+
session: pane.agentSessionId ? { kind: pane.agentSessionId.includes('/') ? 'path' : 'id', value: pane.agentSessionId } : undefined,
|
|
50
|
+
// A remote child's transcript sits on its own machine's disk.
|
|
51
|
+
transcript: host === LOCAL_HOST ? resolveTranscript(harness, pane.agentSessionId, pane.cwd) : undefined,
|
|
52
|
+
lastBusyAt: now,
|
|
53
|
+
depth: parent.depth + 1,
|
|
54
|
+
stuckMs: options.stuckMinutes === undefined ? undefined : Math.max(1_000, Math.round(options.stuckMinutes * 60_000)),
|
|
55
|
+
inactiveMs: resolveInactiveMs(undefined),
|
|
56
|
+
};
|
|
57
|
+
upsertChild(parent.id, child);
|
|
58
|
+
return { child, link: herdrLink('pane', child.paneId), already: false };
|
|
59
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// A child's brief lives in a private file, and the harness gets a one-line
|
|
2
|
+
// pointer to it. herdr types an agent's arguments into a shell and refuses a
|
|
3
|
+
// line break, and a prompt on a command line shows in `ps` and matches
|
|
4
|
+
// `pkill -f`. A file keeps the line breaks, any length, and the text private.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { promptPath, promptsDir } from './paths.js';
|
|
8
|
+
/** A brief is read when the child starts. One a week old has been read. */
|
|
9
|
+
const BRIEF_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
|
|
10
|
+
/** Write the brief with mode 0600 in a 0700 directory, and return its path. */
|
|
11
|
+
export function writeBrief(childId, text, now = Date.now()) {
|
|
12
|
+
const dir = promptsDir();
|
|
13
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
14
|
+
fs.chmodSync(dir, 0o700);
|
|
15
|
+
pruneBriefs(now);
|
|
16
|
+
const file = promptPath(childId);
|
|
17
|
+
fs.writeFileSync(file, text, { mode: 0o600 });
|
|
18
|
+
fs.chmodSync(file, 0o600);
|
|
19
|
+
return file;
|
|
20
|
+
}
|
|
21
|
+
/** Remove a child's brief. A brief that is already gone is not an error. */
|
|
22
|
+
export function removeBrief(childId) {
|
|
23
|
+
fs.rmSync(promptPath(childId), { force: true });
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Remove the briefs older than a week. A child that exits removes its own, so
|
|
27
|
+
* this only catches a daemon that stopped before its child did.
|
|
28
|
+
*/
|
|
29
|
+
export function pruneBriefs(now = Date.now()) {
|
|
30
|
+
let names;
|
|
31
|
+
try {
|
|
32
|
+
names = fs.readdirSync(promptsDir());
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
for (const name of names) {
|
|
38
|
+
const file = path.join(promptsDir(), name);
|
|
39
|
+
try {
|
|
40
|
+
if (now - fs.statSync(file).mtimeMs > BRIEF_MAX_AGE_MS)
|
|
41
|
+
fs.rmSync(file, { force: true });
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// Another process removed it first.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The one argument that hands the brief to the harness. Claude Code and Pi
|
|
50
|
+
* attach a file named with @ to the first message, so the child spends no tool
|
|
51
|
+
* call reading it. Any other harness gets a sentence that names the file.
|
|
52
|
+
*/
|
|
53
|
+
export function briefArgument(kind, file) {
|
|
54
|
+
// Claude Code reads a mention out of the prompt text, so a path with a space
|
|
55
|
+
// needs quotes there. Pi takes the argument whole and strips only the @.
|
|
56
|
+
if (kind === 'claude')
|
|
57
|
+
return /\s/.test(file) ? `@"${file}"` : `@${file}`;
|
|
58
|
+
if (kind === 'pi')
|
|
59
|
+
return `@${file}`;
|
|
60
|
+
return `Your task is in ${file}. Read it, then do what it says.`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// One writer per child. A spawn that resumes a child holds a lock file on the
|
|
2
|
+
// child's id while it decides whether the child is alive and while it brings it
|
|
3
|
+
// back, so two callers resuming the same session open one tab between them.
|
|
4
|
+
// The lock is a file, not a map in memory, because two daemons on one machine
|
|
5
|
+
// can share a Bellwether home. A lock whose process is gone, or that is older
|
|
6
|
+
// than any resume can take, is stale and is taken over.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { isAlive } from '../daemon/lock.js';
|
|
10
|
+
import { bellwetherHome, slug } from './paths.js';
|
|
11
|
+
/** Longer than a resume can last: the start retries for 60 s and the dialogs wait 30 s. */
|
|
12
|
+
export const CHILD_LOCK_MAX_AGE_MS = 5 * 60_000;
|
|
13
|
+
export function childLockPath(key) {
|
|
14
|
+
return path.join(bellwetherHome(), 'locks', `${slug(key)}.lock`);
|
|
15
|
+
}
|
|
16
|
+
/** Thrown to the caller that finds the lock taken. */
|
|
17
|
+
export class ChildBusyError extends Error {
|
|
18
|
+
key;
|
|
19
|
+
holder;
|
|
20
|
+
constructor(key, holder, label) {
|
|
21
|
+
super(`${label} is already being brought back by another call (process ${holder.pid}, ${holder.purpose}, started ${new Date(holder.at).toISOString()}). Wait for its event, or call agent_list to see where it landed.`);
|
|
22
|
+
this.name = 'ChildBusyError';
|
|
23
|
+
this.key = key;
|
|
24
|
+
this.holder = holder;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function readLock(file) {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
30
|
+
if (typeof parsed.pid !== 'number' || typeof parsed.at !== 'number')
|
|
31
|
+
return undefined;
|
|
32
|
+
return { pid: parsed.pid, at: parsed.at, purpose: typeof parsed.purpose === 'string' ? parsed.purpose : 'unknown' };
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Run `work` while holding the lock on `key`. A second caller, in this process
|
|
40
|
+
* or another, gets a ChildBusyError naming `label` instead of waiting.
|
|
41
|
+
*/
|
|
42
|
+
export async function withChildLock(key, label, purpose, work, now = Date.now, alive = isAlive) {
|
|
43
|
+
const file = childLockPath(key);
|
|
44
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
45
|
+
const mine = { pid: process.pid, at: now(), purpose };
|
|
46
|
+
const token = JSON.stringify(mine);
|
|
47
|
+
let taken = false;
|
|
48
|
+
for (let attempt = 0; attempt < 2 && !taken; attempt += 1) {
|
|
49
|
+
try {
|
|
50
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
51
|
+
fs.writeSync(fd, `${token}\n`);
|
|
52
|
+
fs.closeSync(fd);
|
|
53
|
+
taken = true;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error.code !== 'EEXIST')
|
|
57
|
+
throw error;
|
|
58
|
+
const held = readLock(file);
|
|
59
|
+
// A half-written file is a holder that is mid-write, so it counts as held.
|
|
60
|
+
if (!held)
|
|
61
|
+
throw new ChildBusyError(key, { pid: 0, at: now(), purpose: 'unknown' }, label);
|
|
62
|
+
if (alive(held.pid) && now() - held.at < CHILD_LOCK_MAX_AGE_MS)
|
|
63
|
+
throw new ChildBusyError(key, held, label);
|
|
64
|
+
fs.rmSync(file, { force: true });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!taken) {
|
|
68
|
+
const held = readLock(file);
|
|
69
|
+
throw new ChildBusyError(key, held ?? { pid: 0, at: now(), purpose: 'unknown' }, label);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return await work();
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
// Remove the file only while it is still this call's, never a successor's.
|
|
76
|
+
try {
|
|
77
|
+
if (fs.readFileSync(file, 'utf8').trim() === token)
|
|
78
|
+
fs.rmSync(file, { force: true });
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Already gone.
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|