@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
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// The receipt scan. Claude Code writes one JSONL line per event to
|
|
2
|
+
// ~/.claude/projects/<slug>/<session>.jsonl, and a channel notification lands
|
|
3
|
+
// there once the model receives it. An entry counts as read when its receipt
|
|
4
|
+
// id appears in the file, which is the same trick your-attention uses for its
|
|
5
|
+
// answers.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { claudeProjectDir } from '../../core/transcript.js';
|
|
10
|
+
/** Claude Code's state root, which a lab overrides with CLAUDE_CONFIG_DIR. */
|
|
11
|
+
export function claudeConfigDir() {
|
|
12
|
+
return process.env['CLAUDE_CONFIG_DIR'] ?? path.join(os.homedir(), '.claude');
|
|
13
|
+
}
|
|
14
|
+
export function findTranscript(session, cwd, configDir) {
|
|
15
|
+
const root = path.join(configDir ?? claudeConfigDir(), 'projects');
|
|
16
|
+
if (cwd) {
|
|
17
|
+
const direct = path.join(root, claudeProjectDir(cwd), `${session}.jsonl`);
|
|
18
|
+
if (fs.existsSync(direct))
|
|
19
|
+
return direct;
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
for (const dir of fs.readdirSync(root)) {
|
|
23
|
+
const file = path.join(root, dir, `${session}.jsonl`);
|
|
24
|
+
if (fs.existsSync(file))
|
|
25
|
+
return file;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// A missing projects directory is not an error: the scan simply waits.
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Read a byte range in pieces, so a long session log never sits in memory whole. */
|
|
34
|
+
function readRange(file, from, to) {
|
|
35
|
+
const pieces = [];
|
|
36
|
+
const fd = fs.openSync(file, 'r');
|
|
37
|
+
try {
|
|
38
|
+
const size = 4 * 1024 * 1024;
|
|
39
|
+
let at = from;
|
|
40
|
+
while (at < to) {
|
|
41
|
+
const length = Math.min(size, to - at);
|
|
42
|
+
const buffer = Buffer.alloc(length);
|
|
43
|
+
const read = fs.readSync(fd, buffer, 0, length, at);
|
|
44
|
+
if (read <= 0)
|
|
45
|
+
break;
|
|
46
|
+
pieces.push(buffer.toString('utf8', 0, read));
|
|
47
|
+
at += read;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
fs.closeSync(fd);
|
|
52
|
+
}
|
|
53
|
+
return pieces.join('');
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Incremental reader over one transcript. The offset starts at the file size
|
|
57
|
+
* when the server connects, so only later bytes count: a receipt id from an
|
|
58
|
+
* earlier run of the same session must not mark a new entry read.
|
|
59
|
+
*/
|
|
60
|
+
export class ReceiptScan {
|
|
61
|
+
session;
|
|
62
|
+
cwd;
|
|
63
|
+
configDir;
|
|
64
|
+
transcript;
|
|
65
|
+
offset = 0;
|
|
66
|
+
constructor(session, cwd, configDir) {
|
|
67
|
+
this.session = session;
|
|
68
|
+
this.cwd = cwd;
|
|
69
|
+
this.configDir = configDir;
|
|
70
|
+
}
|
|
71
|
+
/** Anchor at the current end of the transcript, wherever it is. */
|
|
72
|
+
start() {
|
|
73
|
+
this.transcript = findTranscript(this.session, this.cwd, this.configDir);
|
|
74
|
+
if (!this.transcript)
|
|
75
|
+
return;
|
|
76
|
+
try {
|
|
77
|
+
this.offset = fs.statSync(this.transcript).size;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
this.offset = 0;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Receipts already present anywhere in the file. Run once at startup, so an
|
|
85
|
+
* event the previous server pushed is not pushed a second time.
|
|
86
|
+
*/
|
|
87
|
+
search(receipts) {
|
|
88
|
+
const found = new Set();
|
|
89
|
+
const wanted = [...receipts];
|
|
90
|
+
if (!wanted.length)
|
|
91
|
+
return found;
|
|
92
|
+
const file = this.transcript ?? findTranscript(this.session, this.cwd, this.configDir);
|
|
93
|
+
if (!file)
|
|
94
|
+
return found;
|
|
95
|
+
let size;
|
|
96
|
+
try {
|
|
97
|
+
size = fs.statSync(file).size;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
if (size === 0)
|
|
103
|
+
return found;
|
|
104
|
+
const content = readRange(file, 0, size);
|
|
105
|
+
for (const receipt of wanted)
|
|
106
|
+
if (content.includes(receipt))
|
|
107
|
+
found.add(receipt);
|
|
108
|
+
return found;
|
|
109
|
+
}
|
|
110
|
+
/** The receipt ids that reached the transcript since the last scan. */
|
|
111
|
+
scan(receipts) {
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
const wanted = [...receipts];
|
|
114
|
+
if (!wanted.length)
|
|
115
|
+
return seen;
|
|
116
|
+
this.transcript ??= findTranscript(this.session, this.cwd, this.configDir);
|
|
117
|
+
if (!this.transcript)
|
|
118
|
+
return seen;
|
|
119
|
+
let size;
|
|
120
|
+
try {
|
|
121
|
+
size = fs.statSync(this.transcript).size;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return seen;
|
|
125
|
+
}
|
|
126
|
+
if (size <= this.offset)
|
|
127
|
+
return seen;
|
|
128
|
+
const added = readRange(this.transcript, this.offset, size);
|
|
129
|
+
this.offset = size;
|
|
130
|
+
for (const receipt of wanted)
|
|
131
|
+
if (added.includes(receipt))
|
|
132
|
+
seen.add(receipt);
|
|
133
|
+
return seen;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// The Pi extension: the Bellwether tools for the parent, and a new turn when
|
|
2
|
+
// a child changes state. The core runs in the daemon; this extension is one
|
|
3
|
+
// client of it. It never types into the parent's pane: it wakes the session
|
|
4
|
+
// through pi.sendMessage, and the receipt id in the message marks the event
|
|
5
|
+
// read once the model context contains it.
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import { DaemonClient } from '../../daemon/client.js';
|
|
8
|
+
import { resolveSocketPath } from '../../core/herdr-client.js';
|
|
9
|
+
import { hostName } from '../../core/spawn.js';
|
|
10
|
+
import { childLabel } from '../../core/label.js';
|
|
11
|
+
import { toolsFor } from '../tools.js';
|
|
12
|
+
const result = (text) => ({ content: [{ type: 'text', text }], details: undefined });
|
|
13
|
+
/** How many Bellwether generations deep this session sits. */
|
|
14
|
+
function depthFromEnv() {
|
|
15
|
+
const value = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10);
|
|
16
|
+
return Number.isFinite(value) ? value : 0;
|
|
17
|
+
}
|
|
18
|
+
/** One message for a burst of events, so three children changing at once read once. */
|
|
19
|
+
function compose(entries) {
|
|
20
|
+
if (!entries.length)
|
|
21
|
+
return '';
|
|
22
|
+
const head = entries.length === 1 ? '[bellwether]' : `[bellwether] ${entries.length} children changed`;
|
|
23
|
+
const body = entries
|
|
24
|
+
.map((entry) => `${childLabel({ name: entry.name, paneId: entry.paneId, id: entry.childId })} ${entry.event}, a ${entry.kind} agent — receipt ${entry.receipt}\n${entry.text}`)
|
|
25
|
+
.join('\n\n');
|
|
26
|
+
return `${head}\n${body}\n\nRead more with agent_read. Reply with agent_send.`;
|
|
27
|
+
}
|
|
28
|
+
export default function bellwether(pi) {
|
|
29
|
+
let daemon;
|
|
30
|
+
let burst;
|
|
31
|
+
let pending = [];
|
|
32
|
+
// Receipts this session has already put in front of the model.
|
|
33
|
+
const sent = new Set();
|
|
34
|
+
const flush = () => {
|
|
35
|
+
burst = undefined;
|
|
36
|
+
if (!pending.length)
|
|
37
|
+
return;
|
|
38
|
+
const batch = pending;
|
|
39
|
+
pending = [];
|
|
40
|
+
const text = compose(batch);
|
|
41
|
+
if (!text)
|
|
42
|
+
return;
|
|
43
|
+
for (const entry of batch)
|
|
44
|
+
sent.add(entry.receipt);
|
|
45
|
+
// The message waits until the agent has no tool calls left, then starts the turn.
|
|
46
|
+
pi.sendMessage({ customType: 'bellwether', content: text, display: true, details: { digest: 'child events' } }, { triggerTurn: true, deliverAs: 'followUp' });
|
|
47
|
+
};
|
|
48
|
+
const onEntries = (entries) => {
|
|
49
|
+
const fresh = entries.filter((entry) => !sent.has(entry.receipt) && !entry.read);
|
|
50
|
+
if (!fresh.length)
|
|
51
|
+
return;
|
|
52
|
+
pending = fresh;
|
|
53
|
+
if (burst)
|
|
54
|
+
return;
|
|
55
|
+
burst = setTimeout(flush, 250);
|
|
56
|
+
burst.unref?.();
|
|
57
|
+
};
|
|
58
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
59
|
+
try {
|
|
60
|
+
daemon = await DaemonClient.connect({
|
|
61
|
+
harness: 'pi',
|
|
62
|
+
session: ctx.sessionManager.getSessionId(),
|
|
63
|
+
cwd: ctx.sessionManager.getCwd(),
|
|
64
|
+
host: hostName() || os.hostname(),
|
|
65
|
+
paneId: process.env['HERDR_PANE_ID'],
|
|
66
|
+
workspaceId: process.env['HERDR_WORKSPACE_ID'],
|
|
67
|
+
depth: depthFromEnv(),
|
|
68
|
+
herdrSocket: resolveSocketPath(),
|
|
69
|
+
childId: process.env['BELLWETHER_CHILD'],
|
|
70
|
+
}, { log: (message) => console.error('[bellwether]', message) });
|
|
71
|
+
daemon.onEvents(onEntries);
|
|
72
|
+
const missed = await daemon.pending();
|
|
73
|
+
if (missed.length)
|
|
74
|
+
onEntries(missed);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
console.error('[bellwether] the daemon did not start:', error.message);
|
|
78
|
+
daemon = undefined;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
pi.on('session_shutdown', () => {
|
|
82
|
+
if (burst)
|
|
83
|
+
clearTimeout(burst);
|
|
84
|
+
burst = undefined;
|
|
85
|
+
pending = [];
|
|
86
|
+
void daemon?.close();
|
|
87
|
+
daemon = undefined;
|
|
88
|
+
});
|
|
89
|
+
// A receipt that reaches the model context marks its event read.
|
|
90
|
+
pi.on('context', (event) => {
|
|
91
|
+
if (!daemon)
|
|
92
|
+
return;
|
|
93
|
+
const seen = JSON.stringify(event.messages);
|
|
94
|
+
const receipts = daemon.unread().filter((entry) => seen.includes(entry.receipt)).map((entry) => entry.receipt);
|
|
95
|
+
if (receipts.length)
|
|
96
|
+
daemon.receipts(receipts);
|
|
97
|
+
});
|
|
98
|
+
const tools = toolsFor({ parent: process.env['BELLWETHER_PARENT'], child: process.env['BELLWETHER_CHILD'] });
|
|
99
|
+
for (const tool of tools) {
|
|
100
|
+
pi.registerTool({
|
|
101
|
+
name: tool.name,
|
|
102
|
+
label: tool.name.replace(/_/g, ' '),
|
|
103
|
+
description: tool.description,
|
|
104
|
+
parameters: tool.schema,
|
|
105
|
+
async execute(_id, args, signal) {
|
|
106
|
+
if (!daemon)
|
|
107
|
+
return result('Bellwether is not running: the daemon did not start for this session.');
|
|
108
|
+
if (signal?.aborted)
|
|
109
|
+
return result('Cancelled.');
|
|
110
|
+
try {
|
|
111
|
+
return result(await daemon.tool(tool.name, args));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
return result(error.message);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// The Bellwether tools, in one list, so the Pi extension and the Claude
|
|
2
|
+
// MCP channel server register exactly the same names and schemas.
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import { AGENT_KINDS, DEFAULT_MAX_DEPTH, spawnChild } from '../core/spawn.js';
|
|
6
|
+
import { removeChildFiles } from '../core/mcp-config.js';
|
|
7
|
+
import { reportForCaller } from '../core/report.js';
|
|
8
|
+
import { childById, readParent, updateChild } from '../core/registry.js';
|
|
9
|
+
import { adoptPane } from '../core/adopt.js';
|
|
10
|
+
import { LOCAL_HOST, hostOf } from '../core/machine.js';
|
|
11
|
+
import { spawnResume } from '../core/spawn-resume.js';
|
|
12
|
+
import { promptChild } from '../core/send.js';
|
|
13
|
+
import { RETIRE_TOOL, realRetireOps, requestRetirement } from '../core/retire.js';
|
|
14
|
+
function clientFor(ctx, host) {
|
|
15
|
+
if (ctx.clientFor)
|
|
16
|
+
return ctx.clientFor(host);
|
|
17
|
+
return host === LOCAL_HOST ? Promise.resolve(ctx.client) : Promise.reject(new Error(`This session cannot reach herdr machine ${host}.`));
|
|
18
|
+
}
|
|
19
|
+
const MACHINE_DESCRIPTION = 'A saved herdr machine, by label or id as `herdr machine list` shows it. Omit it for this machine. A child on another machine cannot call parent_report, because its report lands on that machine\'s disk, so Bellwether follows it through herdr status alone.';
|
|
20
|
+
const optionalString = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
|
|
21
|
+
/** The tools any session gets. */
|
|
22
|
+
export const parentTools = [
|
|
23
|
+
{
|
|
24
|
+
name: 'agent_spawn',
|
|
25
|
+
description: 'Start a child coding agent in its own herdr tab, of any kind herdr can start. Bellwether watches it and starts your next turn when it reports, goes idle, blocks, stalls or exits. Give the prompt a concrete deliverable, and tell the child to call parent_report when it is done. With resume, the call is a message to an earlier child instead: a child herdr still shows gets the prompt as an ordinary message, with no new tab, and a retired one comes back in a new tab with its harness reopening the same session, under the same child id, so its history and unread events continue. Resume works for claude and pi children.',
|
|
26
|
+
schema: {
|
|
27
|
+
type: 'object',
|
|
28
|
+
properties: {
|
|
29
|
+
resume: { type: 'string', description: 'Message an earlier child rather than start a new one: its name, its id, or its session id. herdr decides whether it is alive. A session id no child of this session ran also takes kind, name, cwd and machine, and comes back as a new child. Omit it to start a new child.' },
|
|
30
|
+
kind: { type: 'string', enum: [...AGENT_KINDS], description: 'The harness to start: pi, claude, codex, opencode or cline. Required without resume.' },
|
|
31
|
+
name: { type: 'string', description: 'A short handle for the child, unique in this session. Used as the herdr agent name and the tab label. Required without resume.' },
|
|
32
|
+
cwd: { type: 'string', description: 'The directory to start the child in. Use an absolute path, ideally a git worktree of its own.' },
|
|
33
|
+
prompt: { type: 'string', description: 'The first message the child receives, or with resume the message for the earlier child. The whole prompt, not a path. Line breaks and any length are fine: Bellwether hands a new or resumed child the prompt through a private file.' },
|
|
34
|
+
model: { type: 'string', description: 'The model or tier to pass to the child harness.' },
|
|
35
|
+
args: { type: 'array', items: { type: 'string' }, description: 'Extra arguments for the child harness, passed through unchanged and appended last.' },
|
|
36
|
+
focus: { type: 'boolean', description: 'Move your view to the new tab. Defaults to false, so the child does not steal focus.' },
|
|
37
|
+
stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
|
|
38
|
+
inactive_minutes: { type: 'number', description: 'How long the child may show no activity of any kind, blocked included, before you are told. Defaults to 5. Clamped to between 1 and 1440. It cannot be turned off.' },
|
|
39
|
+
max_depth: { type: 'number', description: 'How deep children may spawn children. Defaults to 2.' },
|
|
40
|
+
machine: { type: 'string', description: `${MACHINE_DESCRIPTION} With resume, a known child always goes back to its own machine.` },
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: 'agent_adopt',
|
|
46
|
+
description: 'Make a running agent that this session did not start into its child, such as one herdr-spawn.sh or a person started. Bellwether then watches it like a spawned child. Refuses a pane another session already watches, and a pane with no agent herdr recognizes. An adopted child has no BELLWETHER_PARENT, so it cannot call parent_report.',
|
|
47
|
+
schema: {
|
|
48
|
+
type: 'object',
|
|
49
|
+
properties: {
|
|
50
|
+
target: { type: 'string', description: 'The pane id, or the herdr name of the live agent.' },
|
|
51
|
+
name: { type: 'string', description: 'The handle to use for the child. Defaults to its herdr name.' },
|
|
52
|
+
machine: { type: 'string', description: MACHINE_DESCRIPTION },
|
|
53
|
+
stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
|
|
54
|
+
},
|
|
55
|
+
required: ['target'],
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: 'agent_list',
|
|
60
|
+
description: 'List this session\'s children with status, age and unread events.',
|
|
61
|
+
schema: { type: 'object', properties: {} },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'agent_read',
|
|
65
|
+
description: 'Read a child: its last assistant message by default, or its screen when you pass lines.',
|
|
66
|
+
schema: {
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
70
|
+
lines: { type: 'number', description: 'Read this many screen lines instead of the last message.' },
|
|
71
|
+
},
|
|
72
|
+
required: ['child'],
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
name: 'agent_send',
|
|
77
|
+
description: 'Prompt a child with herdr agent.prompt. herdr refuses a blocked child, so for one this returns the dialog and takes keys to answer it instead.',
|
|
78
|
+
schema: {
|
|
79
|
+
type: 'object',
|
|
80
|
+
properties: {
|
|
81
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
82
|
+
text: { type: 'string', description: 'The prompt to submit.' },
|
|
83
|
+
keys: { type: 'array', items: { type: 'string' }, description: 'Key presses to send instead of a prompt, named as ctrl+c or enter.' },
|
|
84
|
+
},
|
|
85
|
+
required: ['child'],
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'agent_stop',
|
|
90
|
+
description: 'Close a child\'s tab, which ends it. Refuses a working child unless you pass force.',
|
|
91
|
+
schema: {
|
|
92
|
+
type: 'object',
|
|
93
|
+
properties: {
|
|
94
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
95
|
+
force: { type: 'boolean', description: 'Close the tab even while the child is working or blocked.' },
|
|
96
|
+
},
|
|
97
|
+
required: ['child'],
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
];
|
|
101
|
+
/** The one tool a child gets, when its environment names a parent. */
|
|
102
|
+
export const childTools = [
|
|
103
|
+
{
|
|
104
|
+
name: 'parent_report',
|
|
105
|
+
description: 'Tell the parent session what happened. Call it when the task is done, when you need input to continue, or to report progress on a long task.',
|
|
106
|
+
schema: {
|
|
107
|
+
type: 'object',
|
|
108
|
+
properties: {
|
|
109
|
+
status: { type: 'string', enum: ['done', 'needs-input', 'progress'], description: 'done finishes the task, needs-input asks a question, progress is a status note.' },
|
|
110
|
+
text: { type: 'string', description: 'What to tell the parent. For done, the result. For needs-input, the question and the options you weighed.' },
|
|
111
|
+
},
|
|
112
|
+
required: ['status', 'text'],
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
];
|
|
116
|
+
/** The tool a child Bellwether spawned gets, when its environment carries BELLWETHER_CHILD. */
|
|
117
|
+
export const retireTools = [
|
|
118
|
+
{
|
|
119
|
+
name: RETIRE_TOOL,
|
|
120
|
+
description: 'Ask to be retired once you exit: the Bellwether daemon then removes your worktree and deletes your branch, but only after your pane and tab are gone, the worktree is not a main worktree, is clean and has no stash, the branch is merged or pushed with its pull request merged or closed, and no process works inside it. The call removes nothing. It runs the checks it can run now and says which pass, records the request, and leaves the rest to the daemon. Close your tab afterwards.',
|
|
121
|
+
schema: {
|
|
122
|
+
type: 'object',
|
|
123
|
+
properties: {
|
|
124
|
+
reason: { type: 'string', description: 'Why the work is finished, kept on your record and in the retire log.' },
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
];
|
|
129
|
+
/**
|
|
130
|
+
* The tools a session gets, from its environment: every session gets the
|
|
131
|
+
* parent tools, a session with a parent also gets parent_report, and only a
|
|
132
|
+
* session with a child id gets the retirement request.
|
|
133
|
+
*/
|
|
134
|
+
export function toolsFor(env) {
|
|
135
|
+
return [...parentTools, ...(env.parent || env.child ? childTools : []), ...(env.child ? retireTools : [])];
|
|
136
|
+
}
|
|
137
|
+
export function toolSchema(name) {
|
|
138
|
+
return [...parentTools, ...childTools, ...retireTools].find((tool) => tool.name === name)?.schema;
|
|
139
|
+
}
|
|
140
|
+
function resolve(record, child) {
|
|
141
|
+
return record ? childById(record, child) : undefined;
|
|
142
|
+
}
|
|
143
|
+
function describeChild(child, watcher) {
|
|
144
|
+
const unread = watcher.outboxEntries().filter((entry) => !entry.read && entry.childId === child.id).length;
|
|
145
|
+
const age = Math.max(0, Math.round((Date.now() - Date.parse(child.startedAt)) / 1000));
|
|
146
|
+
const retire = child.retireOutcome === 'removed' ? ', retired' : child.retireOutcome === 'refused' ? ', retirement refused' : child.retireRequestedAt ? ', retirement requested' : '';
|
|
147
|
+
const state = `${child.exitedAt ? `exited${child.exitCode === undefined ? '' : ` (${child.exitCode})`}` : child.lastStatus}${retire}`;
|
|
148
|
+
return `${child.name}\t${child.kind}\t${state}\t${age}s\t${hostOf(child)}\t${child.paneId}\tunread ${unread}\t${child.cwd ?? ''}`;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Run one tool for a session. `caller` is the identity the session's adapter
|
|
152
|
+
* sent with the call; parent_report routes by it and by the child records
|
|
153
|
+
* this daemon holds, never by the daemon's own environment.
|
|
154
|
+
*/
|
|
155
|
+
export async function runBellwetherTool(ctx, name, args, caller = {}) {
|
|
156
|
+
if (name === 'parent_report') {
|
|
157
|
+
const status = optionalString(args['status']);
|
|
158
|
+
const text = optionalString(args['text']);
|
|
159
|
+
if (!status || !text)
|
|
160
|
+
throw new Error('parent_report needs both status and text');
|
|
161
|
+
const written = reportForCaller(caller, status, text);
|
|
162
|
+
return `Reported ${status} to the parent, as ${written.childName}.`;
|
|
163
|
+
}
|
|
164
|
+
if (name === RETIRE_TOOL) {
|
|
165
|
+
// Routed by the caller's identity and this daemon's records, like parent_report.
|
|
166
|
+
return requestRetirement(caller, ctx.retireOps ?? realRetireOps(), optionalString(args['reason']));
|
|
167
|
+
}
|
|
168
|
+
const record = readParent(ctx.parentId);
|
|
169
|
+
if (!record)
|
|
170
|
+
throw new Error(`No Bellwether registry for ${ctx.parentId}. Start a session with the Bellwether extension loaded.`);
|
|
171
|
+
if (name === 'agent_spawn' && optionalString(args['resume'])) {
|
|
172
|
+
const result = await spawnResume((host) => clientFor(ctx, host), ctx.parentId, {
|
|
173
|
+
target: optionalString(args['resume']) ?? '',
|
|
174
|
+
prompt: optionalString(args['prompt']),
|
|
175
|
+
kind: optionalString(args['kind']),
|
|
176
|
+
name: optionalString(args['name']),
|
|
177
|
+
cwd: optionalString(args['cwd']),
|
|
178
|
+
host: optionalString(args['machine']),
|
|
179
|
+
model: optionalString(args['model']),
|
|
180
|
+
args: Array.isArray(args['args']) ? args['args'] : undefined,
|
|
181
|
+
focus: args['focus'] === true,
|
|
182
|
+
});
|
|
183
|
+
const { child } = result;
|
|
184
|
+
const lines = result.corrected ? [result.corrected] : [];
|
|
185
|
+
if (result.action === 'messaged') {
|
|
186
|
+
if (result.corrected)
|
|
187
|
+
ctx.watcher.reset(child.id);
|
|
188
|
+
lines.push(`${child.name} is still alive in pane ${child.paneId}, so the prompt went to it as a message, with no new tab.`, result.reply, `herdr link: ${result.link}`);
|
|
189
|
+
return lines.join('\n');
|
|
190
|
+
}
|
|
191
|
+
ctx.watcher.reset(child.id);
|
|
192
|
+
const where = child.host === LOCAL_HOST ? '' : ` on machine ${child.host}`;
|
|
193
|
+
lines.push(`${child.name} resumed session ${result.session.value}${where} in pane ${child.paneId}, as the same child ${child.id}.`, 'Bellwether watches it again, and its earlier events and receipts carry on.', `herdr link: ${result.link}`);
|
|
194
|
+
return lines.join('\n');
|
|
195
|
+
}
|
|
196
|
+
if (name === 'agent_spawn') {
|
|
197
|
+
const options = {
|
|
198
|
+
kind: optionalString(args['kind']) ?? 'pi',
|
|
199
|
+
name: optionalString(args['name']) ?? '',
|
|
200
|
+
cwd: optionalString(args['cwd']),
|
|
201
|
+
prompt: optionalString(args['prompt']),
|
|
202
|
+
model: optionalString(args['model']),
|
|
203
|
+
args: Array.isArray(args['args']) ? args['args'] : undefined,
|
|
204
|
+
focus: args['focus'] === true,
|
|
205
|
+
stuckMinutes: typeof args['stuck_minutes'] === 'number' ? args['stuck_minutes'] : undefined,
|
|
206
|
+
inactiveMinutes: typeof args['inactive_minutes'] === 'number' ? args['inactive_minutes'] : undefined,
|
|
207
|
+
maxDepth: typeof args['max_depth'] === 'number' ? args['max_depth'] : DEFAULT_MAX_DEPTH,
|
|
208
|
+
host: optionalString(args['machine']) ?? LOCAL_HOST,
|
|
209
|
+
};
|
|
210
|
+
if (!optionalString(args['kind']))
|
|
211
|
+
throw new Error('agent_spawn needs a kind for a new child, or resume to message an earlier one.');
|
|
212
|
+
if (!options.name)
|
|
213
|
+
throw new Error('agent_spawn needs a name for a new child, or resume to message an earlier one.');
|
|
214
|
+
// Resolve the machine before anything is written, so a typo leaves no record.
|
|
215
|
+
const client = await clientFor(ctx, options.host ?? LOCAL_HOST);
|
|
216
|
+
const { child, link } = await spawnChild(client, record, options, undefined, { forget: (childId) => ctx.watcher.forget(childId) });
|
|
217
|
+
const where = child.host === LOCAL_HOST ? '' : ` on machine ${child.host}`;
|
|
218
|
+
const lines = [`${child.name} started as a ${child.kind} agent${where} in pane ${child.paneId}, tab ${child.tabId ?? child.paneId}.`, `Bellwether watches it, and your next turn starts when it changes state.`, `herdr link: ${link}`];
|
|
219
|
+
return lines.join('\n');
|
|
220
|
+
}
|
|
221
|
+
if (name === 'agent_adopt') {
|
|
222
|
+
const target = optionalString(args['target']);
|
|
223
|
+
if (!target)
|
|
224
|
+
throw new Error('agent_adopt needs a target: a pane id or a live agent name');
|
|
225
|
+
const host = optionalString(args['machine']) ?? LOCAL_HOST;
|
|
226
|
+
const client = await clientFor(ctx, host);
|
|
227
|
+
const { child, link, already } = await adoptPane(client, record, { target, host, name: optionalString(args['name']), stuckMinutes: typeof args['stuck_minutes'] === 'number' ? args['stuck_minutes'] : undefined });
|
|
228
|
+
if (already)
|
|
229
|
+
return `${child.name} in pane ${child.paneId} is already a child of this session.`;
|
|
230
|
+
const where = host === LOCAL_HOST ? '' : ` on machine ${host}`;
|
|
231
|
+
return [`Adopted ${child.name}, a ${child.kind} agent${where} in pane ${child.paneId}. Bellwether watches it from now on.`, 'It was not started by Bellwether, so it cannot call parent_report; its status changes still start your turns.', `herdr link: ${link}`].join('\n');
|
|
232
|
+
}
|
|
233
|
+
if (name === 'agent_list') {
|
|
234
|
+
if (!record.children.length)
|
|
235
|
+
return 'No children yet. Start one with agent_spawn.';
|
|
236
|
+
const header = 'name\tkind\tstate\tage\thost\tpane\tunread\tcwd';
|
|
237
|
+
return [header, ...record.children.map((child) => describeChild(child, ctx.watcher))].join('\n');
|
|
238
|
+
}
|
|
239
|
+
const target = optionalString(args['child']);
|
|
240
|
+
if (!target)
|
|
241
|
+
throw new Error(`${name} needs a child`);
|
|
242
|
+
const child = resolve(record, target);
|
|
243
|
+
if (!child)
|
|
244
|
+
throw new Error(`No child of this session matches "${target}". Call agent_list to see them.`);
|
|
245
|
+
// Pane ids are scoped to one herdr server, so every call goes to the child's host.
|
|
246
|
+
const herdr = await clientFor(ctx, hostOf(child));
|
|
247
|
+
if (name === 'agent_read') {
|
|
248
|
+
const lines = typeof args['lines'] === 'number' ? args['lines'] : undefined;
|
|
249
|
+
if (lines)
|
|
250
|
+
return (await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines })).trim();
|
|
251
|
+
if (child.transcript) {
|
|
252
|
+
try {
|
|
253
|
+
const content = fs.readFileSync(child.transcript, 'utf8');
|
|
254
|
+
const messages = content
|
|
255
|
+
.split('\n')
|
|
256
|
+
.filter(Boolean)
|
|
257
|
+
.map((line) => {
|
|
258
|
+
try {
|
|
259
|
+
return JSON.parse(line);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
})
|
|
265
|
+
.filter((entry) => entry !== undefined);
|
|
266
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
267
|
+
const entry = messages[index];
|
|
268
|
+
const message = entry['message'];
|
|
269
|
+
const role = entry['type'] === 'assistant' ? 'assistant' : typeof message === 'object' && message !== null ? message['role'] : undefined;
|
|
270
|
+
if (role !== 'assistant')
|
|
271
|
+
continue;
|
|
272
|
+
const body = typeof message === 'object' && message !== null ? message['content'] : entry['content'];
|
|
273
|
+
const text = typeof body === 'string' ? body : Array.isArray(body) ? body.map((part) => (typeof part === 'object' && part !== null && typeof part['text'] === 'string' ? String(part['text']) : '')).filter(Boolean).join('\n') : '';
|
|
274
|
+
if (text.trim())
|
|
275
|
+
return text;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// Fall through to the screen.
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return (await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 })).trim();
|
|
283
|
+
}
|
|
284
|
+
if (name === 'agent_send') {
|
|
285
|
+
const text = optionalString(args['text']);
|
|
286
|
+
const keys = Array.isArray(args['keys']) ? args['keys'] : undefined;
|
|
287
|
+
if (keys?.length) {
|
|
288
|
+
await herdr.sendKeys(child.paneId, keys);
|
|
289
|
+
return `Sent ${keys.join(' ')} to ${child.name}.`;
|
|
290
|
+
}
|
|
291
|
+
if (!text)
|
|
292
|
+
throw new Error('agent_send needs text or keys');
|
|
293
|
+
return promptChild(herdr, child, text);
|
|
294
|
+
}
|
|
295
|
+
if (name === 'agent_stop') {
|
|
296
|
+
if (!args['force'] && (child.lastStatus === 'working' || child.lastStatus === 'blocked')) {
|
|
297
|
+
const tail = await herdr.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 20 }).catch(() => '');
|
|
298
|
+
return `${child.name} is ${child.lastStatus}, so agent_stop refused to close it. Pass force to close it anyway.\n${tail.trim()}`;
|
|
299
|
+
}
|
|
300
|
+
if (child.tabId)
|
|
301
|
+
await herdr.tabClose(child.tabId);
|
|
302
|
+
else
|
|
303
|
+
await herdr.paneClose(child.paneId);
|
|
304
|
+
updateChild(ctx.parentId, child.id, (entry) => {
|
|
305
|
+
entry.exitedAt = new Date().toISOString();
|
|
306
|
+
});
|
|
307
|
+
removeChildFiles(child.id);
|
|
308
|
+
return `Closed ${child.name}.`;
|
|
309
|
+
}
|
|
310
|
+
throw new Error(`Bellwether has no tool named ${name}`);
|
|
311
|
+
}
|
|
312
|
+
export function hostEnv() {
|
|
313
|
+
return { host: os.hostname() };
|
|
314
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elecnix/bellwether",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
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
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -15,27 +15,28 @@
|
|
|
15
15
|
"node": ">=22.18"
|
|
16
16
|
},
|
|
17
17
|
"files": [
|
|
18
|
-
"
|
|
19
|
-
"src/"
|
|
18
|
+
"dist/"
|
|
20
19
|
],
|
|
21
20
|
"publishConfig": {
|
|
22
21
|
"access": "public"
|
|
23
22
|
},
|
|
24
23
|
"bin": {
|
|
25
|
-
"bellwether": "
|
|
26
|
-
"bellwether-mcp": "
|
|
24
|
+
"bellwether": "dist/cli.js",
|
|
25
|
+
"bellwether-mcp": "dist/integrations/claude/channel.js"
|
|
27
26
|
},
|
|
28
27
|
"pi": {
|
|
29
28
|
"extensions": [
|
|
30
|
-
"./
|
|
29
|
+
"./dist/integrations/pi/extension.js"
|
|
31
30
|
]
|
|
32
31
|
},
|
|
33
32
|
"scripts": {
|
|
33
|
+
"build": "rm -rf dist && tsgo -p tsconfig.build.json && chmod +x dist/cli.js dist/integrations/claude/channel.js",
|
|
34
|
+
"prepare": "npm run build",
|
|
34
35
|
"typecheck": "tsgo --noEmit -p .",
|
|
35
36
|
"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\"",
|
|
37
|
+
"test:unit": "node --test --import ./test/fixtures/isolation.ts --disable-warning=ExperimentalWarning \"test/unit/**/*.test.ts\"",
|
|
38
|
+
"test:integration": "node --test --test-concurrency=1 --import ./test/fixtures/isolation.ts --disable-warning=ExperimentalWarning \"test/integration/**/*.test.ts\"",
|
|
39
|
+
"test:lab": "node --test --test-concurrency=1 --import ./test/fixtures/isolation.ts --disable-warning=ExperimentalWarning \"test/lab/**/*.test.ts\"",
|
|
39
40
|
"doctor": "node --disable-warning=ExperimentalWarning src/cli.ts doctor"
|
|
40
41
|
},
|
|
41
42
|
"dependencies": {
|
package/bin/bellwether-mcp.js
DELETED
package/bin/bellwether.js
DELETED