@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.
Files changed (58) hide show
  1. package/README.md +58 -7
  2. package/dist/cli.js +296 -0
  3. package/dist/core/adopt.js +59 -0
  4. package/dist/core/brief.js +61 -0
  5. package/dist/core/child-lock.js +84 -0
  6. package/dist/core/classifier.js +100 -0
  7. package/dist/core/herdr-client.js +382 -0
  8. package/dist/core/inactivity.js +31 -0
  9. package/dist/core/label.js +7 -0
  10. package/dist/core/machine.js +134 -0
  11. package/dist/core/mcp-config.js +47 -0
  12. package/dist/core/outbox.js +145 -0
  13. package/dist/core/paths.js +46 -0
  14. package/dist/core/registry.js +129 -0
  15. package/dist/core/report.js +95 -0
  16. package/dist/core/resume.js +210 -0
  17. package/dist/core/retire.js +416 -0
  18. package/dist/core/send.js +17 -0
  19. package/dist/core/spawn-resume.js +96 -0
  20. package/dist/core/spawn.js +226 -0
  21. package/dist/core/startup-dialogs.js +120 -0
  22. package/dist/core/transcript.js +87 -0
  23. package/dist/core/types.js +2 -0
  24. package/dist/core/watcher.js +821 -0
  25. package/dist/daemon/client.js +459 -0
  26. package/dist/daemon/lock.js +68 -0
  27. package/dist/daemon/main.js +40 -0
  28. package/dist/daemon/protocol.js +104 -0
  29. package/dist/daemon/server.js +244 -0
  30. package/dist/daemon/service.js +67 -0
  31. package/dist/integrations/claude/channel.js +257 -0
  32. package/dist/integrations/claude/transcript.js +135 -0
  33. package/dist/integrations/pi/extension.js +119 -0
  34. package/dist/integrations/tools.js +314 -0
  35. package/package.json +10 -9
  36. package/bin/bellwether-mcp.js +0 -4
  37. package/bin/bellwether.js +0 -2
  38. package/src/cli.ts +0 -293
  39. package/src/core/classifier.ts +0 -108
  40. package/src/core/herdr-client.ts +0 -410
  41. package/src/core/outbox.ts +0 -89
  42. package/src/core/paths.ts +0 -41
  43. package/src/core/registry.ts +0 -96
  44. package/src/core/report.ts +0 -54
  45. package/src/core/spawn.ts +0 -159
  46. package/src/core/transcript.ts +0 -74
  47. package/src/core/types.ts +0 -95
  48. package/src/core/watcher.ts +0 -590
  49. package/src/daemon/client.ts +0 -383
  50. package/src/daemon/lock.ts +0 -72
  51. package/src/daemon/main.ts +0 -38
  52. package/src/daemon/protocol.ts +0 -184
  53. package/src/daemon/server.ts +0 -275
  54. package/src/daemon/service.ts +0 -80
  55. package/src/integrations/claude/channel.ts +0 -247
  56. package/src/integrations/claude/transcript.ts +0 -124
  57. package/src/integrations/pi/extension.ts +0 -136
  58. package/src/integrations/tools.ts +0 -235
package/src/core/spawn.ts DELETED
@@ -1,159 +0,0 @@
1
- // Starting a child. The order follows the design: write the registry record
2
- // first, then create the tab with the Bellwether environment, then ask herdr
3
- // to start the harness in the tab's root pane, then watch the new pane.
4
- import os from 'node:os';
5
- import { HerdrApiError, type HerdrClient } from './herdr-client.ts';
6
- import { newChildId } from './outbox.ts';
7
- import { updateChild, upsertChild } from './registry.ts';
8
- import { resolveTranscript } from './transcript.ts';
9
- import type { ChildRecord, Harness, ParentRecord } from './types.ts';
10
-
11
- /** How deep a Bellwether child may spawn. The design starts at 2. */
12
- export const DEFAULT_MAX_DEPTH = 2;
13
-
14
- export const AGENT_KINDS = ['pi', 'claude', 'codex', 'opencode', 'cline'] as const;
15
- export type AgentKind = (typeof AGENT_KINDS)[number];
16
-
17
- export function harnessOf(kind: string): Harness | 'other' {
18
- if (kind === 'pi') return 'pi';
19
- if (kind === 'claude') return 'claude-code';
20
- return 'other';
21
- }
22
-
23
- export interface SpawnOptions {
24
- kind: string;
25
- name: string;
26
- cwd?: string;
27
- prompt?: string;
28
- model?: string;
29
- args?: string[];
30
- focus?: boolean;
31
- /** Minutes of quiet before the child counts as stuck. */
32
- stuckMinutes?: number;
33
- /** The workspace to open the tab in. Defaults to the parent's own. */
34
- workspaceId?: string;
35
- /** How deep a child may itself spawn. */
36
- maxDepth?: number;
37
- }
38
-
39
- export interface SpawnResult {
40
- child: ChildRecord;
41
- link: string;
42
- }
43
-
44
- /** The extra arguments a child harness needs to load Bellwether itself. */
45
- export function childArgs(kind: string, options: SpawnOptions): string[] {
46
- const args: string[] = [];
47
- if (options.model) args.push('--model', options.model);
48
- // Claude Code reads this flag as a list and keeps taking values until the
49
- // next flag, so the two-argument form swallowed the prompt that follows it.
50
- // The equals form pins the flag to one value.
51
- if (kind === 'claude') args.push('--dangerously-load-development-channels=server:bellwether');
52
- if (options.prompt) args.push(options.prompt);
53
- if (options.args?.length) args.push(...options.args);
54
- return args;
55
- }
56
-
57
- export async function spawnChild(client: HerdrClient, parent: ParentRecord, options: SpawnOptions, signal?: AbortSignal): Promise<SpawnResult> {
58
- const depth = parent.depth + 1;
59
- const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
60
- if (depth > maxDepth) throw new Error(`Bellwether is ${maxDepth} levels deep already, so ${options.name} would go one level too far. Raise max_depth on the spawn if that is what you want.`);
61
-
62
- const now = new Date().toISOString();
63
- const child: ChildRecord = {
64
- id: newChildId(),
65
- name: options.name,
66
- kind: options.kind,
67
- harness: harnessOf(options.kind),
68
- paneId: '',
69
- cwd: options.cwd,
70
- startedAt: now,
71
- lastStatus: 'unknown',
72
- statusChangedAt: now,
73
- lastBusyAt: now,
74
- depth,
75
- stuckMs: options.stuckMinutes === undefined ? undefined : Math.max(1_000, Math.round(options.stuckMinutes * 60_000)),
76
- };
77
- // 1. The record lands before herdr is asked for anything.
78
- upsertChild(parent.id, child);
79
-
80
- // 2. The tab carries the environment the child needs to find its parent.
81
- const env: Record<string, string> = {
82
- BELLWETHER_PARENT: parent.id,
83
- BELLWETHER_CHILD: child.id,
84
- BELLWETHER_CHILD_NAME: child.name,
85
- BELLWETHER_DEPTH: String(depth),
86
- BELLWETHER_HARNESS: child.harness,
87
- };
88
- const tab = await client.tabCreate({ workspaceId: options.workspaceId ?? parent.workspaceId, cwd: options.cwd, label: child.name, env, focus: options.focus ?? false }, signal);
89
- if (!tab.paneId) throw new Error('herdr created no pane for the child tab');
90
-
91
- child.tabId = tab.tabId;
92
- child.paneId = tab.paneId;
93
- child.workspaceId = options.workspaceId ?? parent.workspaceId;
94
- upsertChild(parent.id, child);
95
-
96
- // 3. Start the harness in the tab's root pane. A tab answers tab.create
97
- // before its shell is at a prompt, so herdr refuses the start with
98
- // agent_pane_busy until the shell is ready.
99
- try {
100
- await startWithRetry(client, { name: child.name, kind: options.kind, paneId: tab.paneId, args: childArgs(options.kind, options) }, signal);
101
- } catch (error) {
102
- await client.tabClose(tab.tabId ?? tab.paneId).catch(() => {});
103
- throw error;
104
- }
105
-
106
- // 4. Resolve the transcript, then hand back the child and its herdr link.
107
- // The registry is re-read rather than written from the caller's copy, which
108
- // would erase the child record that upsertChild just added.
109
- await new Promise((resolve) => setTimeout(resolve, 750));
110
- try {
111
- const panes = await client.agentList(signal);
112
- const pane = panes.find((entry) => entry.paneId === child.paneId);
113
- if (pane) {
114
- child.transcript = resolveTranscript(child.harness, pane.agentSessionId, child.cwd);
115
- child.lastStatus = pane.agentStatus;
116
- updateChild(parent.id, child.id, (entry) => {
117
- entry.transcript = child.transcript;
118
- entry.lastStatus = child.lastStatus;
119
- });
120
- }
121
- } catch {
122
- // A missed session id only costs the transcript-based summary.
123
- }
124
-
125
- return { child, link: herdrLink('pane', child.paneId) };
126
- }
127
-
128
- /** herdr refuses a start until the new tab's shell reaches its prompt. */
129
- const PANE_NOT_READY = new Set(['agent_pane_busy', 'agent_pane_not_ready', 'pane_busy']);
130
-
131
- export async function startWithRetry(
132
- client: HerdrClient,
133
- params: { name: string; kind: string; paneId: string; args: string[]; timeoutMs?: number },
134
- signal?: AbortSignal,
135
- totalMs = 60_000,
136
- ): Promise<void> {
137
- const deadline = Date.now() + totalMs;
138
- let delay = 400;
139
- for (;;) {
140
- try {
141
- await client.agentStart(params, signal);
142
- return;
143
- } catch (error) {
144
- const code = error instanceof HerdrApiError ? error.code : undefined;
145
- if (!code || !PANE_NOT_READY.has(code) || Date.now() > deadline) throw error;
146
- await new Promise((resolve) => setTimeout(resolve, delay));
147
- delay = Math.min(delay * 2, 4_000);
148
- }
149
- }
150
- }
151
-
152
- export function herdrLink(kind: 'pane' | 'tab' | 'workspace' | 'agent', id: string): string {
153
- const fingerprint = process.env['HERDR_ENV'] === '1' ? '' : '';
154
- return `https://herdr.invalid/v1/${fingerprint}${kind}/${id}`;
155
- }
156
-
157
- export function hostName(): string {
158
- return os.hostname();
159
- }
@@ -1,74 +0,0 @@
1
- // Finding a child's transcript. The watcher reads the last assistant message
2
- // from it, which is where a finished child's answer already sits.
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
-
7
- /** Claude Code replaces every non-alphanumeric character of the cwd with a dash. */
8
- export function claudeProjectDir(cwd: string): string {
9
- return cwd.replace(/[^A-Za-z0-9]/g, '-');
10
- }
11
-
12
- function newestFile(dir: string, matches: (name: string) => boolean, depth = 3): string | undefined {
13
- let best: { file: string; mtime: number } | undefined;
14
- const walk = (current: string, remaining: number): void => {
15
- let entries: fs.Dirent[];
16
- try {
17
- entries = fs.readdirSync(current, { withFileTypes: true });
18
- } catch {
19
- return;
20
- }
21
- for (const entry of entries) {
22
- const full = path.join(current, entry.name);
23
- if (entry.isDirectory() && remaining > 0) walk(full, remaining - 1);
24
- else if (entry.isFile() && matches(entry.name)) {
25
- try {
26
- const mtime = fs.statSync(full).mtimeMs;
27
- if (!best || mtime > best.mtime) best = { file: full, mtime };
28
- } catch {
29
- // A transcript that vanished is not an error here.
30
- }
31
- }
32
- }
33
- };
34
- walk(dir, depth);
35
- return best?.file;
36
- }
37
-
38
- /** Pi names a session file `<timestamp>_<session id>.jsonl`. */
39
- const endsWith = (name: string) => (sessionId: string): boolean => name.endsWith(`${sessionId}.jsonl`);
40
-
41
- /**
42
- * Locate the transcript for a harness session. Pi and Claude Code both keep
43
- * one JSONL file per session, named after the session id, under a per-project
44
- * directory.
45
- */
46
- export function resolveTranscript(harness: string, sessionId: string | undefined, cwd: string | undefined): string | undefined {
47
- if (!sessionId) return undefined;
48
- // Pi reports its session as a path, Claude Code as an id. Take a path as one.
49
- if (sessionId.includes('/') || sessionId.endsWith('.jsonl')) return fs.existsSync(sessionId) ? sessionId : undefined;
50
- const home = os.homedir();
51
- if (harness === 'claude-code') {
52
- const root = path.join(home, '.claude', 'projects');
53
- const direct = cwd ? path.join(root, claudeProjectDir(cwd), `${sessionId}.jsonl`) : undefined;
54
- if (direct && fs.existsSync(direct)) return direct;
55
- return newestFile(root, endsWith(sessionId));
56
- }
57
- if (harness === 'pi') {
58
- const root = process.env['PI_CODING_AGENT_DIR'] ?? path.join(home, '.pi', 'agent');
59
- return newestFile(path.join(root, 'sessions'), endsWith(sessionId));
60
- }
61
- return undefined;
62
- }
63
-
64
- /** The session value herdr reports for a pane, whatever shape it takes. */
65
- export function sessionValueFrom(agentSession: unknown): string | undefined {
66
- if (typeof agentSession === 'string') return agentSession;
67
- if (typeof agentSession === 'object' && agentSession !== null) {
68
- const value = (agentSession as Record<string, unknown>)['value'];
69
- if (typeof value === 'string' && value.length > 0) return value;
70
- const id = (agentSession as Record<string, unknown>)['id'];
71
- if (typeof id === 'string' && id.length > 0) return id;
72
- }
73
- return undefined;
74
- }
package/src/core/types.ts DELETED
@@ -1,95 +0,0 @@
1
- /** The lifecycle states herdr reports for an agent in a pane. */
2
- export type AgentStatus = 'idle' | 'working' | 'blocked' | 'done' | 'unknown';
3
-
4
- /** What the parent is told about a child. */
5
- export type ChildEventKind = 'report' | 'idle' | 'blocked' | 'stuck' | 'exited';
6
-
7
- /** The three things a child can report through parent_report. */
8
- export type ReportStatus = 'done' | 'needs-input' | 'progress';
9
-
10
- /** The harnesses Bellwether has an adapter for. */
11
- export type Harness = 'pi' | 'claude-code';
12
-
13
- /**
14
- * One child of a parent session. The record is written before herdr creates
15
- * anything, so a crash still leaves a trace of what was asked for.
16
- */
17
- export interface ChildRecord {
18
- id: string;
19
- name: string;
20
- /** The herdr agent kind: pi, claude, codex, opencode or cline. */
21
- kind: string;
22
- harness: Harness | 'other';
23
- paneId: string;
24
- tabId?: string;
25
- workspaceId?: string;
26
- cwd?: string;
27
- startedAt: string;
28
- /** The last status herdr reported for the pane. */
29
- lastStatus: AgentStatus;
30
- /** Set when the status last changed, for the settle time. */
31
- statusChangedAt: string;
32
- /** herdr's completion_seq for the last finished turn. */
33
- completionSeq?: number;
34
- /** The child's transcript file, when its harness keeps one. */
35
- transcript?: string;
36
- /** How many Bellwether generations deep this child is. */
37
- depth: number;
38
- /** The last report the child sent, and when. */
39
- lastReport?: { status: ReportStatus; text: string; at: string; seq: number };
40
- /**
41
- * Set when a report arrives and cleared when the turn it covered ends, so a
42
- * child that reported does not also produce an idle event for the same turn.
43
- */
44
- reportPending?: boolean;
45
- /** The last time the child's transcript or screen moved. */
46
- lastBusyAt: string;
47
- /** This child's own stuck threshold, when its spawn set one. */
48
- stuckMs?: number;
49
- /** Set once the child is gone, so its events stop. */
50
- exitedAt?: string;
51
- exitCode?: number;
52
- }
53
-
54
- /** One parent session, and the children it started. */
55
- export interface ParentRecord {
56
- id: string;
57
- harness: Harness;
58
- session: string;
59
- host: string;
60
- cwd: string;
61
- paneId?: string;
62
- workspaceId?: string;
63
- depth: number;
64
- children: ChildRecord[];
65
- /** How far into the child spool this parent has read, so a restart resumes. */
66
- spoolOffset?: number;
67
- updatedAt: string;
68
- }
69
-
70
- /** One pending message for the parent, keyed by child until it is delivered. */
71
- export interface OutboxEntry {
72
- receipt: string;
73
- childId: string;
74
- name: string;
75
- kind: string;
76
- paneId: string;
77
- event: ChildEventKind;
78
- text: string;
79
- at: string;
80
- deliveredAt?: string;
81
- read: boolean;
82
- }
83
-
84
- /** One report a child wrote to its parent's spool file. */
85
- export interface SpoolReport {
86
- parentId: string;
87
- parentPaneId?: string;
88
- childId?: string;
89
- childName: string;
90
- paneId?: string;
91
- status: ReportStatus;
92
- text: string;
93
- at: string;
94
- seq: number;
95
- }