@elecnix/bellwether 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +105 -2
- package/bin/bellwether-mcp.js +4 -0
- package/bin/bellwether.js +2 -0
- package/package.json +46 -4
- package/src/cli.ts +293 -0
- package/src/core/classifier.ts +108 -0
- package/src/core/herdr-client.ts +410 -0
- package/src/core/outbox.ts +89 -0
- package/src/core/paths.ts +41 -0
- package/src/core/registry.ts +96 -0
- package/src/core/report.ts +54 -0
- package/src/core/spawn.ts +159 -0
- package/src/core/transcript.ts +74 -0
- package/src/core/types.ts +95 -0
- package/src/core/watcher.ts +590 -0
- package/src/daemon/client.ts +383 -0
- package/src/daemon/lock.ts +72 -0
- package/src/daemon/main.ts +38 -0
- package/src/daemon/protocol.ts +184 -0
- package/src/daemon/server.ts +275 -0
- package/src/daemon/service.ts +80 -0
- package/src/integrations/claude/channel.ts +247 -0
- package/src/integrations/claude/transcript.ts +124 -0
- package/src/integrations/pi/extension.ts +136 -0
- package/src/integrations/tools.ts +235 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nicolas Marchildon
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Bellwether
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Bellwether gives a coding agent in herdr tools to start another agent in a new herdr tab, of any kind herdr can start. When a child reports, goes idle, blocks, stalls or exits, the parent agent gets a fresh turn that says so. One herdr subscription streams each child state change to the parent.
|
|
4
|
+
|
|
5
|
+
The MVP covers Pi and Claude Code, each as a parent and as a child.
|
|
6
|
+
|
|
7
|
+
## Parts
|
|
8
|
+
|
|
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
|
+
|
|
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.
|
|
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
|
+
- **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
|
+
- **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.
|
|
15
|
+
- **Classifier.** It turns herdr states into child events, with a settle time for each. It is a pure function of state, clock and observation.
|
|
16
|
+
- **Outbox.** One pending entry per child, where a newer state replaces an older one. The receipt id in the entry marks it read once the parent's model context shows that id.
|
|
17
|
+
|
|
18
|
+
## Child events
|
|
19
|
+
|
|
20
|
+
| Event | Signal | Settle |
|
|
21
|
+
| -- | -- | -- |
|
|
22
|
+
| report | The child calls `parent_report`. | none |
|
|
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`. | 3 s |
|
|
25
|
+
| stuck | herdr reports `working` or `unknown` and the child has been quiet past the threshold. | 10 min |
|
|
26
|
+
| exited | `pane.exited`, `pane.closed`, or herdr stops detecting the agent. | none |
|
|
27
|
+
|
|
28
|
+
## Tools
|
|
29
|
+
|
|
30
|
+
| Tool | Who gets it | What it does |
|
|
31
|
+
| -- | -- | -- |
|
|
32
|
+
| `agent_spawn` | any session | starts a child in a new tab |
|
|
33
|
+
| `agent_list` | any session | lists this session's children with status, age and unread events |
|
|
34
|
+
| `agent_read` | any session | returns a child's last assistant message, or its screen when you pass `lines` |
|
|
35
|
+
| `agent_send` | any session | prompts a child, or sends keys when herdr refuses a blocked one |
|
|
36
|
+
| `agent_stop` | any session | closes a child's tab, refusing a working child unless you pass `force` |
|
|
37
|
+
| `parent_report` | a child whose environment carries `BELLWETHER_PARENT` | sends `done`, `needs-input` or `progress` to the parent |
|
|
38
|
+
|
|
39
|
+
Bellwether sends input only to panes it started for this parent.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
### Pi
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
pi install npm:@elecnix/bellwether
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The package declares its extension under `pi.extensions`, so Pi loads it at the next session start.
|
|
50
|
+
|
|
51
|
+
### Claude Code
|
|
52
|
+
|
|
53
|
+
Add the marketplace, then install the plugin:
|
|
54
|
+
|
|
55
|
+
```text
|
|
56
|
+
/plugin marketplace add elecnix/bellwether
|
|
57
|
+
/plugin install bellwether@bellwether
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Channels are a research preview. A plugin outside the organization allowlist needs the development flag when the session starts:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
claude --dangerously-load-development-channels plugin:bellwether@bellwether
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
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
|
+
|
|
68
|
+
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
|
+
|
|
70
|
+
### Check the install
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
bellwether doctor
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
It reports the herdr socket, the herdr API version, the Pi extension path, the MCP entry point and every registered parent with its children. A Pi extension path that does not resolve, or an MCP entry without its executable bit, fails the check.
|
|
77
|
+
|
|
78
|
+
## Environment
|
|
79
|
+
|
|
80
|
+
A child started by `agent_spawn` receives these variables in its tab:
|
|
81
|
+
|
|
82
|
+
| Variable | Meaning |
|
|
83
|
+
| -- | -- |
|
|
84
|
+
| `BELLWETHER_PARENT` | the parent session's registry id |
|
|
85
|
+
| `BELLWETHER_CHILD` | this child's record id |
|
|
86
|
+
| `BELLWETHER_CHILD_NAME` | this child's name |
|
|
87
|
+
| `BELLWETHER_DEPTH` | how many levels deep this child sits |
|
|
88
|
+
| `BELLWETHER_HARNESS` | `pi`, `claude-code`, or `other` |
|
|
89
|
+
|
|
90
|
+
## Layout
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
src/core/ herdr client, registry, watcher, classifier, outbox, spawn, report
|
|
94
|
+
src/daemon/ the daemon: protocol, server, client, lock, parent service
|
|
95
|
+
src/integrations/ the tool list, shared by both adapters
|
|
96
|
+
src/integrations/pi/ the Pi extension
|
|
97
|
+
src/integrations/claude/ the Claude Code MCP channel server
|
|
98
|
+
bin/ the bellwether command
|
|
99
|
+
docs/ probe results and notes
|
|
100
|
+
test/unit/ tier 1: fake clock, in-memory registry
|
|
101
|
+
test/integration/ tier 2: a fake herdr socket and the daemon, tier 3: a real isolated herdr server
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elecnix/bellwether",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Give an agent in herdr tools to start child agents in other tabs, and a new turn when a child changes state.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": "github:elecnix/bellwether",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi-package",
|
|
10
|
+
"claude-code",
|
|
11
|
+
"herdr",
|
|
12
|
+
"coding-agents"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22.18"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin/",
|
|
19
|
+
"src/"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"bellwether": "bin/bellwether.js",
|
|
26
|
+
"bellwether-mcp": "bin/bellwether-mcp.js"
|
|
27
|
+
},
|
|
28
|
+
"pi": {
|
|
29
|
+
"extensions": [
|
|
30
|
+
"./src/integrations/pi/extension.ts"
|
|
31
|
+
]
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"typecheck": "tsgo --noEmit -p .",
|
|
35
|
+
"test": "npm run test:unit && npm run test:integration && npm run test:lab",
|
|
36
|
+
"test:unit": "node --test --disable-warning=ExperimentalWarning \"test/unit/**/*.test.ts\"",
|
|
37
|
+
"test:integration": "node --test --test-concurrency=1 --disable-warning=ExperimentalWarning \"test/integration/**/*.test.ts\"",
|
|
38
|
+
"test:lab": "node --test --test-concurrency=1 --disable-warning=ExperimentalWarning \"test/lab/**/*.test.ts\"",
|
|
39
|
+
"doctor": "node --disable-warning=ExperimentalWarning src/cli.ts doctor"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@modelcontextprotocol/sdk": "1.32.2"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "22.20.5",
|
|
46
|
+
"@typescript/native-preview": "7.0.0-dev.20260707.2"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// The bellwether command.
|
|
2
|
+
//
|
|
3
|
+
// `watch` is the dogfood driver: it runs the same core the Pi extension and the
|
|
4
|
+
// Claude channel run, and prints one line per child event, so a supervisor can
|
|
5
|
+
// read the stream instead of polling herdr.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { HerdrClient, resolveSocketPath } from './core/herdr-client.ts';
|
|
9
|
+
import { bellwetherHome } from './core/paths.ts';
|
|
10
|
+
import { emptyParent, listParents, readParent, saveParent } from './core/registry.ts';
|
|
11
|
+
import { reportToParent, writeReport } from './core/report.ts';
|
|
12
|
+
import { DaemonClient } from './daemon/client.ts';
|
|
13
|
+
import { daemonIsLive, startDaemon } from './daemon/server.ts';
|
|
14
|
+
import type { OutboxEntry, ReportStatus } from './core/types.ts';
|
|
15
|
+
|
|
16
|
+
interface Flags {
|
|
17
|
+
[key: string]: string | number | boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function parseArgs(argv: string[]): { positional: string[]; flags: Flags } {
|
|
21
|
+
const positional: string[] = [];
|
|
22
|
+
const flags: Flags = {};
|
|
23
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
24
|
+
const token = argv[index] as string;
|
|
25
|
+
if (!token.startsWith('--')) {
|
|
26
|
+
positional.push(token);
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
const key = token.slice(2);
|
|
30
|
+
const next = argv[index + 1];
|
|
31
|
+
if (next === undefined || next.startsWith('--')) {
|
|
32
|
+
flags[key] = true;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (key === 'keys' || key === 'args') {
|
|
36
|
+
flags[key] = next;
|
|
37
|
+
} else if (key === 'stuck-minutes' || key === 'max-depth' || key === 'lines') {
|
|
38
|
+
flags[key] = Number(next);
|
|
39
|
+
} else {
|
|
40
|
+
flags[key] = next;
|
|
41
|
+
}
|
|
42
|
+
index += 1;
|
|
43
|
+
}
|
|
44
|
+
return { positional, flags };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function str(flags: Flags, key: string): string | undefined {
|
|
48
|
+
const value = flags[key];
|
|
49
|
+
return typeof value === 'string' && value.length ? value : undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function num(flags: Flags, key: string): number | undefined {
|
|
53
|
+
const value = flags[key];
|
|
54
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The registry this CLI run works against: an explicit id, the environment, or the newest. */
|
|
58
|
+
function parentFor(flags: Flags): { id: string; created: boolean } {
|
|
59
|
+
const explicit = str(flags, 'parent') ?? process.env['BELLWETHER_PARENT'];
|
|
60
|
+
if (explicit) return { id: explicit, created: false };
|
|
61
|
+
const name = `cli-${path.basename(process.cwd())}`;
|
|
62
|
+
const existing = readParent(name);
|
|
63
|
+
if (existing) return { id: existing.id, created: false };
|
|
64
|
+
saveParent({
|
|
65
|
+
...emptyParent('pi', name, process.cwd(), { host: process.env['HOSTNAME'] ?? '', paneId: process.env['HERDR_PANE_ID'], workspaceId: process.env['HERDR_WORKSPACE_ID'] }),
|
|
66
|
+
id: name,
|
|
67
|
+
});
|
|
68
|
+
return { id: name, created: true };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function clientFrom(flags: Flags): HerdrClient {
|
|
72
|
+
return new HerdrClient({ socketPath: str(flags, 'socket'), session: str(flags, 'session') });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function ok(label: string, detail: string): void {
|
|
76
|
+
console.log(` ok ${label}: ${detail}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function bad(label: string, detail: string): void {
|
|
80
|
+
console.log(` fail ${label}: ${detail}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The package root, found by walking up from this file to its package.json. */
|
|
84
|
+
function packageRoot(): string | undefined {
|
|
85
|
+
let dir = import.meta.dirname;
|
|
86
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
87
|
+
if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
|
|
88
|
+
const parent = path.dirname(dir);
|
|
89
|
+
if (parent === dir) return undefined;
|
|
90
|
+
dir = parent;
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type PackageManifest = {
|
|
96
|
+
pi?: { extensions?: string[] };
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** Harnesses load these two paths by name, so a missing one fails at load time.
|
|
100
|
+
* doctor names it here, before a user meets it inside a session. */
|
|
101
|
+
function checkPackaging(): number {
|
|
102
|
+
const root = packageRoot();
|
|
103
|
+
if (!root) {
|
|
104
|
+
bad('package root', 'no package.json above the CLI');
|
|
105
|
+
return 1;
|
|
106
|
+
}
|
|
107
|
+
let failures = 0;
|
|
108
|
+
let manifest: PackageManifest;
|
|
109
|
+
try {
|
|
110
|
+
manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as PackageManifest;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
bad('package.json', String(error));
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const extensions = manifest.pi?.extensions ?? [];
|
|
117
|
+
if (!extensions.length) {
|
|
118
|
+
bad('pi extension', 'package.json declares none');
|
|
119
|
+
failures += 1;
|
|
120
|
+
}
|
|
121
|
+
for (const entry of extensions) {
|
|
122
|
+
const file = path.resolve(root, entry);
|
|
123
|
+
if (fs.existsSync(file)) {
|
|
124
|
+
ok('pi extension', path.relative(root, file));
|
|
125
|
+
} else {
|
|
126
|
+
bad('pi extension', `${entry} does not exist`);
|
|
127
|
+
failures += 1;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const mcpEntry = path.join(root, 'bin', 'bellwether-mcp.js');
|
|
132
|
+
const label = path.relative(root, mcpEntry);
|
|
133
|
+
if (!fs.existsSync(mcpEntry)) {
|
|
134
|
+
bad('mcp entry', `${label} does not exist`);
|
|
135
|
+
failures += 1;
|
|
136
|
+
} else if (!(fs.statSync(mcpEntry).mode & 0o111)) {
|
|
137
|
+
bad('mcp entry', `${label} is not executable`);
|
|
138
|
+
failures += 1;
|
|
139
|
+
} else {
|
|
140
|
+
ok('mcp entry', label);
|
|
141
|
+
}
|
|
142
|
+
return failures;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function doctor(): Promise<number> {
|
|
146
|
+
let failures = 0;
|
|
147
|
+
console.log(`bellwether home ${bellwetherHome()}`);
|
|
148
|
+
const daemonSocket = path.join(bellwetherHome(), 'daemon.sock');
|
|
149
|
+
const daemonLive = daemonIsLive(bellwetherHome());
|
|
150
|
+
console.log(` ${daemonLive ? 'ok ' : 'info '} daemon: ${daemonLive ? 'running' : 'idle, starts on demand'} (${daemonSocket})`);
|
|
151
|
+
failures += checkPackaging();
|
|
152
|
+
const socket = resolveSocketPath();
|
|
153
|
+
if (!fs.existsSync(socket)) {
|
|
154
|
+
console.log(` fail herdr socket: ${socket} does not exist`);
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
console.log(` ok herdr socket: ${socket}`);
|
|
158
|
+
try {
|
|
159
|
+
const panes = await new HerdrClient({ socketPath: socket }).paneList();
|
|
160
|
+
console.log(` ok herdr api: ${panes.length} panes`);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
console.log(` fail herdr api: ${String(error)}`);
|
|
163
|
+
failures += 1;
|
|
164
|
+
}
|
|
165
|
+
for (const parent of listParents()) {
|
|
166
|
+
const live = parent.children.filter((child) => !child.exitedAt);
|
|
167
|
+
console.log(` ${parent.id}: ${live.length} live of ${parent.children.length} children, updated ${parent.updatedAt}`);
|
|
168
|
+
}
|
|
169
|
+
return failures;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function main(): Promise<number> {
|
|
173
|
+
const [command = 'help', ...rest] = process.argv.slice(2);
|
|
174
|
+
const { positional, flags } = parseArgs(rest);
|
|
175
|
+
|
|
176
|
+
if (command === 'help' || command === '--help') {
|
|
177
|
+
console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
|
|
178
|
+
console.log(' daemon [--socket PATH] run the local daemon in the foreground');
|
|
179
|
+
console.log(' spawn --kind KIND --name NAME [--cwd DIR] [--prompt TEXT] [--model M] [--parent ID] [--focus]');
|
|
180
|
+
console.log(' watch [--parent ID] [--tick-ms N] one line per child event, then keeps reading');
|
|
181
|
+
console.log(' list [--parent ID]');
|
|
182
|
+
console.log(' read CHILD [--lines N]');
|
|
183
|
+
console.log(' send CHILD [--text TEXT | --keys KEY,...]');
|
|
184
|
+
console.log(' stop CHILD [--force]');
|
|
185
|
+
console.log(' report --status done|needs-input|progress --text TEXT');
|
|
186
|
+
return 0;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (command === 'doctor') return doctor();
|
|
190
|
+
|
|
191
|
+
if (command === 'daemon') {
|
|
192
|
+
const socketPath = str(flags, 'socket') ?? process.env['BELLWETHER_DAEMON_SOCKET'] ?? path.join(bellwetherHome(), 'daemon.sock');
|
|
193
|
+
const daemon = await startDaemon({ socketPath, home: bellwetherHome(), log: (message) => console.error('[bellwether-daemon]', message) });
|
|
194
|
+
console.error(`[bellwether-daemon] listening on ${socketPath} with pid ${daemon.pid}`);
|
|
195
|
+
const stop = (): void => void daemon.close().then(() => process.exit(0));
|
|
196
|
+
process.on('SIGTERM', stop);
|
|
197
|
+
process.on('SIGINT', stop);
|
|
198
|
+
await daemon.whenClosed();
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (command === 'parents') {
|
|
203
|
+
for (const parent of listParents()) console.log(`${parent.id}\t${parent.children.length} children\t${parent.updatedAt}\t${parent.cwd}`);
|
|
204
|
+
return 0;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (command === 'report') {
|
|
208
|
+
const status = (str(flags, 'status') ?? 'progress') as ReportStatus;
|
|
209
|
+
const text = str(flags, 'text') ?? '';
|
|
210
|
+
if (!text) throw new Error('report needs --text');
|
|
211
|
+
if (!reportToParent(status, text)) {
|
|
212
|
+
const parentId = str(flags, 'parent');
|
|
213
|
+
if (!parentId) throw new Error('report needs BELLWETHER_PARENT or --parent');
|
|
214
|
+
writeReport({ parentId, childName: process.env['BELLWETHER_CHILD_NAME'] ?? 'child', status, text });
|
|
215
|
+
}
|
|
216
|
+
return 0;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const { id: parentId } = parentFor(flags);
|
|
220
|
+
const parent = readParent(parentId);
|
|
221
|
+
if (!parent) throw new Error(`No parent registry ${parentId}. Run bellwether list once to create it.`);
|
|
222
|
+
const daemon = await DaemonClient.connect({
|
|
223
|
+
harness: parent.harness,
|
|
224
|
+
session: parent.session,
|
|
225
|
+
cwd: parent.cwd,
|
|
226
|
+
host: parent.host,
|
|
227
|
+
paneId: parent.paneId,
|
|
228
|
+
workspaceId: parent.workspaceId,
|
|
229
|
+
depth: parent.depth,
|
|
230
|
+
herdrSocket: resolveSocketPath({ socketPath: str(flags, 'socket'), session: str(flags, 'session') }),
|
|
231
|
+
}, { log: (message) => console.error('[bellwether]', message) });
|
|
232
|
+
|
|
233
|
+
if (command === 'watch') {
|
|
234
|
+
const printed = new Set<string>();
|
|
235
|
+
const emit = (entry: OutboxEntry): void => {
|
|
236
|
+
if (printed.has(entry.receipt) || entry.read) return;
|
|
237
|
+
printed.add(entry.receipt);
|
|
238
|
+
console.log(`CHILD ${entry.event} ${entry.name} ${entry.paneId} unread=${entry.receipt} at=${entry.at}`);
|
|
239
|
+
console.log(` ${entry.text.split('\n').join('\n ')}`);
|
|
240
|
+
};
|
|
241
|
+
daemon.onEvents((entries) => entries.forEach(emit));
|
|
242
|
+
(await daemon.pending()).forEach(emit);
|
|
243
|
+
console.log(`READY watch parent=${parentId} home=${bellwetherHome()}`);
|
|
244
|
+
const keepAlive = setInterval(() => {}, 60_000);
|
|
245
|
+
process.on('SIGINT', () => {
|
|
246
|
+
clearInterval(keepAlive);
|
|
247
|
+
void daemon.close().then(() => process.exit(0));
|
|
248
|
+
});
|
|
249
|
+
await new Promise(() => {});
|
|
250
|
+
return 0;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
if (command === 'spawn') {
|
|
255
|
+
const name = str(flags, 'name');
|
|
256
|
+
if (!name) throw new Error('spawn needs --name');
|
|
257
|
+
console.log(await daemon.tool('agent_spawn', {
|
|
258
|
+
kind: str(flags, 'kind') ?? 'pi',
|
|
259
|
+
name,
|
|
260
|
+
cwd: str(flags, 'cwd'),
|
|
261
|
+
prompt: str(flags, 'prompt'),
|
|
262
|
+
model: str(flags, 'model'),
|
|
263
|
+
focus: flags['focus'] === true,
|
|
264
|
+
stuckMinutes: num(flags, 'stuck-minutes'),
|
|
265
|
+
maxDepth: num(flags, 'max-depth'),
|
|
266
|
+
args: str(flags, 'args')?.split('\u0000'),
|
|
267
|
+
}));
|
|
268
|
+
} else if (command === 'list') {
|
|
269
|
+
console.log(await daemon.tool('agent_list', {}));
|
|
270
|
+
} else if (command === 'read') {
|
|
271
|
+
const child = positional[0];
|
|
272
|
+
if (!child) throw new Error('read needs a child');
|
|
273
|
+
console.log(await daemon.tool('agent_read', { child, lines: num(flags, 'lines') }));
|
|
274
|
+
} else if (command === 'send') {
|
|
275
|
+
const child = positional[0];
|
|
276
|
+
if (!child) 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
|
+
} else if (command === 'stop') {
|
|
280
|
+
const child = positional[0];
|
|
281
|
+
if (!child) throw new Error('stop needs a child');
|
|
282
|
+
console.log(await daemon.tool('agent_stop', { child, force: flags['force'] === true }));
|
|
283
|
+
} else {
|
|
284
|
+
console.log('Usage: bellwether <daemon|spawn|watch|list|read|send|stop|report|parents|doctor>');
|
|
285
|
+
return 1;
|
|
286
|
+
}
|
|
287
|
+
} finally {
|
|
288
|
+
await daemon.close();
|
|
289
|
+
}
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
process.exitCode = await main();
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The classifier: turns herdr states into child events, with a settle time for
|
|
2
|
+
// each. It is a pure function of (state, clock, observation) so tier 1 can run
|
|
3
|
+
// it against a fake clock without a socket.
|
|
4
|
+
import type { AgentStatus, ChildEventKind } from './types.ts';
|
|
5
|
+
|
|
6
|
+
/** Starting values. The lab tunes these; they are not measurements. */
|
|
7
|
+
export const DEFAULT_LIMITS: SettleLimits = {
|
|
8
|
+
idleMs: 5_000,
|
|
9
|
+
blockedMs: 3_000,
|
|
10
|
+
stuckMs: 10 * 60_000,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export interface SettleLimits {
|
|
14
|
+
/** How long an idle child waits, so a quick next turn sends no message. */
|
|
15
|
+
idleMs: number;
|
|
16
|
+
/** How long a blocked child waits before its dialog is worth reading. */
|
|
17
|
+
blockedMs: number;
|
|
18
|
+
/** How long a working child may be quiet before it is stuck. */
|
|
19
|
+
stuckMs: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The per-child clock the classifier keeps between observations. */
|
|
23
|
+
export interface ClassifierState {
|
|
24
|
+
status: AgentStatus;
|
|
25
|
+
/** When the status last changed, for the settle time. */
|
|
26
|
+
statusSince: number;
|
|
27
|
+
/** herdr's completion_seq for the newest finished turn. */
|
|
28
|
+
completionSeq?: number;
|
|
29
|
+
/** The newest turn a report has already covered. */
|
|
30
|
+
reportedFor?: number;
|
|
31
|
+
/** The last time the child moved: output, transcript growth, or a report. */
|
|
32
|
+
lastBusyAt: number;
|
|
33
|
+
/** Set once an event fired for the current quiet period, so it fires once. */
|
|
34
|
+
firedStuckSince?: number;
|
|
35
|
+
/** Set once the blocked event fired, so the dialog is reported once. */
|
|
36
|
+
firedBlocked?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface Observation {
|
|
40
|
+
status: AgentStatus;
|
|
41
|
+
completionSeq?: number;
|
|
42
|
+
/** True when the child produced output or its transcript grew since the last look. */
|
|
43
|
+
busy?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function initialState(status: AgentStatus, now: number): ClassifierState {
|
|
47
|
+
return { status, statusSince: now, lastBusyAt: now };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isReady(status: AgentStatus): boolean {
|
|
51
|
+
return status === 'idle' || status === 'done';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Fold one observation into the state and say whether an event is due.
|
|
56
|
+
* The returned state is a new object; the classifier never mutates its input.
|
|
57
|
+
*/
|
|
58
|
+
export function advance(state: ClassifierState, observation: Observation, now: number, limits: SettleLimits = DEFAULT_LIMITS): { state: ClassifierState; event?: ChildEventKind } {
|
|
59
|
+
const next: ClassifierState = { ...state };
|
|
60
|
+
if (observation.status !== state.status) {
|
|
61
|
+
next.status = observation.status;
|
|
62
|
+
next.statusSince = now;
|
|
63
|
+
next.firedStuckSince = undefined;
|
|
64
|
+
next.firedBlocked = undefined;
|
|
65
|
+
}
|
|
66
|
+
const becameReady = isReady(observation.status) && !isReady(state.status);
|
|
67
|
+
if (observation.completionSeq !== undefined && observation.completionSeq !== state.completionSeq) {
|
|
68
|
+
next.completionSeq = observation.completionSeq;
|
|
69
|
+
next.statusSince = now;
|
|
70
|
+
} else if (observation.completionSeq === undefined && becameReady) {
|
|
71
|
+
// herdr reports completion_seq on AgentInfo, and the watcher reads that
|
|
72
|
+
// projection, so a reconciled child normally carries one. The field is
|
|
73
|
+
// still absent before the first reconcile finishes, and on a pane herdr
|
|
74
|
+
// has not observed working for: a turn that ends faster than screen
|
|
75
|
+
// detection catches it leaves the value unchanged. A turn that ends is
|
|
76
|
+
// also visible as a status change into idle or done, so count those.
|
|
77
|
+
next.completionSeq = (state.completionSeq ?? 0) + 1;
|
|
78
|
+
next.statusSince = now;
|
|
79
|
+
}
|
|
80
|
+
if (observation.busy) {
|
|
81
|
+
next.lastBusyAt = now;
|
|
82
|
+
next.firedStuckSince = undefined;
|
|
83
|
+
next.firedBlocked = undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A blocked child stays blocked until someone answers it, so report the
|
|
87
|
+
// dialog once and then wait for the status to move rather than repeating it
|
|
88
|
+
// on every tick.
|
|
89
|
+
if (next.status === 'blocked' && now - next.statusSince >= limits.blockedMs && !next.firedBlocked) {
|
|
90
|
+
return { state: { ...next, firedBlocked: true }, event: 'blocked' };
|
|
91
|
+
}
|
|
92
|
+
if (isReady(next.status) && next.completionSeq !== undefined && next.completionSeq !== next.reportedFor && now - next.statusSince >= limits.idleMs) {
|
|
93
|
+
return { state: { ...next, reportedFor: next.completionSeq }, event: 'idle' };
|
|
94
|
+
}
|
|
95
|
+
// A child first seen already settled still owes its parent one message.
|
|
96
|
+
if (isReady(next.status) && next.completionSeq === undefined && state.status !== next.status && now - next.statusSince >= limits.idleMs) {
|
|
97
|
+
return { state: { ...next, completionSeq: 1, reportedFor: 1 }, event: 'idle' };
|
|
98
|
+
}
|
|
99
|
+
if ((next.status === 'working' || next.status === 'unknown') && next.firedStuckSince !== next.lastBusyAt && now - next.lastBusyAt >= limits.stuckMs) {
|
|
100
|
+
return { state: { ...next, firedStuckSince: next.lastBusyAt }, event: 'stuck' };
|
|
101
|
+
}
|
|
102
|
+
return { state: next };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Mark the newest turn as covered by a report, so no idle event follows it. */
|
|
106
|
+
export function markReported(state: ClassifierState, now: number): ClassifierState {
|
|
107
|
+
return { ...state, reportedFor: state.completionSeq, lastBusyAt: now, statusSince: now };
|
|
108
|
+
}
|