@elecnix/bellwether 0.1.0 → 0.1.2
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 +2 -1
- package/dist/cli.js +295 -0
- package/dist/core/classifier.js +66 -0
- package/dist/core/herdr-client.js +368 -0
- package/dist/core/outbox.js +80 -0
- package/dist/core/paths.js +32 -0
- package/dist/core/registry.js +93 -0
- package/dist/core/report.js +50 -0
- package/dist/core/spawn.js +128 -0
- package/dist/core/transcript.js +79 -0
- package/dist/core/types.js +1 -0
- package/dist/core/watcher.js +593 -0
- package/dist/daemon/client.js +377 -0
- package/dist/daemon/lock.js +68 -0
- package/dist/daemon/main.js +34 -0
- package/dist/daemon/protocol.js +90 -0
- package/dist/daemon/server.js +244 -0
- package/dist/daemon/service.js +63 -0
- package/dist/integrations/claude/channel.js +245 -0
- package/dist/integrations/claude/transcript.js +135 -0
- package/dist/integrations/pi/extension.js +117 -0
- package/dist/integrations/tools.js +220 -0
- package/package.json +7 -6
- 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,117 @@
|
|
|
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 { childTools, parentTools } from '../tools.js';
|
|
11
|
+
const result = (text) => ({ content: [{ type: 'text', text }], details: undefined });
|
|
12
|
+
/** How many Bellwether generations deep this session sits. */
|
|
13
|
+
function depthFromEnv() {
|
|
14
|
+
const value = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10);
|
|
15
|
+
return Number.isFinite(value) ? value : 0;
|
|
16
|
+
}
|
|
17
|
+
/** One message for a burst of events, so three children changing at once read once. */
|
|
18
|
+
function compose(entries) {
|
|
19
|
+
if (!entries.length)
|
|
20
|
+
return '';
|
|
21
|
+
const head = entries.length === 1 ? '[bellwether]' : `[bellwether] ${entries.length} children changed`;
|
|
22
|
+
const body = entries
|
|
23
|
+
.map((entry) => `${entry.name} (${entry.kind}, ${entry.paneId}) ${entry.event} — receipt ${entry.receipt}\n${entry.text}`)
|
|
24
|
+
.join('\n\n');
|
|
25
|
+
return `${head}\n${body}\n\nRead more with agent_read. Reply with agent_send.`;
|
|
26
|
+
}
|
|
27
|
+
export default function bellwether(pi) {
|
|
28
|
+
let daemon;
|
|
29
|
+
let burst;
|
|
30
|
+
let pending = [];
|
|
31
|
+
// Receipts this session has already put in front of the model.
|
|
32
|
+
const sent = new Set();
|
|
33
|
+
const flush = () => {
|
|
34
|
+
burst = undefined;
|
|
35
|
+
if (!pending.length)
|
|
36
|
+
return;
|
|
37
|
+
const batch = pending;
|
|
38
|
+
pending = [];
|
|
39
|
+
const text = compose(batch);
|
|
40
|
+
if (!text)
|
|
41
|
+
return;
|
|
42
|
+
for (const entry of batch)
|
|
43
|
+
sent.add(entry.receipt);
|
|
44
|
+
// The message waits until the agent has no tool calls left, then starts the turn.
|
|
45
|
+
pi.sendMessage({ customType: 'bellwether', content: text, display: true, details: { digest: 'child events' } }, { triggerTurn: true, deliverAs: 'followUp' });
|
|
46
|
+
};
|
|
47
|
+
const onEntries = (entries) => {
|
|
48
|
+
const fresh = entries.filter((entry) => !sent.has(entry.receipt) && !entry.read);
|
|
49
|
+
if (!fresh.length)
|
|
50
|
+
return;
|
|
51
|
+
pending = fresh;
|
|
52
|
+
if (burst)
|
|
53
|
+
return;
|
|
54
|
+
burst = setTimeout(flush, 250);
|
|
55
|
+
burst.unref?.();
|
|
56
|
+
};
|
|
57
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
58
|
+
try {
|
|
59
|
+
daemon = await DaemonClient.connect({
|
|
60
|
+
harness: 'pi',
|
|
61
|
+
session: ctx.sessionManager.getSessionId(),
|
|
62
|
+
cwd: ctx.sessionManager.getCwd(),
|
|
63
|
+
host: hostName() || os.hostname(),
|
|
64
|
+
paneId: process.env['HERDR_PANE_ID'],
|
|
65
|
+
workspaceId: process.env['HERDR_WORKSPACE_ID'],
|
|
66
|
+
depth: depthFromEnv(),
|
|
67
|
+
herdrSocket: resolveSocketPath(),
|
|
68
|
+
}, { log: (message) => console.error('[bellwether]', message) });
|
|
69
|
+
daemon.onEvents(onEntries);
|
|
70
|
+
const missed = await daemon.pending();
|
|
71
|
+
if (missed.length)
|
|
72
|
+
onEntries(missed);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
console.error('[bellwether] the daemon did not start:', error.message);
|
|
76
|
+
daemon = undefined;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
pi.on('session_shutdown', () => {
|
|
80
|
+
if (burst)
|
|
81
|
+
clearTimeout(burst);
|
|
82
|
+
burst = undefined;
|
|
83
|
+
pending = [];
|
|
84
|
+
void daemon?.close();
|
|
85
|
+
daemon = undefined;
|
|
86
|
+
});
|
|
87
|
+
// A receipt that reaches the model context marks its event read.
|
|
88
|
+
pi.on('context', (event) => {
|
|
89
|
+
if (!daemon)
|
|
90
|
+
return;
|
|
91
|
+
const seen = JSON.stringify(event.messages);
|
|
92
|
+
const receipts = daemon.unread().filter((entry) => seen.includes(entry.receipt)).map((entry) => entry.receipt);
|
|
93
|
+
if (receipts.length)
|
|
94
|
+
daemon.receipts(receipts);
|
|
95
|
+
});
|
|
96
|
+
const tools = process.env['BELLWETHER_PARENT'] ? [...parentTools, ...childTools] : parentTools;
|
|
97
|
+
for (const tool of tools) {
|
|
98
|
+
pi.registerTool({
|
|
99
|
+
name: tool.name,
|
|
100
|
+
label: tool.name.replace(/_/g, ' '),
|
|
101
|
+
description: tool.description,
|
|
102
|
+
parameters: tool.schema,
|
|
103
|
+
async execute(_id, args, signal) {
|
|
104
|
+
if (!daemon)
|
|
105
|
+
return result('Bellwether is not running: the daemon did not start for this session.');
|
|
106
|
+
if (signal?.aborted)
|
|
107
|
+
return result('Cancelled.');
|
|
108
|
+
try {
|
|
109
|
+
return result(await daemon.tool(tool.name, args));
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
return result(error.message);
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// The six 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 { HerdrApiError } from '../core/herdr-client.js';
|
|
6
|
+
import { AGENT_KINDS, DEFAULT_MAX_DEPTH, spawnChild } from '../core/spawn.js';
|
|
7
|
+
import { reportToParent } from '../core/report.js';
|
|
8
|
+
import { childById, readParent, updateChild } from '../core/registry.js';
|
|
9
|
+
const optionalString = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
|
|
10
|
+
/** The five tools any session gets. */
|
|
11
|
+
export const parentTools = [
|
|
12
|
+
{
|
|
13
|
+
name: 'agent_spawn',
|
|
14
|
+
description: 'Start a child coding agent in its own herdr tab, of any kind herdr can start. Bellwether watches it and starts your next turn when it reports, goes idle, blocks, stalls or exits. Give the prompt a concrete deliverable, and tell the child to call parent_report when it is done.',
|
|
15
|
+
schema: {
|
|
16
|
+
type: 'object',
|
|
17
|
+
properties: {
|
|
18
|
+
kind: { type: 'string', enum: [...AGENT_KINDS], description: 'The harness to start: pi, claude, codex, opencode or cline.' },
|
|
19
|
+
name: { type: 'string', description: 'A short handle for the child, unique in this session. Used as the herdr agent name and the tab label.' },
|
|
20
|
+
cwd: { type: 'string', description: 'The directory to start the child in. Use an absolute path, ideally a git worktree of its own.' },
|
|
21
|
+
prompt: { type: 'string', description: 'The first message the child receives. The whole prompt, not a path.' },
|
|
22
|
+
model: { type: 'string', description: 'The model or tier to pass to the child harness.' },
|
|
23
|
+
args: { type: 'array', items: { type: 'string' }, description: 'Extra arguments for the child harness, passed through unchanged and appended last.' },
|
|
24
|
+
focus: { type: 'boolean', description: 'Move your view to the new tab. Defaults to false, so the child does not steal focus.' },
|
|
25
|
+
stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
|
|
26
|
+
max_depth: { type: 'number', description: 'How deep children may spawn children. Defaults to 2.' },
|
|
27
|
+
},
|
|
28
|
+
required: ['kind', 'name'],
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: 'agent_list',
|
|
33
|
+
description: 'List this session\'s children with status, age and unread events.',
|
|
34
|
+
schema: { type: 'object', properties: {} },
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'agent_read',
|
|
38
|
+
description: 'Read a child: its last assistant message by default, or its screen when you pass lines.',
|
|
39
|
+
schema: {
|
|
40
|
+
type: 'object',
|
|
41
|
+
properties: {
|
|
42
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
43
|
+
lines: { type: 'number', description: 'Read this many screen lines instead of the last message.' },
|
|
44
|
+
},
|
|
45
|
+
required: ['child'],
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: 'agent_send',
|
|
50
|
+
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.',
|
|
51
|
+
schema: {
|
|
52
|
+
type: 'object',
|
|
53
|
+
properties: {
|
|
54
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
55
|
+
text: { type: 'string', description: 'The prompt to submit.' },
|
|
56
|
+
keys: { type: 'array', items: { type: 'string' }, description: 'Key presses to send instead of a prompt, named as ctrl+c or enter.' },
|
|
57
|
+
},
|
|
58
|
+
required: ['child'],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'agent_stop',
|
|
63
|
+
description: 'Close a child\'s tab, which ends it. Refuses a working child unless you pass force.',
|
|
64
|
+
schema: {
|
|
65
|
+
type: 'object',
|
|
66
|
+
properties: {
|
|
67
|
+
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
68
|
+
force: { type: 'boolean', description: 'Close the tab even while the child is working or blocked.' },
|
|
69
|
+
},
|
|
70
|
+
required: ['child'],
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
];
|
|
74
|
+
/** The one tool a child gets, when its environment names a parent. */
|
|
75
|
+
export const childTools = [
|
|
76
|
+
{
|
|
77
|
+
name: 'parent_report',
|
|
78
|
+
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.',
|
|
79
|
+
schema: {
|
|
80
|
+
type: 'object',
|
|
81
|
+
properties: {
|
|
82
|
+
status: { type: 'string', enum: ['done', 'needs-input', 'progress'], description: 'done finishes the task, needs-input asks a question, progress is a status note.' },
|
|
83
|
+
text: { type: 'string', description: 'What to tell the parent. For done, the result. For needs-input, the question and the options you weighed.' },
|
|
84
|
+
},
|
|
85
|
+
required: ['status', 'text'],
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
];
|
|
89
|
+
export function toolSchema(name) {
|
|
90
|
+
return [...parentTools, ...childTools].find((tool) => tool.name === name)?.schema;
|
|
91
|
+
}
|
|
92
|
+
function resolve(record, child) {
|
|
93
|
+
return record ? childById(record, child) : undefined;
|
|
94
|
+
}
|
|
95
|
+
function describeChild(child, watcher) {
|
|
96
|
+
const unread = watcher.outboxEntries().filter((entry) => !entry.read && entry.childId === child.id).length;
|
|
97
|
+
const age = Math.max(0, Math.round((Date.now() - Date.parse(child.startedAt)) / 1000));
|
|
98
|
+
const state = child.exitedAt ? `exited${child.exitCode === undefined ? '' : ` (${child.exitCode})`}` : child.lastStatus;
|
|
99
|
+
return `${child.name}\t${child.kind}\t${state}\t${age}s\t${child.paneId}\tunread ${unread}\t${child.cwd ?? ''}`;
|
|
100
|
+
}
|
|
101
|
+
export async function runBellwetherTool(ctx, name, args) {
|
|
102
|
+
const record = readParent(ctx.parentId);
|
|
103
|
+
if (!record)
|
|
104
|
+
throw new Error(`No Bellwether registry for ${ctx.parentId}. Start a session with the Bellwether extension loaded.`);
|
|
105
|
+
if (name === 'parent_report') {
|
|
106
|
+
const status = optionalString(args['status']);
|
|
107
|
+
const text = optionalString(args['text']);
|
|
108
|
+
if (!status || !text)
|
|
109
|
+
throw new Error('parent_report needs both status and text');
|
|
110
|
+
const written = reportToParent(status, text);
|
|
111
|
+
if (!written)
|
|
112
|
+
throw new Error('This session has no BELLWETHER_PARENT, so there is nobody to report to.');
|
|
113
|
+
return `Reported ${status} to the parent.`;
|
|
114
|
+
}
|
|
115
|
+
if (name === 'agent_spawn') {
|
|
116
|
+
const options = {
|
|
117
|
+
kind: optionalString(args['kind']) ?? 'pi',
|
|
118
|
+
name: optionalString(args['name']) ?? '',
|
|
119
|
+
cwd: optionalString(args['cwd']),
|
|
120
|
+
prompt: optionalString(args['prompt']),
|
|
121
|
+
model: optionalString(args['model']),
|
|
122
|
+
args: Array.isArray(args['args']) ? args['args'] : undefined,
|
|
123
|
+
focus: args['focus'] === true,
|
|
124
|
+
stuckMinutes: typeof args['stuck_minutes'] === 'number' ? args['stuck_minutes'] : undefined,
|
|
125
|
+
maxDepth: typeof args['max_depth'] === 'number' ? args['max_depth'] : DEFAULT_MAX_DEPTH,
|
|
126
|
+
};
|
|
127
|
+
if (!options.name)
|
|
128
|
+
throw new Error('agent_spawn needs a name');
|
|
129
|
+
const { child, link } = await spawnChild(ctx.client, record, options);
|
|
130
|
+
return [`${child.name} started as a ${child.kind} agent in pane ${child.paneId}, tab ${child.tabId ?? child.paneId}.`, `Bellwether watches it, and your next turn starts when it changes state.`, `herdr link: ${link}`].join('\n');
|
|
131
|
+
}
|
|
132
|
+
if (name === 'agent_list') {
|
|
133
|
+
if (!record.children.length)
|
|
134
|
+
return 'No children yet. Start one with agent_spawn.';
|
|
135
|
+
const header = 'name\tkind\tstate\tage\tpane\tunread\tcwd';
|
|
136
|
+
return [header, ...record.children.map((child) => describeChild(child, ctx.watcher))].join('\n');
|
|
137
|
+
}
|
|
138
|
+
const target = optionalString(args['child']);
|
|
139
|
+
if (!target)
|
|
140
|
+
throw new Error(`${name} needs a child`);
|
|
141
|
+
const child = resolve(record, target);
|
|
142
|
+
if (!child)
|
|
143
|
+
throw new Error(`No child of this session matches "${target}". Call agent_list to see them.`);
|
|
144
|
+
if (name === 'agent_read') {
|
|
145
|
+
const lines = typeof args['lines'] === 'number' ? args['lines'] : undefined;
|
|
146
|
+
if (lines)
|
|
147
|
+
return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines })).trim();
|
|
148
|
+
if (child.transcript) {
|
|
149
|
+
try {
|
|
150
|
+
const content = fs.readFileSync(child.transcript, 'utf8');
|
|
151
|
+
const messages = content
|
|
152
|
+
.split('\n')
|
|
153
|
+
.filter(Boolean)
|
|
154
|
+
.map((line) => {
|
|
155
|
+
try {
|
|
156
|
+
return JSON.parse(line);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
})
|
|
162
|
+
.filter((entry) => entry !== undefined);
|
|
163
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
164
|
+
const entry = messages[index];
|
|
165
|
+
const message = entry['message'];
|
|
166
|
+
const role = entry['type'] === 'assistant' ? 'assistant' : typeof message === 'object' && message !== null ? message['role'] : undefined;
|
|
167
|
+
if (role !== 'assistant')
|
|
168
|
+
continue;
|
|
169
|
+
const body = typeof message === 'object' && message !== null ? message['content'] : entry['content'];
|
|
170
|
+
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') : '';
|
|
171
|
+
if (text.trim())
|
|
172
|
+
return text;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// Fall through to the screen.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 })).trim();
|
|
180
|
+
}
|
|
181
|
+
if (name === 'agent_send') {
|
|
182
|
+
const text = optionalString(args['text']);
|
|
183
|
+
const keys = Array.isArray(args['keys']) ? args['keys'] : undefined;
|
|
184
|
+
if (keys?.length) {
|
|
185
|
+
await ctx.client.sendKeys(child.paneId, keys);
|
|
186
|
+
return `Sent ${keys.join(' ')} to ${child.name}.`;
|
|
187
|
+
}
|
|
188
|
+
if (!text)
|
|
189
|
+
throw new Error('agent_send needs text or keys');
|
|
190
|
+
try {
|
|
191
|
+
await ctx.client.agentPrompt(child.paneId, text);
|
|
192
|
+
return `Prompted ${child.name}.`;
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error instanceof HerdrApiError && child.lastStatus === 'blocked') {
|
|
196
|
+
const dialog = await ctx.client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }).catch(() => '');
|
|
197
|
+
return `herdr refused the prompt because ${child.name} is blocked. The dialog:\n${dialog.trim()}\n\nReply with agent_send keys, for example ["enter"] or ["down","enter"].`;
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (name === 'agent_stop') {
|
|
203
|
+
if (!args['force'] && (child.lastStatus === 'working' || child.lastStatus === 'blocked')) {
|
|
204
|
+
const tail = await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 20 }).catch(() => '');
|
|
205
|
+
return `${child.name} is ${child.lastStatus}, so agent_stop refused to close it. Pass force to close it anyway.\n${tail.trim()}`;
|
|
206
|
+
}
|
|
207
|
+
if (child.tabId)
|
|
208
|
+
await ctx.client.tabClose(child.tabId);
|
|
209
|
+
else
|
|
210
|
+
await ctx.client.paneClose(child.paneId);
|
|
211
|
+
updateChild(ctx.parentId, child.id, (entry) => {
|
|
212
|
+
entry.exitedAt = new Date().toISOString();
|
|
213
|
+
});
|
|
214
|
+
return `Closed ${child.name}.`;
|
|
215
|
+
}
|
|
216
|
+
throw new Error(`Bellwether has no tool named ${name}`);
|
|
217
|
+
}
|
|
218
|
+
export function hostEnv() {
|
|
219
|
+
return { host: os.hostname() };
|
|
220
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elecnix/bellwether",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
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,22 +15,23 @@
|
|
|
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
37
|
"test:unit": "node --test --disable-warning=ExperimentalWarning \"test/unit/**/*.test.ts\"",
|
package/bin/bellwether-mcp.js
DELETED
package/bin/bellwether.js
DELETED
package/src/cli.ts
DELETED
|
@@ -1,293 +0,0 @@
|
|
|
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();
|