@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
|
@@ -1,124 +0,0 @@
|
|
|
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.ts';
|
|
10
|
-
|
|
11
|
-
/** Claude Code's state root, which a lab overrides with CLAUDE_CONFIG_DIR. */
|
|
12
|
-
export function claudeConfigDir(): string {
|
|
13
|
-
return process.env['CLAUDE_CONFIG_DIR'] ?? path.join(os.homedir(), '.claude');
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function findTranscript(session: string, cwd?: string, configDir?: string): string | undefined {
|
|
17
|
-
const root = path.join(configDir ?? claudeConfigDir(), 'projects');
|
|
18
|
-
if (cwd) {
|
|
19
|
-
const direct = path.join(root, claudeProjectDir(cwd), `${session}.jsonl`);
|
|
20
|
-
if (fs.existsSync(direct)) return direct;
|
|
21
|
-
}
|
|
22
|
-
try {
|
|
23
|
-
for (const dir of fs.readdirSync(root)) {
|
|
24
|
-
const file = path.join(root, dir, `${session}.jsonl`);
|
|
25
|
-
if (fs.existsSync(file)) return file;
|
|
26
|
-
}
|
|
27
|
-
} catch {
|
|
28
|
-
// A missing projects directory is not an error: the scan simply waits.
|
|
29
|
-
}
|
|
30
|
-
return undefined;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** Read a byte range in pieces, so a long session log never sits in memory whole. */
|
|
34
|
-
function readRange(file: string, from: number, to: number): string {
|
|
35
|
-
const pieces: string[] = [];
|
|
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) break;
|
|
45
|
-
pieces.push(buffer.toString('utf8', 0, read));
|
|
46
|
-
at += read;
|
|
47
|
-
}
|
|
48
|
-
} finally {
|
|
49
|
-
fs.closeSync(fd);
|
|
50
|
-
}
|
|
51
|
-
return pieces.join('');
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Incremental reader over one transcript. The offset starts at the file size
|
|
56
|
-
* when the server connects, so only later bytes count: a receipt id from an
|
|
57
|
-
* earlier run of the same session must not mark a new entry read.
|
|
58
|
-
*/
|
|
59
|
-
export class ReceiptScan {
|
|
60
|
-
private readonly session: string;
|
|
61
|
-
private readonly cwd: string | undefined;
|
|
62
|
-
private readonly configDir: string | undefined;
|
|
63
|
-
private transcript: string | undefined;
|
|
64
|
-
private offset = 0;
|
|
65
|
-
|
|
66
|
-
constructor(session: string, cwd?: string, configDir?: string) {
|
|
67
|
-
this.session = session;
|
|
68
|
-
this.cwd = cwd;
|
|
69
|
-
this.configDir = configDir;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Anchor at the current end of the transcript, wherever it is. */
|
|
73
|
-
start(): void {
|
|
74
|
-
this.transcript = findTranscript(this.session, this.cwd, this.configDir);
|
|
75
|
-
if (!this.transcript) return;
|
|
76
|
-
try {
|
|
77
|
-
this.offset = fs.statSync(this.transcript).size;
|
|
78
|
-
} catch {
|
|
79
|
-
this.offset = 0;
|
|
80
|
-
}
|
|
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: Iterable<string>): Set<string> {
|
|
88
|
-
const found = new Set<string>();
|
|
89
|
-
const wanted = [...receipts];
|
|
90
|
-
if (!wanted.length) return found;
|
|
91
|
-
const file = this.transcript ?? findTranscript(this.session, this.cwd, this.configDir);
|
|
92
|
-
if (!file) return found;
|
|
93
|
-
let size: number;
|
|
94
|
-
try {
|
|
95
|
-
size = fs.statSync(file).size;
|
|
96
|
-
} catch {
|
|
97
|
-
return found;
|
|
98
|
-
}
|
|
99
|
-
if (size === 0) return found;
|
|
100
|
-
const content = readRange(file, 0, size);
|
|
101
|
-
for (const receipt of wanted) if (content.includes(receipt)) found.add(receipt);
|
|
102
|
-
return found;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** The receipt ids that reached the transcript since the last scan. */
|
|
106
|
-
scan(receipts: Iterable<string>): Set<string> {
|
|
107
|
-
const seen = new Set<string>();
|
|
108
|
-
const wanted = [...receipts];
|
|
109
|
-
if (!wanted.length) return seen;
|
|
110
|
-
this.transcript ??= findTranscript(this.session, this.cwd, this.configDir);
|
|
111
|
-
if (!this.transcript) return seen;
|
|
112
|
-
let size: number;
|
|
113
|
-
try {
|
|
114
|
-
size = fs.statSync(this.transcript).size;
|
|
115
|
-
} catch {
|
|
116
|
-
return seen;
|
|
117
|
-
}
|
|
118
|
-
if (size <= this.offset) return seen;
|
|
119
|
-
const added = readRange(this.transcript, this.offset, size);
|
|
120
|
-
this.offset = size;
|
|
121
|
-
for (const receipt of wanted) if (added.includes(receipt)) seen.add(receipt);
|
|
122
|
-
return seen;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
@@ -1,136 +0,0 @@
|
|
|
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.ts';
|
|
8
|
-
import { resolveSocketPath } from '../../core/herdr-client.ts';
|
|
9
|
-
import { hostName } from '../../core/spawn.ts';
|
|
10
|
-
import type { OutboxEntry } from '../../core/types.ts';
|
|
11
|
-
import { childTools, parentTools } from '../tools.ts';
|
|
12
|
-
|
|
13
|
-
// The parts of pi's ExtensionAPI this extension uses.
|
|
14
|
-
interface PiContext {
|
|
15
|
-
isIdle(): boolean;
|
|
16
|
-
sessionManager: { getSessionId(): string; getCwd(): string; getSessionName?(): string | undefined };
|
|
17
|
-
}
|
|
18
|
-
interface ToolResult {
|
|
19
|
-
content: { type: 'text'; text: string }[];
|
|
20
|
-
details: unknown;
|
|
21
|
-
}
|
|
22
|
-
interface PiApi {
|
|
23
|
-
on(event: 'session_start' | 'session_shutdown', handler: (event: unknown, ctx: PiContext) => void | Promise<void>): void;
|
|
24
|
-
on(event: 'context', handler: (event: { messages: unknown[] }, ctx: PiContext) => void | Promise<void>): void;
|
|
25
|
-
registerTool(tool: {
|
|
26
|
-
name: string;
|
|
27
|
-
label: string;
|
|
28
|
-
description: string;
|
|
29
|
-
parameters: unknown;
|
|
30
|
-
execute(id: string, params: Record<string, unknown>, signal: AbortSignal | undefined, onUpdate: unknown, ctx: PiContext): Promise<ToolResult>;
|
|
31
|
-
}): void;
|
|
32
|
-
sendMessage(message: { customType: string; content: string; display: boolean; details?: unknown }, options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' }): void;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const result = (text: string): ToolResult => ({ content: [{ type: 'text', text }], details: undefined });
|
|
36
|
-
|
|
37
|
-
/** How many Bellwether generations deep this session sits. */
|
|
38
|
-
function depthFromEnv(): number {
|
|
39
|
-
const value = Number.parseInt(process.env['BELLWETHER_DEPTH'] ?? '0', 10);
|
|
40
|
-
return Number.isFinite(value) ? value : 0;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** One message for a burst of events, so three children changing at once read once. */
|
|
44
|
-
function compose(entries: OutboxEntry[]): string {
|
|
45
|
-
if (!entries.length) return '';
|
|
46
|
-
const head = entries.length === 1 ? '[bellwether]' : `[bellwether] ${entries.length} children changed`;
|
|
47
|
-
const body = entries
|
|
48
|
-
.map((entry) => `${entry.name} (${entry.kind}, ${entry.paneId}) ${entry.event} — receipt ${entry.receipt}\n${entry.text}`)
|
|
49
|
-
.join('\n\n');
|
|
50
|
-
return `${head}\n${body}\n\nRead more with agent_read. Reply with agent_send.`;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export default function bellwether(pi: PiApi): void {
|
|
54
|
-
let daemon: DaemonClient | undefined;
|
|
55
|
-
let burst: NodeJS.Timeout | undefined;
|
|
56
|
-
let pending: OutboxEntry[] = [];
|
|
57
|
-
// Receipts this session has already put in front of the model.
|
|
58
|
-
const sent = new Set<string>();
|
|
59
|
-
|
|
60
|
-
const flush = (): void => {
|
|
61
|
-
burst = undefined;
|
|
62
|
-
if (!pending.length) return;
|
|
63
|
-
const batch = pending;
|
|
64
|
-
pending = [];
|
|
65
|
-
const text = compose(batch);
|
|
66
|
-
if (!text) return;
|
|
67
|
-
for (const entry of batch) sent.add(entry.receipt);
|
|
68
|
-
// The message waits until the agent has no tool calls left, then starts the turn.
|
|
69
|
-
pi.sendMessage({ customType: 'bellwether', content: text, display: true, details: { digest: 'child events' } }, { triggerTurn: true, deliverAs: 'followUp' });
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
const onEntries = (entries: OutboxEntry[]): void => {
|
|
73
|
-
const fresh = entries.filter((entry) => !sent.has(entry.receipt) && !entry.read);
|
|
74
|
-
if (!fresh.length) return;
|
|
75
|
-
pending = fresh;
|
|
76
|
-
if (burst) return;
|
|
77
|
-
burst = setTimeout(flush, 250);
|
|
78
|
-
burst.unref?.();
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
pi.on('session_start', async (_event, ctx) => {
|
|
82
|
-
try {
|
|
83
|
-
daemon = await DaemonClient.connect({
|
|
84
|
-
harness: 'pi',
|
|
85
|
-
session: ctx.sessionManager.getSessionId(),
|
|
86
|
-
cwd: ctx.sessionManager.getCwd(),
|
|
87
|
-
host: hostName() || os.hostname(),
|
|
88
|
-
paneId: process.env['HERDR_PANE_ID'],
|
|
89
|
-
workspaceId: process.env['HERDR_WORKSPACE_ID'],
|
|
90
|
-
depth: depthFromEnv(),
|
|
91
|
-
herdrSocket: resolveSocketPath(),
|
|
92
|
-
}, { log: (message) => console.error('[bellwether]', message) });
|
|
93
|
-
daemon.onEvents(onEntries);
|
|
94
|
-
const missed = await daemon.pending();
|
|
95
|
-
if (missed.length) onEntries(missed);
|
|
96
|
-
} catch (error) {
|
|
97
|
-
console.error('[bellwether] the daemon did not start:', (error as Error).message);
|
|
98
|
-
daemon = undefined;
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
pi.on('session_shutdown', () => {
|
|
103
|
-
if (burst) clearTimeout(burst);
|
|
104
|
-
burst = undefined;
|
|
105
|
-
pending = [];
|
|
106
|
-
void daemon?.close();
|
|
107
|
-
daemon = undefined;
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
// A receipt that reaches the model context marks its event read.
|
|
111
|
-
pi.on('context', (event) => {
|
|
112
|
-
if (!daemon) return;
|
|
113
|
-
const seen = JSON.stringify(event.messages);
|
|
114
|
-
const receipts = daemon.unread().filter((entry) => seen.includes(entry.receipt)).map((entry) => entry.receipt);
|
|
115
|
-
if (receipts.length) daemon.receipts(receipts);
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
const tools = process.env['BELLWETHER_PARENT'] ? [...parentTools, ...childTools] : parentTools;
|
|
119
|
-
for (const tool of tools) {
|
|
120
|
-
pi.registerTool({
|
|
121
|
-
name: tool.name,
|
|
122
|
-
label: tool.name.replace(/_/g, ' '),
|
|
123
|
-
description: tool.description,
|
|
124
|
-
parameters: tool.schema,
|
|
125
|
-
async execute(_id, args, signal) {
|
|
126
|
-
if (!daemon) return result('Bellwether is not running: the daemon did not start for this session.');
|
|
127
|
-
if (signal?.aborted) return result('Cancelled.');
|
|
128
|
-
try {
|
|
129
|
-
return result(await daemon.tool(tool.name, args));
|
|
130
|
-
} catch (error) {
|
|
131
|
-
return result((error as Error).message);
|
|
132
|
-
}
|
|
133
|
-
},
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
}
|
|
@@ -1,235 +0,0 @@
|
|
|
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 type { HerdrClient } from '../core/herdr-client.ts';
|
|
6
|
-
import { HerdrApiError } from '../core/herdr-client.ts';
|
|
7
|
-
import { AGENT_KINDS, DEFAULT_MAX_DEPTH, spawnChild, type SpawnOptions } from '../core/spawn.ts';
|
|
8
|
-
import { reportToParent } from '../core/report.ts';
|
|
9
|
-
import { childById, readParent, updateChild } from '../core/registry.ts';
|
|
10
|
-
import type { Watcher } from '../core/watcher.ts';
|
|
11
|
-
import type { ChildRecord, ReportStatus } from '../core/types.ts';
|
|
12
|
-
|
|
13
|
-
export interface ToolContext {
|
|
14
|
-
client: HerdrClient;
|
|
15
|
-
parentId: string;
|
|
16
|
-
watcher: Watcher;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface ToolDefinition {
|
|
20
|
-
name: string;
|
|
21
|
-
description: string;
|
|
22
|
-
schema: Record<string, unknown>;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const optionalString = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
|
|
26
|
-
|
|
27
|
-
/** The five tools any session gets. */
|
|
28
|
-
export const parentTools: ToolDefinition[] = [
|
|
29
|
-
{
|
|
30
|
-
name: 'agent_spawn',
|
|
31
|
-
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.',
|
|
32
|
-
schema: {
|
|
33
|
-
type: 'object',
|
|
34
|
-
properties: {
|
|
35
|
-
kind: { type: 'string', enum: [...AGENT_KINDS], description: 'The harness to start: pi, claude, codex, opencode or cline.' },
|
|
36
|
-
name: { type: 'string', description: 'A short handle for the child, unique in this session. Used as the herdr agent name and the tab label.' },
|
|
37
|
-
cwd: { type: 'string', description: 'The directory to start the child in. Use an absolute path, ideally a git worktree of its own.' },
|
|
38
|
-
prompt: { type: 'string', description: 'The first message the child receives. The whole prompt, not a path.' },
|
|
39
|
-
model: { type: 'string', description: 'The model or tier to pass to the child harness.' },
|
|
40
|
-
args: { type: 'array', items: { type: 'string' }, description: 'Extra arguments for the child harness, passed through unchanged and appended last.' },
|
|
41
|
-
focus: { type: 'boolean', description: 'Move your view to the new tab. Defaults to false, so the child does not steal focus.' },
|
|
42
|
-
stuck_minutes: { type: 'number', description: 'How long the child may be quiet before it counts as stuck. Defaults to 10.' },
|
|
43
|
-
max_depth: { type: 'number', description: 'How deep children may spawn children. Defaults to 2.' },
|
|
44
|
-
},
|
|
45
|
-
required: ['kind', 'name'],
|
|
46
|
-
},
|
|
47
|
-
},
|
|
48
|
-
{
|
|
49
|
-
name: 'agent_list',
|
|
50
|
-
description: 'List this session\'s children with status, age and unread events.',
|
|
51
|
-
schema: { type: 'object', properties: {} },
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
name: 'agent_read',
|
|
55
|
-
description: 'Read a child: its last assistant message by default, or its screen when you pass lines.',
|
|
56
|
-
schema: {
|
|
57
|
-
type: 'object',
|
|
58
|
-
properties: {
|
|
59
|
-
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
60
|
-
lines: { type: 'number', description: 'Read this many screen lines instead of the last message.' },
|
|
61
|
-
},
|
|
62
|
-
required: ['child'],
|
|
63
|
-
},
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
name: 'agent_send',
|
|
67
|
-
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.',
|
|
68
|
-
schema: {
|
|
69
|
-
type: 'object',
|
|
70
|
-
properties: {
|
|
71
|
-
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
72
|
-
text: { type: 'string', description: 'The prompt to submit.' },
|
|
73
|
-
keys: { type: 'array', items: { type: 'string' }, description: 'Key presses to send instead of a prompt, named as ctrl+c or enter.' },
|
|
74
|
-
},
|
|
75
|
-
required: ['child'],
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
{
|
|
79
|
-
name: 'agent_stop',
|
|
80
|
-
description: 'Close a child\'s tab, which ends it. Refuses a working child unless you pass force.',
|
|
81
|
-
schema: {
|
|
82
|
-
type: 'object',
|
|
83
|
-
properties: {
|
|
84
|
-
child: { type: 'string', description: 'The child\'s name, its pane id, or the id agent_spawn returned.' },
|
|
85
|
-
force: { type: 'boolean', description: 'Close the tab even while the child is working or blocked.' },
|
|
86
|
-
},
|
|
87
|
-
required: ['child'],
|
|
88
|
-
},
|
|
89
|
-
},
|
|
90
|
-
];
|
|
91
|
-
|
|
92
|
-
/** The one tool a child gets, when its environment names a parent. */
|
|
93
|
-
export const childTools: ToolDefinition[] = [
|
|
94
|
-
{
|
|
95
|
-
name: 'parent_report',
|
|
96
|
-
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.',
|
|
97
|
-
schema: {
|
|
98
|
-
type: 'object',
|
|
99
|
-
properties: {
|
|
100
|
-
status: { type: 'string', enum: ['done', 'needs-input', 'progress'], description: 'done finishes the task, needs-input asks a question, progress is a status note.' },
|
|
101
|
-
text: { type: 'string', description: 'What to tell the parent. For done, the result. For needs-input, the question and the options you weighed.' },
|
|
102
|
-
},
|
|
103
|
-
required: ['status', 'text'],
|
|
104
|
-
},
|
|
105
|
-
},
|
|
106
|
-
];
|
|
107
|
-
|
|
108
|
-
export function toolSchema(name: string): Record<string, unknown> | undefined {
|
|
109
|
-
return [...parentTools, ...childTools].find((tool) => tool.name === name)?.schema;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function resolve(record: ReturnType<typeof readParent>, child: string): ChildRecord | undefined {
|
|
113
|
-
return record ? childById(record, child) : undefined;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function describeChild(child: ChildRecord, watcher: Watcher): string {
|
|
117
|
-
const unread = watcher.outboxEntries().filter((entry) => !entry.read && entry.childId === child.id).length;
|
|
118
|
-
const age = Math.max(0, Math.round((Date.now() - Date.parse(child.startedAt)) / 1000));
|
|
119
|
-
const state = child.exitedAt ? `exited${child.exitCode === undefined ? '' : ` (${child.exitCode})`}` : child.lastStatus;
|
|
120
|
-
return `${child.name}\t${child.kind}\t${state}\t${age}s\t${child.paneId}\tunread ${unread}\t${child.cwd ?? ''}`;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export async function runBellwetherTool(ctx: ToolContext, name: string, args: Record<string, unknown>): Promise<string> {
|
|
124
|
-
const record = readParent(ctx.parentId);
|
|
125
|
-
if (!record) throw new Error(`No Bellwether registry for ${ctx.parentId}. Start a session with the Bellwether extension loaded.`);
|
|
126
|
-
|
|
127
|
-
if (name === 'parent_report') {
|
|
128
|
-
const status = optionalString(args['status']) as ReportStatus | undefined;
|
|
129
|
-
const text = optionalString(args['text']);
|
|
130
|
-
if (!status || !text) throw new Error('parent_report needs both status and text');
|
|
131
|
-
const written = reportToParent(status, text);
|
|
132
|
-
if (!written) throw new Error('This session has no BELLWETHER_PARENT, so there is nobody to report to.');
|
|
133
|
-
return `Reported ${status} to the parent.`;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (name === 'agent_spawn') {
|
|
137
|
-
const options: SpawnOptions = {
|
|
138
|
-
kind: optionalString(args['kind']) ?? 'pi',
|
|
139
|
-
name: optionalString(args['name']) ?? '',
|
|
140
|
-
cwd: optionalString(args['cwd']),
|
|
141
|
-
prompt: optionalString(args['prompt']),
|
|
142
|
-
model: optionalString(args['model']),
|
|
143
|
-
args: Array.isArray(args['args']) ? (args['args'] as string[]) : undefined,
|
|
144
|
-
focus: args['focus'] === true,
|
|
145
|
-
stuckMinutes: typeof args['stuck_minutes'] === 'number' ? (args['stuck_minutes'] as number) : undefined,
|
|
146
|
-
maxDepth: typeof args['max_depth'] === 'number' ? (args['max_depth'] as number) : DEFAULT_MAX_DEPTH,
|
|
147
|
-
};
|
|
148
|
-
if (!options.name) throw new Error('agent_spawn needs a name');
|
|
149
|
-
const { child, link } = await spawnChild(ctx.client, record, options);
|
|
150
|
-
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');
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
if (name === 'agent_list') {
|
|
154
|
-
if (!record.children.length) return 'No children yet. Start one with agent_spawn.';
|
|
155
|
-
const header = 'name\tkind\tstate\tage\tpane\tunread\tcwd';
|
|
156
|
-
return [header, ...record.children.map((child) => describeChild(child, ctx.watcher))].join('\n');
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
const target = optionalString(args['child']);
|
|
160
|
-
if (!target) throw new Error(`${name} needs a child`);
|
|
161
|
-
const child = resolve(record, target);
|
|
162
|
-
if (!child) throw new Error(`No child of this session matches "${target}". Call agent_list to see them.`);
|
|
163
|
-
|
|
164
|
-
if (name === 'agent_read') {
|
|
165
|
-
const lines = typeof args['lines'] === 'number' ? (args['lines'] as number) : undefined;
|
|
166
|
-
if (lines) return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines })).trim();
|
|
167
|
-
if (child.transcript) {
|
|
168
|
-
try {
|
|
169
|
-
const content = fs.readFileSync(child.transcript, 'utf8');
|
|
170
|
-
const messages = content
|
|
171
|
-
.split('\n')
|
|
172
|
-
.filter(Boolean)
|
|
173
|
-
.map((line) => {
|
|
174
|
-
try {
|
|
175
|
-
return JSON.parse(line) as Record<string, unknown>;
|
|
176
|
-
} catch {
|
|
177
|
-
return undefined;
|
|
178
|
-
}
|
|
179
|
-
})
|
|
180
|
-
.filter((entry): entry is Record<string, unknown> => entry !== undefined);
|
|
181
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
182
|
-
const entry = messages[index] as Record<string, unknown>;
|
|
183
|
-
const message = entry['message'];
|
|
184
|
-
const role = entry['type'] === 'assistant' ? 'assistant' : typeof message === 'object' && message !== null ? (message as Record<string, unknown>)['role'] : undefined;
|
|
185
|
-
if (role !== 'assistant') continue;
|
|
186
|
-
const body = typeof message === 'object' && message !== null ? (message as Record<string, unknown>)['content'] : entry['content'];
|
|
187
|
-
const text = typeof body === 'string' ? body : Array.isArray(body) ? body.map((part) => (typeof part === 'object' && part !== null && typeof (part as Record<string, unknown>)['text'] === 'string' ? String((part as Record<string, unknown>)['text']) : '')).filter(Boolean).join('\n') : '';
|
|
188
|
-
if (text.trim()) return text;
|
|
189
|
-
}
|
|
190
|
-
} catch {
|
|
191
|
-
// Fall through to the screen.
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
return (await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 })).trim();
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if (name === 'agent_send') {
|
|
198
|
-
const text = optionalString(args['text']);
|
|
199
|
-
const keys = Array.isArray(args['keys']) ? (args['keys'] as string[]) : undefined;
|
|
200
|
-
if (keys?.length) {
|
|
201
|
-
await ctx.client.sendKeys(child.paneId, keys);
|
|
202
|
-
return `Sent ${keys.join(' ')} to ${child.name}.`;
|
|
203
|
-
}
|
|
204
|
-
if (!text) throw new Error('agent_send needs text or keys');
|
|
205
|
-
try {
|
|
206
|
-
await ctx.client.agentPrompt(child.paneId, text);
|
|
207
|
-
return `Prompted ${child.name}.`;
|
|
208
|
-
} catch (error) {
|
|
209
|
-
if (error instanceof HerdrApiError && child.lastStatus === 'blocked') {
|
|
210
|
-
const dialog = await ctx.client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }).catch(() => '');
|
|
211
|
-
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"].`;
|
|
212
|
-
}
|
|
213
|
-
throw error;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
if (name === 'agent_stop') {
|
|
218
|
-
if (!args['force'] && (child.lastStatus === 'working' || child.lastStatus === 'blocked')) {
|
|
219
|
-
const tail = await ctx.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 20 }).catch(() => '');
|
|
220
|
-
return `${child.name} is ${child.lastStatus}, so agent_stop refused to close it. Pass force to close it anyway.\n${tail.trim()}`;
|
|
221
|
-
}
|
|
222
|
-
if (child.tabId) await ctx.client.tabClose(child.tabId);
|
|
223
|
-
else await ctx.client.paneClose(child.paneId);
|
|
224
|
-
updateChild(ctx.parentId, child.id, (entry) => {
|
|
225
|
-
entry.exitedAt = new Date().toISOString();
|
|
226
|
-
});
|
|
227
|
-
return `Closed ${child.name}.`;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
throw new Error(`Bellwether has no tool named ${name}`);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
export function hostEnv(): Record<string, string> {
|
|
234
|
-
return { host: os.hostname() };
|
|
235
|
-
}
|