@elecnix/bellwether 0.1.0 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -7
- package/dist/cli.js +296 -0
- package/dist/core/adopt.js +59 -0
- package/dist/core/brief.js +61 -0
- package/dist/core/child-lock.js +84 -0
- package/dist/core/classifier.js +100 -0
- package/dist/core/herdr-client.js +382 -0
- package/dist/core/inactivity.js +31 -0
- package/dist/core/label.js +7 -0
- package/dist/core/machine.js +134 -0
- package/dist/core/mcp-config.js +47 -0
- package/dist/core/outbox.js +145 -0
- package/dist/core/paths.js +46 -0
- package/dist/core/registry.js +129 -0
- package/dist/core/report.js +95 -0
- package/dist/core/resume.js +210 -0
- package/dist/core/retire.js +416 -0
- package/dist/core/send.js +17 -0
- package/dist/core/spawn-resume.js +96 -0
- package/dist/core/spawn.js +226 -0
- package/dist/core/startup-dialogs.js +120 -0
- package/dist/core/transcript.js +87 -0
- package/dist/core/types.js +2 -0
- package/dist/core/watcher.js +821 -0
- package/dist/daemon/client.js +459 -0
- package/dist/daemon/lock.js +68 -0
- package/dist/daemon/main.js +40 -0
- package/dist/daemon/protocol.js +104 -0
- package/dist/daemon/server.js +244 -0
- package/dist/daemon/service.js +67 -0
- package/dist/integrations/claude/channel.js +257 -0
- package/dist/integrations/claude/transcript.js +135 -0
- package/dist/integrations/pi/extension.js +119 -0
- package/dist/integrations/tools.js +314 -0
- package/package.json +10 -9
- package/bin/bellwether-mcp.js +0 -4
- package/bin/bellwether.js +0 -2
- package/src/cli.ts +0 -293
- package/src/core/classifier.ts +0 -108
- package/src/core/herdr-client.ts +0 -410
- package/src/core/outbox.ts +0 -89
- package/src/core/paths.ts +0 -41
- package/src/core/registry.ts +0 -96
- package/src/core/report.ts +0 -54
- package/src/core/spawn.ts +0 -159
- package/src/core/transcript.ts +0 -74
- package/src/core/types.ts +0 -95
- package/src/core/watcher.ts +0 -590
- package/src/daemon/client.ts +0 -383
- package/src/daemon/lock.ts +0 -72
- package/src/daemon/main.ts +0 -38
- package/src/daemon/protocol.ts +0 -184
- package/src/daemon/server.ts +0 -275
- package/src/daemon/service.ts +0 -80
- package/src/integrations/claude/channel.ts +0 -247
- package/src/integrations/claude/transcript.ts +0 -124
- package/src/integrations/pi/extension.ts +0 -136
- package/src/integrations/tools.ts +0 -235
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// The classifier: turns herdr states into child events, with a settle time for
|
|
2
|
+
// each. It is a pure function of (state, clock, observation) so tier 1 can run
|
|
3
|
+
// it against a fake clock without a socket.
|
|
4
|
+
import { DEFAULT_INACTIVE_MS, inactiveMsOf } from './inactivity.js';
|
|
5
|
+
/** Starting values. The lab tunes these; they are not measurements. */
|
|
6
|
+
export const DEFAULT_LIMITS = {
|
|
7
|
+
idleMs: 5_000,
|
|
8
|
+
blockedMs: 3_000,
|
|
9
|
+
stuckMs: 10 * 60_000,
|
|
10
|
+
inactiveMs: DEFAULT_INACTIVE_MS,
|
|
11
|
+
};
|
|
12
|
+
export function initialState(status, now, seed = {}) {
|
|
13
|
+
const activityAt = seed.activityAt ?? now;
|
|
14
|
+
return { status, statusSince: now, lastBusyAt: now, lastActivityAt: activityAt, firedInactiveFor: seed.firedInactiveFor };
|
|
15
|
+
}
|
|
16
|
+
/** The limits one child is judged by: the base, with the child's own thresholds. */
|
|
17
|
+
export function limitsFor(child, base) {
|
|
18
|
+
const limits = { ...base, inactiveMs: inactiveMsOf(child) };
|
|
19
|
+
return child.stuckMs === undefined ? limits : { ...limits, stuckMs: child.stuckMs };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The state a child starts from, recovered from its registry record. A parent
|
|
23
|
+
* that restarts resumes the same quiet period instead of a fresh one, and does
|
|
24
|
+
* not send the inactive event again for a period it already reported.
|
|
25
|
+
*/
|
|
26
|
+
export function seedFor(child, now) {
|
|
27
|
+
const activityAt = Math.max(Date.parse(child.lastBusyAt), Date.parse(child.statusChangedAt));
|
|
28
|
+
const fired = child.inactiveNotifiedFor === undefined ? NaN : Date.parse(child.inactiveNotifiedFor);
|
|
29
|
+
return initialState(child.lastStatus, now, {
|
|
30
|
+
activityAt: Number.isFinite(activityAt) ? activityAt : now,
|
|
31
|
+
firedInactiveFor: Number.isFinite(fired) ? fired : undefined,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export function isReady(status) {
|
|
35
|
+
return status === 'idle' || status === 'done';
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Fold one observation into the state and say whether an event is due.
|
|
39
|
+
* The returned state is a new object; the classifier never mutates its input.
|
|
40
|
+
*/
|
|
41
|
+
export function advance(state, observation, now, limits = DEFAULT_LIMITS) {
|
|
42
|
+
const next = { ...state };
|
|
43
|
+
const seqMoved = observation.completionSeq !== undefined && observation.completionSeq !== state.completionSeq;
|
|
44
|
+
if (observation.status !== state.status || seqMoved || observation.busy) {
|
|
45
|
+
next.lastActivityAt = now;
|
|
46
|
+
}
|
|
47
|
+
if (observation.status !== state.status) {
|
|
48
|
+
next.status = observation.status;
|
|
49
|
+
next.statusSince = now;
|
|
50
|
+
next.firedStuckSince = undefined;
|
|
51
|
+
next.firedBlocked = undefined;
|
|
52
|
+
}
|
|
53
|
+
const becameReady = isReady(observation.status) && !isReady(state.status);
|
|
54
|
+
if (seqMoved) {
|
|
55
|
+
next.completionSeq = observation.completionSeq;
|
|
56
|
+
next.statusSince = now;
|
|
57
|
+
}
|
|
58
|
+
else if (observation.completionSeq === undefined && becameReady) {
|
|
59
|
+
// herdr reports completion_seq on AgentInfo, and the watcher reads that
|
|
60
|
+
// projection, so a reconciled child normally carries one. The field is
|
|
61
|
+
// still absent before the first reconcile finishes, and on a pane herdr
|
|
62
|
+
// has not observed working for: a turn that ends faster than screen
|
|
63
|
+
// detection catches it leaves the value unchanged. A turn that ends is
|
|
64
|
+
// also visible as a status change into idle or done, so count those.
|
|
65
|
+
next.completionSeq = (state.completionSeq ?? 0) + 1;
|
|
66
|
+
next.statusSince = now;
|
|
67
|
+
}
|
|
68
|
+
if (observation.busy) {
|
|
69
|
+
next.lastBusyAt = now;
|
|
70
|
+
next.firedStuckSince = undefined;
|
|
71
|
+
next.firedBlocked = undefined;
|
|
72
|
+
}
|
|
73
|
+
// A blocked child stays blocked until someone answers it, so report the
|
|
74
|
+
// dialog once and then wait for the status to move rather than repeating it
|
|
75
|
+
// on every tick.
|
|
76
|
+
if (next.status === 'blocked' && now - next.statusSince >= limits.blockedMs && !next.firedBlocked) {
|
|
77
|
+
return { state: { ...next, firedBlocked: true }, event: 'blocked' };
|
|
78
|
+
}
|
|
79
|
+
if (isReady(next.status) && next.completionSeq !== undefined && next.completionSeq !== next.reportedFor && now - next.statusSince >= limits.idleMs) {
|
|
80
|
+
return { state: { ...next, reportedFor: next.completionSeq }, event: 'idle' };
|
|
81
|
+
}
|
|
82
|
+
// A child first seen already settled still owes its parent one message.
|
|
83
|
+
if (isReady(next.status) && next.completionSeq === undefined && state.status !== next.status && now - next.statusSince >= limits.idleMs) {
|
|
84
|
+
return { state: { ...next, completionSeq: 1, reportedFor: 1 }, event: 'idle' };
|
|
85
|
+
}
|
|
86
|
+
if ((next.status === 'working' || next.status === 'unknown') && next.firedStuckSince !== next.lastBusyAt && now - next.lastBusyAt >= limits.stuckMs) {
|
|
87
|
+
return { state: { ...next, firedStuckSince: next.lastBusyAt }, event: 'stuck' };
|
|
88
|
+
}
|
|
89
|
+
// Inactivity is checked last, so it never displaces a more specific event
|
|
90
|
+
// from the same pass. Whatever it defers fires on a later pass, because
|
|
91
|
+
// nothing here consumes the inactivity clock until it fires.
|
|
92
|
+
if (now - next.lastActivityAt >= (limits.inactiveMs ?? DEFAULT_INACTIVE_MS) && (next.firedInactiveFor === undefined || next.lastActivityAt > next.firedInactiveFor)) {
|
|
93
|
+
return { state: { ...next, firedInactiveFor: next.lastActivityAt }, event: 'inactive' };
|
|
94
|
+
}
|
|
95
|
+
return { state: next };
|
|
96
|
+
}
|
|
97
|
+
/** Mark the newest turn as covered by a report, so no idle event follows it. */
|
|
98
|
+
export function markReported(state, now) {
|
|
99
|
+
return { ...state, reportedFor: state.completionSeq, lastBusyAt: now, lastActivityAt: now, statusSince: now };
|
|
100
|
+
}
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// The herdr socket client: newline-delimited JSON, one connection per request,
|
|
2
|
+
// and one held-open connection for the subscription. The subscription checks
|
|
3
|
+
// the `subscription_started` acknowledgement and buffers frames that arrive
|
|
4
|
+
// before it, because herdr can deliver an event in the same read as the ack.
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
export const MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
const MAX_PENDING_EVENTS = 4096;
|
|
10
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
11
|
+
export const AGENT_STATUSES = ['idle', 'working', 'blocked', 'done', 'unknown'];
|
|
12
|
+
export class HerdrApiError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(`herdr ${message}`);
|
|
16
|
+
this.name = 'HerdrApiError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function dial(endpoint, onReady) {
|
|
21
|
+
if (typeof endpoint !== 'string')
|
|
22
|
+
return endpoint(onReady);
|
|
23
|
+
const socket = net.createConnection(endpoint);
|
|
24
|
+
socket.on('connect', onReady);
|
|
25
|
+
return socket;
|
|
26
|
+
}
|
|
27
|
+
let sequence = 0;
|
|
28
|
+
export function nextRequestId(prefix = 'bellwether') {
|
|
29
|
+
sequence += 1;
|
|
30
|
+
return `${prefix}:${process.pid}:${sequence}`;
|
|
31
|
+
}
|
|
32
|
+
function isRecord(value) {
|
|
33
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
/** herdr's own config root, which is also where a named session's socket lives. */
|
|
36
|
+
export function configHome() {
|
|
37
|
+
return process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config');
|
|
38
|
+
}
|
|
39
|
+
function sessionSocket(session) {
|
|
40
|
+
return path.join(configHome(), 'herdr', 'sessions', session, 'herdr.sock');
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* herdr's documented socket order: an explicit path, then the session flag,
|
|
44
|
+
* then HERDR_SOCKET_PATH, then HERDR_SESSION, then the default session.
|
|
45
|
+
*/
|
|
46
|
+
export function resolveSocketPath(options = {}) {
|
|
47
|
+
if (options.socketPath)
|
|
48
|
+
return options.socketPath;
|
|
49
|
+
if (options.session)
|
|
50
|
+
return sessionSocket(options.session);
|
|
51
|
+
const fromEnv = process.env['HERDR_SOCKET_PATH'];
|
|
52
|
+
if (fromEnv)
|
|
53
|
+
return fromEnv;
|
|
54
|
+
const envSession = process.env['HERDR_SESSION'];
|
|
55
|
+
if (envSession)
|
|
56
|
+
return sessionSocket(envSession);
|
|
57
|
+
return path.join(configHome(), 'herdr', 'herdr.sock');
|
|
58
|
+
}
|
|
59
|
+
class NdjsonFrames {
|
|
60
|
+
buffer = Buffer.alloc(0);
|
|
61
|
+
push(chunk) {
|
|
62
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
63
|
+
const frames = [];
|
|
64
|
+
for (;;) {
|
|
65
|
+
const newline = this.buffer.indexOf(0x0a);
|
|
66
|
+
if (newline < 0)
|
|
67
|
+
break;
|
|
68
|
+
const line = this.buffer.subarray(0, newline);
|
|
69
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
70
|
+
if (line.length === 0)
|
|
71
|
+
continue;
|
|
72
|
+
if (line.length > MAX_FRAME_BYTES)
|
|
73
|
+
throw new Error('herdr sent a frame over the size limit');
|
|
74
|
+
frames.push(JSON.parse(line.toString('utf8')));
|
|
75
|
+
}
|
|
76
|
+
if (this.buffer.length > MAX_FRAME_BYTES)
|
|
77
|
+
throw new Error('herdr sent a frame over the size limit');
|
|
78
|
+
return frames;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function errorFrom(frame) {
|
|
82
|
+
if (!('error' in frame))
|
|
83
|
+
return undefined;
|
|
84
|
+
const error = frame.error;
|
|
85
|
+
if (!isRecord(error))
|
|
86
|
+
return new HerdrApiError(undefined, 'returned an invalid error');
|
|
87
|
+
return new HerdrApiError(typeof error['code'] === 'string' ? error['code'] : undefined, typeof error['message'] === 'string' ? error['message'] : 'request failed');
|
|
88
|
+
}
|
|
89
|
+
/** One request on its own connection, resolving with `result` or rejecting with HerdrApiError. */
|
|
90
|
+
export function requestHerdr(endpoint, request, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
if (signal?.aborted)
|
|
93
|
+
return reject(new Error('herdr request aborted'));
|
|
94
|
+
const socket = dial(endpoint, () => socket.write(`${JSON.stringify(request)}\n`));
|
|
95
|
+
const frames = new NdjsonFrames();
|
|
96
|
+
let settled = false;
|
|
97
|
+
const timer = setTimeout(() => finish(new Error(`herdr ${request.method} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
98
|
+
timer.unref?.();
|
|
99
|
+
const cleanup = () => {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
signal?.removeEventListener('abort', onAbort);
|
|
102
|
+
socket.destroy();
|
|
103
|
+
};
|
|
104
|
+
const finish = (error, value) => {
|
|
105
|
+
if (settled)
|
|
106
|
+
return;
|
|
107
|
+
settled = true;
|
|
108
|
+
cleanup();
|
|
109
|
+
if (error)
|
|
110
|
+
reject(error);
|
|
111
|
+
else
|
|
112
|
+
resolve(value);
|
|
113
|
+
};
|
|
114
|
+
const onAbort = () => finish(new Error('herdr request aborted'));
|
|
115
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
116
|
+
socket.on('error', (error) => finish(error));
|
|
117
|
+
socket.on('end', () => finish(new Error(`herdr closed the connection before answering ${request.method}`)));
|
|
118
|
+
socket.on('data', (chunk) => {
|
|
119
|
+
if (settled)
|
|
120
|
+
return;
|
|
121
|
+
try {
|
|
122
|
+
for (const frame of frames.push(chunk)) {
|
|
123
|
+
if (!isRecord(frame))
|
|
124
|
+
continue;
|
|
125
|
+
const error = errorFrom(frame);
|
|
126
|
+
if (error && (frame['id'] === undefined || frame['id'] === ''))
|
|
127
|
+
return finish(error);
|
|
128
|
+
if (frame['id'] !== request.id)
|
|
129
|
+
continue;
|
|
130
|
+
if (error)
|
|
131
|
+
return finish(error);
|
|
132
|
+
if (!('result' in frame))
|
|
133
|
+
return finish(new Error(`herdr ${request.method} answered without a result`));
|
|
134
|
+
return finish(undefined, frame['result']);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Hold a subscription open. Frames that arrive before the acknowledgement are
|
|
145
|
+
* buffered and replayed, so no event is lost between connect and ack.
|
|
146
|
+
*/
|
|
147
|
+
export function openHerdrSubscription(endpoint, request, onEvent, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
if (signal.aborted)
|
|
150
|
+
return reject(new Error('herdr subscription aborted'));
|
|
151
|
+
const socket = dial(endpoint, () => socket.write(`${JSON.stringify(request)}\n`));
|
|
152
|
+
const frames = new NdjsonFrames();
|
|
153
|
+
const pending = [];
|
|
154
|
+
let ready = false;
|
|
155
|
+
let finished = false;
|
|
156
|
+
let intentional = false;
|
|
157
|
+
let resolveClosed = () => { };
|
|
158
|
+
let rejectClosed = () => { };
|
|
159
|
+
const closed = new Promise((res, rej) => {
|
|
160
|
+
resolveClosed = res;
|
|
161
|
+
rejectClosed = rej;
|
|
162
|
+
});
|
|
163
|
+
void closed.catch(() => undefined);
|
|
164
|
+
const timer = setTimeout(() => finish(new Error('herdr subscription was not acknowledged')), timeoutMs);
|
|
165
|
+
timer.unref?.();
|
|
166
|
+
function teardown() {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
signal.removeEventListener('abort', onAbort);
|
|
169
|
+
socket.destroy();
|
|
170
|
+
}
|
|
171
|
+
/** End the subscription. Before the ack it rejects the caller; after it, it closes. */
|
|
172
|
+
function finish(error) {
|
|
173
|
+
if (finished)
|
|
174
|
+
return;
|
|
175
|
+
finished = true;
|
|
176
|
+
teardown();
|
|
177
|
+
if (!ready) {
|
|
178
|
+
reject(error ?? new Error('herdr subscription aborted'));
|
|
179
|
+
resolveClosed();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (error && !intentional)
|
|
183
|
+
rejectClosed(error);
|
|
184
|
+
else
|
|
185
|
+
resolveClosed();
|
|
186
|
+
}
|
|
187
|
+
function onAbort() {
|
|
188
|
+
intentional = true;
|
|
189
|
+
finish();
|
|
190
|
+
}
|
|
191
|
+
function deliver(event) {
|
|
192
|
+
if (finished)
|
|
193
|
+
return;
|
|
194
|
+
try {
|
|
195
|
+
onEvent(event);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function handle(frame) {
|
|
202
|
+
if (isRecord(frame)) {
|
|
203
|
+
const error = errorFrom(frame);
|
|
204
|
+
const id = frame['id'];
|
|
205
|
+
if (error && (id === request.id || id === undefined || id === ''))
|
|
206
|
+
return finish(error);
|
|
207
|
+
if (id !== undefined && id !== '' && id !== request.id)
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (!ready) {
|
|
211
|
+
if (isRecord(frame) && frame['id'] === request.id) {
|
|
212
|
+
if (!isRecord(frame['result']) || frame['result']['type'] !== 'subscription_started') {
|
|
213
|
+
return finish(new Error('herdr returned an invalid subscription acknowledgement'));
|
|
214
|
+
}
|
|
215
|
+
ready = true;
|
|
216
|
+
clearTimeout(timer);
|
|
217
|
+
socket.unref();
|
|
218
|
+
resolve({ close() { intentional = true; finish(); }, closed });
|
|
219
|
+
for (const event of pending.splice(0))
|
|
220
|
+
deliver(event);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (pending.length >= MAX_PENDING_EVENTS)
|
|
224
|
+
return finish(new Error('too many herdr events arrived before the acknowledgement'));
|
|
225
|
+
if (isRecord(frame) && typeof frame['event'] === 'string')
|
|
226
|
+
pending.push({ event: frame['event'], data: isRecord(frame['data']) ? frame['data'] : {} });
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (isRecord(frame) && typeof frame['event'] === 'string')
|
|
230
|
+
deliver({ event: frame['event'], data: isRecord(frame['data']) ? frame['data'] : {} });
|
|
231
|
+
}
|
|
232
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
233
|
+
socket.on('error', (error) => finish(error));
|
|
234
|
+
socket.on('end', () => finish(intentional ? undefined : new Error('herdr closed the subscription')));
|
|
235
|
+
socket.on('data', (chunk) => {
|
|
236
|
+
if (finished)
|
|
237
|
+
return;
|
|
238
|
+
try {
|
|
239
|
+
for (const frame of frames.push(chunk)) {
|
|
240
|
+
if (finished)
|
|
241
|
+
return;
|
|
242
|
+
handle(frame);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
function optionalString(value) {
|
|
252
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
253
|
+
}
|
|
254
|
+
function optionalNumber(value) {
|
|
255
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
256
|
+
}
|
|
257
|
+
function agentStatus(value) {
|
|
258
|
+
return typeof value === 'string' && AGENT_STATUSES.includes(value) ? value : undefined;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The text of a pane.read answer. herdr nests it: the frame is
|
|
262
|
+
* `{type: 'pane_read', read: {pane_id, source, format, text}}`.
|
|
263
|
+
*/
|
|
264
|
+
export function paneText(result) {
|
|
265
|
+
if (typeof result === 'string')
|
|
266
|
+
return result;
|
|
267
|
+
if (isRecord(result)) {
|
|
268
|
+
const read = result['read'];
|
|
269
|
+
if (isRecord(read) && typeof read['text'] === 'string')
|
|
270
|
+
return read['text'];
|
|
271
|
+
if (typeof result['text'] === 'string')
|
|
272
|
+
return result['text'];
|
|
273
|
+
}
|
|
274
|
+
return '';
|
|
275
|
+
}
|
|
276
|
+
/** Read the fields Bellwether needs, and nothing else, from a raw pane object. */
|
|
277
|
+
export function parsePane(value) {
|
|
278
|
+
if (!isRecord(value))
|
|
279
|
+
return undefined;
|
|
280
|
+
const paneId = optionalString(value['pane_id']);
|
|
281
|
+
const workspaceId = optionalString(value['workspace_id']);
|
|
282
|
+
const tabId = optionalString(value['tab_id']);
|
|
283
|
+
const terminalId = optionalString(value['terminal_id']);
|
|
284
|
+
const status = agentStatus(value['agent_status']);
|
|
285
|
+
if (!paneId || !workspaceId || !tabId || !terminalId || !status)
|
|
286
|
+
return undefined;
|
|
287
|
+
const session = isRecord(value['agent_session']) ? optionalString(value['agent_session']['value']) : undefined;
|
|
288
|
+
return {
|
|
289
|
+
paneId,
|
|
290
|
+
workspaceId,
|
|
291
|
+
tabId,
|
|
292
|
+
terminalId,
|
|
293
|
+
focused: value['focused'] === true,
|
|
294
|
+
revision: optionalNumber(value['revision']) ?? 0,
|
|
295
|
+
cwd: optionalString(value['foreground_cwd']) ?? optionalString(value['cwd']),
|
|
296
|
+
agent: optionalString(value['agent']),
|
|
297
|
+
name: optionalString(value['name']),
|
|
298
|
+
agentStatus: status,
|
|
299
|
+
agentSessionId: session,
|
|
300
|
+
completionSeq: optionalNumber(value['completion_seq']),
|
|
301
|
+
terminalTitle: optionalString(value['terminal_title_stripped']) ?? optionalString(value['terminal_title']),
|
|
302
|
+
label: optionalString(value['label']),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/** A thin typed wrapper over one herdr server, local or on a saved machine. */
|
|
306
|
+
export class HerdrClient {
|
|
307
|
+
/** The local socket, or a `machine:` label for a client that dials a bridge. */
|
|
308
|
+
socketPath;
|
|
309
|
+
endpoint;
|
|
310
|
+
constructor(options = {}) {
|
|
311
|
+
if (options.dial) {
|
|
312
|
+
this.endpoint = options.dial;
|
|
313
|
+
this.socketPath = options.label ?? 'machine';
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
this.socketPath = resolveSocketPath(options);
|
|
317
|
+
this.endpoint = this.socketPath;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
request(method, params = {}, options = {}) {
|
|
321
|
+
return requestHerdr(this.endpoint, { id: options.id ?? nextRequestId(), method, params }, options.signal, options.timeoutMs);
|
|
322
|
+
}
|
|
323
|
+
async agentList(signal) {
|
|
324
|
+
const result = await this.request('agent.list', {}, { signal });
|
|
325
|
+
if (!isRecord(result) || !Array.isArray(result['agents']))
|
|
326
|
+
throw new Error('herdr returned an invalid agent list');
|
|
327
|
+
return result['agents'].map(parsePane).filter((pane) => pane !== undefined);
|
|
328
|
+
}
|
|
329
|
+
async paneList(signal) {
|
|
330
|
+
const result = await this.request('pane.list', {}, { signal });
|
|
331
|
+
if (!isRecord(result) || !Array.isArray(result['panes']))
|
|
332
|
+
throw new Error('herdr returned an invalid pane list');
|
|
333
|
+
return result['panes'].map(parsePane).filter((pane) => pane !== undefined);
|
|
334
|
+
}
|
|
335
|
+
snapshot(signal) {
|
|
336
|
+
return this.request('session.snapshot', {}, { signal }).then((result) => (isRecord(result) ? result : {}));
|
|
337
|
+
}
|
|
338
|
+
tabCreate(params, signal) {
|
|
339
|
+
return this.request('tab.create', {
|
|
340
|
+
workspace_id: params.workspaceId ?? null,
|
|
341
|
+
cwd: params.cwd ?? null,
|
|
342
|
+
label: params.label ?? null,
|
|
343
|
+
env: params.env ?? {},
|
|
344
|
+
focus: params.focus ?? false,
|
|
345
|
+
}, { signal }).then((result) => {
|
|
346
|
+
if (!isRecord(result))
|
|
347
|
+
return {};
|
|
348
|
+
const tab = isRecord(result['tab']) ? result['tab'] : undefined;
|
|
349
|
+
// herdr answers with root_pane; keep the pane alias for older servers.
|
|
350
|
+
const pane = isRecord(result['root_pane']) ? result['root_pane'] : isRecord(result['pane']) ? result['pane'] : undefined;
|
|
351
|
+
return { tabId: optionalString(tab?.['tab_id']), paneId: optionalString(pane?.['pane_id']) };
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
agentStart(params, signal) {
|
|
355
|
+
return this.request('agent.start', { name: params.name, kind: params.kind, pane_id: params.paneId, args: params.args ?? [], timeout_ms: params.timeoutMs ?? null }, { signal }).then(() => undefined);
|
|
356
|
+
}
|
|
357
|
+
async paneRead(params, signal) {
|
|
358
|
+
const result = await this.request('pane.read', { pane_id: params.paneId, source: params.source, lines: params.lines ?? null, format: 'text' }, { signal, timeoutMs: 8000 });
|
|
359
|
+
return paneText(result);
|
|
360
|
+
}
|
|
361
|
+
agentPrompt(target, text, signal) {
|
|
362
|
+
return this.request('agent.prompt', { target, text }, { signal, timeoutMs: 12000 }).then(() => undefined);
|
|
363
|
+
}
|
|
364
|
+
sendKeys(target, keys, signal) {
|
|
365
|
+
return this.request('agent.send_keys', { target, keys }, { signal }).then(() => undefined);
|
|
366
|
+
}
|
|
367
|
+
paneClose(paneId, signal) {
|
|
368
|
+
return this.request('pane.close', { pane_id: paneId }, { signal }).then(() => undefined);
|
|
369
|
+
}
|
|
370
|
+
tabClose(tabId, signal) {
|
|
371
|
+
return this.request('tab.close', { tab_id: tabId }, { signal }).then(() => undefined);
|
|
372
|
+
}
|
|
373
|
+
workspaceList(signal) {
|
|
374
|
+
return this.request('workspace.list', {}, { signal }).then((result) => (isRecord(result) && Array.isArray(result['workspaces']) ? result['workspaces'] : []));
|
|
375
|
+
}
|
|
376
|
+
paneCurrent(signal) {
|
|
377
|
+
return this.request('pane.current', {}, { signal }).then((result) => (isRecord(result) ? parsePane(result['pane']) : undefined));
|
|
378
|
+
}
|
|
379
|
+
subscribe(subscriptions, onEvent, signal, timeoutMs) {
|
|
380
|
+
return openHerdrSubscription(this.endpoint, { id: nextRequestId('sub'), method: 'events.subscribe', params: { subscriptions } }, onEvent, signal, timeoutMs);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The threshold when a spawn does not set one. */
|
|
2
|
+
export const DEFAULT_INACTIVE_MS = 5 * 60_000;
|
|
3
|
+
/** The longest threshold a spawn may ask for. Anything above it is clamped. */
|
|
4
|
+
export const MAX_INACTIVE_MS = 24 * 60 * 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* The shortest threshold. A spawn cannot turn the notification off, and a
|
|
7
|
+
* zero or negative value would fire on every tick, so the floor is one minute.
|
|
8
|
+
*/
|
|
9
|
+
export const MIN_INACTIVE_MS = 60_000;
|
|
10
|
+
/**
|
|
11
|
+
* Turn a spawn's minutes into the stored threshold in milliseconds. Leaving
|
|
12
|
+
* the value out gives the default. A value that is not a finite number, such
|
|
13
|
+
* as NaN, also gives the default; a value beyond the range is clamped to it.
|
|
14
|
+
* There is no input that yields no threshold.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveInactiveMs(minutes) {
|
|
17
|
+
if (minutes === undefined || Number.isNaN(minutes))
|
|
18
|
+
return DEFAULT_INACTIVE_MS;
|
|
19
|
+
const ms = minutes * 60_000;
|
|
20
|
+
return Math.min(MAX_INACTIVE_MS, Math.max(MIN_INACTIVE_MS, Math.round(ms)));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The threshold a child's record asks for, bounded again on read. A record
|
|
24
|
+
* written by hand, or by an older version, cannot push it past the range.
|
|
25
|
+
*/
|
|
26
|
+
export function inactiveMsOf(child) {
|
|
27
|
+
const stored = child.inactiveMs;
|
|
28
|
+
if (stored === undefined || !Number.isFinite(stored))
|
|
29
|
+
return DEFAULT_INACTIVE_MS;
|
|
30
|
+
return Math.min(MAX_INACTIVE_MS, Math.max(MIN_INACTIVE_MS, stored));
|
|
31
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// How a message names a child. Two children may share a name, so the name is
|
|
2
|
+
// the human label and the pane id tells them apart. A child whose tab never
|
|
3
|
+
// opened has no pane yet, and its own id stands in.
|
|
4
|
+
export function childLabel(child) {
|
|
5
|
+
const handle = child.paneId || child.id?.slice(0, 8);
|
|
6
|
+
return handle ? `${child.name} (${handle})` : child.name;
|
|
7
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Reaching a herdr server on another machine. herdr's own `--machine` prefix
|
|
2
|
+
// runs `herdr --session <s> remote-api-bridge` over SSH on the saved profile's
|
|
3
|
+
// target, and speaks the socket protocol over that process's stdio. Bellwether
|
|
4
|
+
// does the same, so a subscription to a remote pane works like a local one.
|
|
5
|
+
import { execFile, spawn } from 'node:child_process';
|
|
6
|
+
import { EventEmitter } from 'node:events';
|
|
7
|
+
import { HerdrClient } from './herdr-client.js';
|
|
8
|
+
/** The host a child runs on when no machine was named: this machine's herdr. */
|
|
9
|
+
export const LOCAL_HOST = 'local';
|
|
10
|
+
/** The capability string a bridge-capable herdr prints for `remote-api-bridge --check`. */
|
|
11
|
+
const BRIDGE_CAPABILITY = 'herdr-api-bridge-v1';
|
|
12
|
+
/**
|
|
13
|
+
* The remote side: find a herdr that can bridge, the way herdr's own forwarding
|
|
14
|
+
* does, because a non-interactive SSH shell often has no herdr on its PATH.
|
|
15
|
+
*/
|
|
16
|
+
const BRIDGE_SCRIPT = [
|
|
17
|
+
'for c in "$(command -v herdr 2>/dev/null)" "$HOME/.local/bin/herdr" /home/linuxbrew/.linuxbrew/bin/herdr /opt/homebrew/bin/herdr /usr/local/bin/herdr; do',
|
|
18
|
+
' [ -n "$c" ] && [ -x "$c" ] || continue',
|
|
19
|
+
` if [ "$("$c" --session "$1" remote-api-bridge --check </dev/null 2>/dev/null)" = ${BRIDGE_CAPABILITY} ]; then exec "$c" --session "$1" remote-api-bridge; fi`,
|
|
20
|
+
'done',
|
|
21
|
+
"echo 'no herdr on this machine can bridge the API; update herdr there' >&2",
|
|
22
|
+
'exit 78',
|
|
23
|
+
].join('\n');
|
|
24
|
+
function shellQuote(value) {
|
|
25
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
26
|
+
}
|
|
27
|
+
/** The command line SSH runs on the remote machine. */
|
|
28
|
+
export function bridgeCommand(session) {
|
|
29
|
+
return `sh -c ${shellQuote(BRIDGE_SCRIPT)} bellwether-bridge ${shellQuote(session)}`;
|
|
30
|
+
}
|
|
31
|
+
/** Dial a machine's herdr through an SSH process whose stdio is the connection. */
|
|
32
|
+
export function bridgeDialer(profile, ssh = 'ssh') {
|
|
33
|
+
return (onReady) => {
|
|
34
|
+
const child = spawn(ssh, ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-T', profile.target, bridgeCommand(profile.session)], { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
35
|
+
const events = new EventEmitter();
|
|
36
|
+
let stderr = '';
|
|
37
|
+
let failed = false;
|
|
38
|
+
const fail = (error) => {
|
|
39
|
+
if (failed)
|
|
40
|
+
return;
|
|
41
|
+
failed = true;
|
|
42
|
+
events.emit('error', error);
|
|
43
|
+
};
|
|
44
|
+
child.on('spawn', onReady);
|
|
45
|
+
child.on('error', fail);
|
|
46
|
+
child.stdin.on('error', () => { });
|
|
47
|
+
child.stdout.on('data', (chunk) => events.emit('data', chunk));
|
|
48
|
+
child.stderr.on('data', (chunk) => {
|
|
49
|
+
stderr = `${stderr}${chunk.toString('utf8')}`.slice(-2000);
|
|
50
|
+
});
|
|
51
|
+
// Wait for the process to close rather than for stdout to end, so a failed
|
|
52
|
+
// bridge reports its stderr instead of a bare closed connection.
|
|
53
|
+
child.on('close', (code, signal) => {
|
|
54
|
+
if (code === 0 || signal === 'SIGTERM')
|
|
55
|
+
events.emit('end');
|
|
56
|
+
else
|
|
57
|
+
fail(new Error(`the herdr bridge to machine ${profile.label} exited with ${code ?? signal}${stderr.trim() ? `: ${stderr.trim()}` : ''}`));
|
|
58
|
+
});
|
|
59
|
+
const connection = {
|
|
60
|
+
write: (line) => child.stdin.write(line),
|
|
61
|
+
on: (event, listener) => events.on(event, listener),
|
|
62
|
+
destroy: () => {
|
|
63
|
+
if (child.exitCode === null)
|
|
64
|
+
child.kill('SIGTERM');
|
|
65
|
+
},
|
|
66
|
+
unref: () => {
|
|
67
|
+
child.unref();
|
|
68
|
+
for (const stream of [child.stdin, child.stdout, child.stderr])
|
|
69
|
+
stream.unref?.();
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
return connection;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function isRecord(value) {
|
|
76
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
77
|
+
}
|
|
78
|
+
/** Parse `herdr machine list --json`. */
|
|
79
|
+
export function parseMachineList(text) {
|
|
80
|
+
const value = JSON.parse(text);
|
|
81
|
+
if (!Array.isArray(value))
|
|
82
|
+
throw new Error('herdr machine list did not print a list');
|
|
83
|
+
return value.filter(isRecord).flatMap((entry) => {
|
|
84
|
+
const { id, label, target, session, enabled } = entry;
|
|
85
|
+
if (typeof id !== 'string' || typeof label !== 'string' || typeof target !== 'string')
|
|
86
|
+
return [];
|
|
87
|
+
return [{ id, label, target, session: typeof session === 'string' && session ? session : 'default', enabled: enabled !== false }];
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** Pick a profile the way herdr does: by id, or by a unique, case-sensitive label. */
|
|
91
|
+
export function pickMachine(profiles, selector) {
|
|
92
|
+
const byId = profiles.find((profile) => profile.id === selector);
|
|
93
|
+
const byLabel = profiles.filter((profile) => profile.label === selector);
|
|
94
|
+
const profile = byId ?? (byLabel.length === 1 ? byLabel[0] : undefined);
|
|
95
|
+
if (!profile) {
|
|
96
|
+
const known = profiles.map((entry) => entry.label).join(', ') || 'none';
|
|
97
|
+
throw new Error(byLabel.length > 1 ? `more than one saved herdr machine is labelled ${selector}; name it by id` : `herdr has no saved machine ${selector}. Saved machines: ${known}.`);
|
|
98
|
+
}
|
|
99
|
+
if (!profile.enabled)
|
|
100
|
+
throw new Error(`the herdr machine ${selector} is disabled`);
|
|
101
|
+
return profile;
|
|
102
|
+
}
|
|
103
|
+
/** Ask the local herdr for its saved machines. */
|
|
104
|
+
export const resolveMachine = (selector) => new Promise((resolve, reject) => {
|
|
105
|
+
execFile('herdr', ['machine', 'list', '--json'], { timeout: 10_000 }, (error, stdout) => {
|
|
106
|
+
if (error)
|
|
107
|
+
return reject(new Error(`herdr machine list failed: ${error.message}`));
|
|
108
|
+
try {
|
|
109
|
+
resolve(pickMachine(parseMachineList(stdout), selector));
|
|
110
|
+
}
|
|
111
|
+
catch (fault) {
|
|
112
|
+
reject(fault);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
export function machineClients(local, resolve = resolveMachine) {
|
|
117
|
+
const clients = new Map();
|
|
118
|
+
return (host) => {
|
|
119
|
+
if (host === LOCAL_HOST)
|
|
120
|
+
return Promise.resolve(local);
|
|
121
|
+
let client = clients.get(host);
|
|
122
|
+
if (!client) {
|
|
123
|
+
client = resolve(host).then((profile) => new HerdrClient({ dial: bridgeDialer(profile), label: `machine:${profile.label}` }));
|
|
124
|
+
// A failed lookup is not cached, so a machine saved later still works.
|
|
125
|
+
client.catch(() => clients.delete(host));
|
|
126
|
+
clients.set(host, client);
|
|
127
|
+
}
|
|
128
|
+
return client;
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** The host a child record names, with an older record read as local. */
|
|
132
|
+
export function hostOf(child) {
|
|
133
|
+
return child.host ?? LOCAL_HOST;
|
|
134
|
+
}
|