@elecnix/bellwether 0.0.0-stage → 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.
@@ -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,49 @@
1
1
  {
2
2
  "name": "@elecnix/bellwether",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
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
+ "dist/"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "bin": {
24
+ "bellwether": "dist/cli.js",
25
+ "bellwether-mcp": "dist/integrations/claude/channel.js"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./dist/integrations/pi/extension.js"
30
+ ]
31
+ },
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",
35
+ "typecheck": "tsgo --noEmit -p .",
36
+ "test": "npm run test:unit && npm run test:integration && npm run test:lab",
37
+ "test:unit": "node --test --disable-warning=ExperimentalWarning \"test/unit/**/*.test.ts\"",
38
+ "test:integration": "node --test --test-concurrency=1 --disable-warning=ExperimentalWarning \"test/integration/**/*.test.ts\"",
39
+ "test:lab": "node --test --test-concurrency=1 --disable-warning=ExperimentalWarning \"test/lab/**/*.test.ts\"",
40
+ "doctor": "node --disable-warning=ExperimentalWarning src/cli.ts doctor"
41
+ },
42
+ "dependencies": {
43
+ "@modelcontextprotocol/sdk": "1.32.2"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "22.20.5",
47
+ "@typescript/native-preview": "7.0.0-dev.20260707.2"
48
+ }
49
+ }