@elecnix/bellwether 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/cli.js +295 -0
- package/dist/core/classifier.js +66 -0
- package/dist/core/herdr-client.js +368 -0
- package/dist/core/outbox.js +80 -0
- package/dist/core/paths.js +32 -0
- package/dist/core/registry.js +93 -0
- package/dist/core/report.js +50 -0
- package/dist/core/spawn.js +128 -0
- package/dist/core/transcript.js +79 -0
- package/dist/core/types.js +1 -0
- package/dist/core/watcher.js +593 -0
- package/dist/daemon/client.js +377 -0
- package/dist/daemon/lock.js +68 -0
- package/dist/daemon/main.js +34 -0
- package/dist/daemon/protocol.js +90 -0
- package/dist/daemon/server.js +244 -0
- package/dist/daemon/service.js +63 -0
- package/dist/integrations/claude/channel.js +245 -0
- package/dist/integrations/claude/transcript.js +135 -0
- package/dist/integrations/pi/extension.js +117 -0
- package/dist/integrations/tools.js +220 -0
- package/package.json +7 -6
- package/bin/bellwether-mcp.js +0 -4
- package/bin/bellwether.js +0 -2
- package/src/cli.ts +0 -293
- package/src/core/classifier.ts +0 -108
- package/src/core/herdr-client.ts +0 -410
- package/src/core/outbox.ts +0 -89
- package/src/core/paths.ts +0 -41
- package/src/core/registry.ts +0 -96
- package/src/core/report.ts +0 -54
- package/src/core/spawn.ts +0 -159
- package/src/core/transcript.ts +0 -74
- package/src/core/types.ts +0 -95
- package/src/core/watcher.ts +0 -590
- package/src/daemon/client.ts +0 -383
- package/src/daemon/lock.ts +0 -72
- package/src/daemon/main.ts +0 -38
- package/src/daemon/protocol.ts +0 -184
- package/src/daemon/server.ts +0 -275
- package/src/daemon/service.ts +0 -80
- package/src/integrations/claude/channel.ts +0 -247
- package/src/integrations/claude/transcript.ts +0 -124
- package/src/integrations/pi/extension.ts +0 -136
- package/src/integrations/tools.ts +0 -235
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
// The watcher: subscribe to the child panes, reconcile against a snapshot,
|
|
2
|
+
// turn herdr states into events, and hand new events to the parent's adapter.
|
|
3
|
+
//
|
|
4
|
+
// The order matters and comes from herdr-lantern: subscribe first, then take a
|
|
5
|
+
// snapshot on a second connection, then reconcile. herdr does not replay
|
|
6
|
+
// events, so a subscription opened after the snapshot would miss whatever
|
|
7
|
+
// happened in between. After a disconnect the watcher takes a fresh snapshot
|
|
8
|
+
// for the same reason.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import { DEFAULT_LIMITS, advance, initialState, markReported } from './classifier.js';
|
|
11
|
+
import { Outbox } from './outbox.js';
|
|
12
|
+
import { mutateParent, readParent, updateChild } from './registry.js';
|
|
13
|
+
import { resolveTranscript, sessionValueFrom } from './transcript.js';
|
|
14
|
+
import { spoolPath } from './paths.js';
|
|
15
|
+
/** herdr's status for a pane, or the child's last known status. */
|
|
16
|
+
function isRecord(value) {
|
|
17
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function statusOf(pane, fallback) {
|
|
20
|
+
const value = pane?.['agent_status'];
|
|
21
|
+
return typeof value === 'string' && ['idle', 'working', 'blocked', 'done', 'unknown'].includes(value) ? value : fallback;
|
|
22
|
+
}
|
|
23
|
+
export class Watcher {
|
|
24
|
+
client;
|
|
25
|
+
parentId;
|
|
26
|
+
limits;
|
|
27
|
+
onEntries;
|
|
28
|
+
now;
|
|
29
|
+
tickMs;
|
|
30
|
+
screenPollMs;
|
|
31
|
+
log;
|
|
32
|
+
outbox;
|
|
33
|
+
states = new Map();
|
|
34
|
+
screenReadAt = new Map();
|
|
35
|
+
transcriptSizes = new Map();
|
|
36
|
+
transcriptLookAt = new Map();
|
|
37
|
+
controller;
|
|
38
|
+
subscription;
|
|
39
|
+
subscribedKey = '';
|
|
40
|
+
ticker;
|
|
41
|
+
reconnecting = false;
|
|
42
|
+
spoolOffset = 0;
|
|
43
|
+
stopped = true;
|
|
44
|
+
constructor(options) {
|
|
45
|
+
this.client = options.client;
|
|
46
|
+
this.parentId = options.parentId;
|
|
47
|
+
this.limits = options.limits ?? DEFAULT_LIMITS;
|
|
48
|
+
this.onEntries = options.onEntries;
|
|
49
|
+
this.now = options.now ?? (() => Date.now());
|
|
50
|
+
this.tickMs = options.tickMs ?? 5_000;
|
|
51
|
+
this.screenPollMs = options.screenPollMs ?? 30_000;
|
|
52
|
+
this.log = options.log ?? (() => { });
|
|
53
|
+
this.outbox = Outbox.load(this.parentId);
|
|
54
|
+
}
|
|
55
|
+
start() {
|
|
56
|
+
if (!this.stopped)
|
|
57
|
+
return;
|
|
58
|
+
this.stopped = false;
|
|
59
|
+
// Resume the child spool where the last run stopped, so a restart neither
|
|
60
|
+
// replays old reports nor drops one written while the parent was down.
|
|
61
|
+
this.spoolOffset = readParent(this.parentId)?.spoolOffset ?? 0;
|
|
62
|
+
this.controller = new AbortController();
|
|
63
|
+
this.ticker = setInterval(() => void this.tick(), this.tickMs);
|
|
64
|
+
this.ticker.unref?.();
|
|
65
|
+
void this.reconcileAndSubscribe();
|
|
66
|
+
}
|
|
67
|
+
stop() {
|
|
68
|
+
this.stopped = true;
|
|
69
|
+
if (this.ticker)
|
|
70
|
+
clearInterval(this.ticker);
|
|
71
|
+
this.ticker = undefined;
|
|
72
|
+
this.subscription?.close();
|
|
73
|
+
this.subscription = undefined;
|
|
74
|
+
this.controller?.abort();
|
|
75
|
+
this.controller = undefined;
|
|
76
|
+
}
|
|
77
|
+
outboxEntries() {
|
|
78
|
+
return this.outbox.all();
|
|
79
|
+
}
|
|
80
|
+
markRead(receipt) {
|
|
81
|
+
if (!this.outbox.markRead(receipt))
|
|
82
|
+
return;
|
|
83
|
+
this.outbox.save(this.parentId);
|
|
84
|
+
}
|
|
85
|
+
/** Record that a receipt has been sent to the parent, so a burst is sent once. */
|
|
86
|
+
markDelivered(receipt) {
|
|
87
|
+
this.outbox.markDelivered(receipt);
|
|
88
|
+
this.outbox.save(this.parentId);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Subscribe to the current child panes, then reconcile against a snapshot.
|
|
92
|
+
* A pane that has gone away must be dropped first: herdr rejects the whole
|
|
93
|
+
* subscription when one pane id no longer exists, which would silence every
|
|
94
|
+
* other child.
|
|
95
|
+
*/
|
|
96
|
+
async reconcileAndSubscribe() {
|
|
97
|
+
if (this.stopped)
|
|
98
|
+
return;
|
|
99
|
+
const signal = this.controller?.signal;
|
|
100
|
+
if (!signal)
|
|
101
|
+
return;
|
|
102
|
+
try {
|
|
103
|
+
const record = readParent(this.parentId);
|
|
104
|
+
const children = record?.children ?? [];
|
|
105
|
+
const live = await this.livePanes(signal);
|
|
106
|
+
const addressable = [];
|
|
107
|
+
for (const child of children) {
|
|
108
|
+
if (child.exitedAt)
|
|
109
|
+
continue;
|
|
110
|
+
// A record written a moment ago may predate its pane. Leave it be.
|
|
111
|
+
if (!child.paneId || Date.now() - Date.parse(child.startedAt) < 15_000 || live.has(child.paneId)) {
|
|
112
|
+
if (child.paneId)
|
|
113
|
+
addressable.push(child);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
this.markExited(child, undefined);
|
|
117
|
+
}
|
|
118
|
+
await this.ensureSubscription(addressable, signal);
|
|
119
|
+
await this.reconcile(addressable, signal);
|
|
120
|
+
this.publish();
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
this.log(`reconcile failed: ${String(error)}`);
|
|
124
|
+
this.subscribedKey = '';
|
|
125
|
+
this.scheduleReconnect();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Every pane id herdr currently knows about. */
|
|
129
|
+
async livePanes(signal) {
|
|
130
|
+
try {
|
|
131
|
+
const result = await this.client.request('pane.list', {}, { signal });
|
|
132
|
+
const list = isRecord(result) && Array.isArray(result['panes']) ? result['panes'] : [];
|
|
133
|
+
return new Set(list.map((pane) => pane['pane_id']).filter((id) => typeof id === 'string'));
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
// An unreachable herdr is handled by the caller's reconnect.
|
|
137
|
+
return new Set();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
markExited(child, code) {
|
|
141
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
142
|
+
entry.exitedAt = new Date().toISOString();
|
|
143
|
+
entry.exitCode = code;
|
|
144
|
+
entry.lastStatus = 'unknown';
|
|
145
|
+
});
|
|
146
|
+
this.offer(child, 'exited', this.describeExit(child.name, code));
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* herdr's status subscriptions are per pane, so the subscription is rebuilt
|
|
150
|
+
* whenever the set of child panes changes.
|
|
151
|
+
*/
|
|
152
|
+
async ensureSubscription(children, signal) {
|
|
153
|
+
const key = paneKey(children);
|
|
154
|
+
if (key === this.subscribedKey && this.subscription)
|
|
155
|
+
return;
|
|
156
|
+
this.subscription?.close();
|
|
157
|
+
this.subscription = undefined;
|
|
158
|
+
const subscriptions = [
|
|
159
|
+
{ type: 'pane.exited' },
|
|
160
|
+
{ type: 'pane.closed' },
|
|
161
|
+
// A tab close sends tab_closed and no pane event, so this is the only
|
|
162
|
+
// signal that a child whose tab went away is gone.
|
|
163
|
+
{ type: 'tab.closed' },
|
|
164
|
+
{ type: 'pane.agent_detected' },
|
|
165
|
+
...children.filter((child) => !child.exitedAt).map((child) => ({ type: 'pane.agent_status_changed', pane_id: child.paneId })),
|
|
166
|
+
];
|
|
167
|
+
this.subscription = await this.client.subscribe(subscriptions, (event) => void this.onHerdrEvent(event), signal);
|
|
168
|
+
this.subscribedKey = key;
|
|
169
|
+
this.log(`subscribed to ${children.length} child pane(s)`);
|
|
170
|
+
void this.subscription.closed.catch((error) => {
|
|
171
|
+
this.log(`subscription lost: ${String(error)}`);
|
|
172
|
+
this.subscribedKey = '';
|
|
173
|
+
this.scheduleReconnect();
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
scheduleReconnect() {
|
|
177
|
+
if (this.stopped || this.reconnecting)
|
|
178
|
+
return;
|
|
179
|
+
this.reconnecting = true;
|
|
180
|
+
let delay = 250;
|
|
181
|
+
const attempt = () => {
|
|
182
|
+
if (this.stopped)
|
|
183
|
+
return;
|
|
184
|
+
void this.reconcileAndSubscribe()
|
|
185
|
+
.then(() => {
|
|
186
|
+
this.reconnecting = false;
|
|
187
|
+
})
|
|
188
|
+
.catch(() => {
|
|
189
|
+
delay = Math.min(delay * 2, 10_000);
|
|
190
|
+
setTimeout(attempt, delay).unref?.();
|
|
191
|
+
});
|
|
192
|
+
};
|
|
193
|
+
setTimeout(attempt, delay).unref?.();
|
|
194
|
+
}
|
|
195
|
+
async onHerdrEvent(event) {
|
|
196
|
+
const paneId = typeof event.data['pane_id'] === 'string' ? event.data['pane_id'] : undefined;
|
|
197
|
+
const tabId = typeof event.data['tab_id'] === 'string' ? event.data['tab_id'] : undefined;
|
|
198
|
+
if (!paneId && !tabId) {
|
|
199
|
+
if (event.event === 'events.lost' || event.event === 'events_lost') {
|
|
200
|
+
this.log('herdr reported lost events; resubscribing');
|
|
201
|
+
this.subscribedKey = '';
|
|
202
|
+
void this.reconcileAndSubscribe();
|
|
203
|
+
}
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const record = readParent(this.parentId);
|
|
207
|
+
// A tab close names a tab and carries no pane id, so match either.
|
|
208
|
+
const child = record?.children.find((entry) => (paneId !== undefined && entry.paneId === paneId) || (tabId !== undefined && entry.tabId === tabId));
|
|
209
|
+
if (!child)
|
|
210
|
+
return;
|
|
211
|
+
if (CLOSE_EVENTS.has(event.event)) {
|
|
212
|
+
const code = typeof event.data['exit_code'] === 'number' ? event.data['exit_code'] : undefined;
|
|
213
|
+
this.markExited(child, code);
|
|
214
|
+
// The subscription named that pane, so it has to be rebuilt without it.
|
|
215
|
+
this.subscribedKey = '';
|
|
216
|
+
void this.reconcileAndSubscribe();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (STATUS_EVENTS.has(event.event)) {
|
|
220
|
+
const status = statusOf(event.data, child.lastStatus);
|
|
221
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
222
|
+
if (entry.lastStatus !== status)
|
|
223
|
+
entry.statusChangedAt = new Date().toISOString();
|
|
224
|
+
entry.lastStatus = status;
|
|
225
|
+
});
|
|
226
|
+
// Read the registry again rather than reusing the copy taken above,
|
|
227
|
+
// which still holds the status from before this event.
|
|
228
|
+
await this.evaluate();
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (event.event === 'pane.agent_detected') {
|
|
232
|
+
const signal = this.controller?.signal;
|
|
233
|
+
if (signal)
|
|
234
|
+
await this.reconcile(record?.children ?? [], signal);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/** Read the live status of every child and fold it into the classifier. */
|
|
238
|
+
async reconcile(children, signal) {
|
|
239
|
+
if (!children.length)
|
|
240
|
+
return;
|
|
241
|
+
let panes = [];
|
|
242
|
+
let agents = [];
|
|
243
|
+
try {
|
|
244
|
+
// session.snapshot answers {type, snapshot: {panes, agents, tabs, ...}}.
|
|
245
|
+
const result = await this.client.snapshot(signal);
|
|
246
|
+
const snapshot = isRecord(result['snapshot']) ? result['snapshot'] : result;
|
|
247
|
+
const paneList = snapshot['panes'] ?? snapshot['pane_list'];
|
|
248
|
+
panes = Array.isArray(paneList) ? paneList : [];
|
|
249
|
+
const agentList = snapshot['agents'];
|
|
250
|
+
agents = Array.isArray(agentList) ? agentList : [];
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
this.log(`snapshot failed: ${String(error)}`);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
// A pane entry is a PaneInfo, which carries no completion_seq. The agent
|
|
257
|
+
// entry beside it is an AgentInfo, which does, so the agent entry wins.
|
|
258
|
+
const byId = new Map();
|
|
259
|
+
for (const pane of [...panes, ...agents]) {
|
|
260
|
+
const paneId = pane['pane_id'];
|
|
261
|
+
if (typeof paneId === 'string')
|
|
262
|
+
byId.set(paneId, pane);
|
|
263
|
+
}
|
|
264
|
+
for (const child of children) {
|
|
265
|
+
const pane = byId.get(child.paneId);
|
|
266
|
+
if (!pane)
|
|
267
|
+
continue;
|
|
268
|
+
const status = statusOf(pane, child.lastStatus);
|
|
269
|
+
const seq = typeof pane['completion_seq'] === 'number' ? pane['completion_seq'] : undefined;
|
|
270
|
+
if (status !== child.lastStatus || (seq !== undefined && seq !== child.completionSeq)) {
|
|
271
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
272
|
+
if (entry.lastStatus !== status)
|
|
273
|
+
entry.statusChangedAt = new Date().toISOString();
|
|
274
|
+
entry.lastStatus = status;
|
|
275
|
+
if (seq !== undefined)
|
|
276
|
+
entry.completionSeq = seq;
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
await this.evaluate();
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* One classifier pass over every child. It reads the registry itself, so a
|
|
284
|
+
* caller can never hand it a stale copy.
|
|
285
|
+
*/
|
|
286
|
+
async evaluate() {
|
|
287
|
+
const record = readParent(this.parentId);
|
|
288
|
+
if (!record)
|
|
289
|
+
return;
|
|
290
|
+
const now = this.now();
|
|
291
|
+
for (const child of record.children) {
|
|
292
|
+
if (child.exitedAt)
|
|
293
|
+
continue;
|
|
294
|
+
const state = this.states.get(child.id) ?? initialState(child.lastStatus, now);
|
|
295
|
+
const busy = await this.childIsBusy(child, now);
|
|
296
|
+
// A spawn can set its own stuck threshold, which is what the lab uses to
|
|
297
|
+
// reach that event in seconds rather than ten minutes.
|
|
298
|
+
const limits = child.stuckMs === undefined ? this.limits : { ...this.limits, stuckMs: child.stuckMs };
|
|
299
|
+
const { state: next, event } = advance(state, { status: child.lastStatus, completionSeq: child.completionSeq, busy }, now, limits);
|
|
300
|
+
this.states.set(child.id, next);
|
|
301
|
+
if (!event)
|
|
302
|
+
continue;
|
|
303
|
+
// A report for this turn already told the parent everything the idle
|
|
304
|
+
// event would say, so keep the one message.
|
|
305
|
+
if (event === 'idle' && child.reportPending) {
|
|
306
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
307
|
+
entry.reportPending = false;
|
|
308
|
+
});
|
|
309
|
+
this.states.set(child.id, markReported(next, now));
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
if (event === 'idle' && child.lastReport && Date.parse(child.lastReport.at) >= Date.parse(child.statusChangedAt)) {
|
|
313
|
+
this.states.set(child.id, markReported(next, now));
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
this.offer(child, event, await this.describe(child, event, next.lastBusyAt, now));
|
|
317
|
+
}
|
|
318
|
+
this.publish();
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* The child's transcript. A spawn can finish before herdr has detected the
|
|
322
|
+
* agent, so the path is resolved lazily rather than only at spawn time.
|
|
323
|
+
*/
|
|
324
|
+
async transcriptFor(child) {
|
|
325
|
+
if (child.transcript)
|
|
326
|
+
return child.transcript;
|
|
327
|
+
// A child whose harness keeps no transcript would otherwise cost one
|
|
328
|
+
// herdr call per tick forever. Look again once a minute at most, because
|
|
329
|
+
// herdr can report the session a little after the spawn returns.
|
|
330
|
+
const lastLook = this.transcriptLookAt.get(child.id) ?? 0;
|
|
331
|
+
if (this.now() - lastLook < TRANSCRIPT_LOOK_INTERVAL_MS)
|
|
332
|
+
return undefined;
|
|
333
|
+
this.transcriptLookAt.set(child.id, this.now());
|
|
334
|
+
try {
|
|
335
|
+
const result = await this.client.request('agent.get', { target: child.paneId });
|
|
336
|
+
const record = isRecord(result) && isRecord(result['agent']) ? result['agent'] : isRecord(result) ? result : undefined;
|
|
337
|
+
const path = resolveTranscript(child.harness, sessionValueFrom(record?.['agent_session']), child.cwd);
|
|
338
|
+
if (path)
|
|
339
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
340
|
+
entry.transcript = path;
|
|
341
|
+
});
|
|
342
|
+
return path;
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** Whether the child moved since the last look. Transcript growth, then screen. */
|
|
349
|
+
async childIsBusy(child, now) {
|
|
350
|
+
const transcript = await this.transcriptFor(child);
|
|
351
|
+
if (transcript) {
|
|
352
|
+
try {
|
|
353
|
+
const size = fs.statSync(transcript).size;
|
|
354
|
+
const previous = this.transcriptSizes.get(child.id);
|
|
355
|
+
this.transcriptSizes.set(child.id, size);
|
|
356
|
+
// The first look only sets the baseline.
|
|
357
|
+
if (previous === undefined || size <= previous)
|
|
358
|
+
return false;
|
|
359
|
+
if (!conversationGrowth(readRange(transcript, previous, size)))
|
|
360
|
+
return false;
|
|
361
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
362
|
+
entry.lastBusyAt = new Date().toISOString();
|
|
363
|
+
});
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
// A harness with no transcript moves only its screen, which costs a read.
|
|
371
|
+
if (this.screenPollMs <= 0)
|
|
372
|
+
return false;
|
|
373
|
+
const last = this.screenReadAt.get(child.id) ?? 0;
|
|
374
|
+
if (now - last < this.screenPollMs)
|
|
375
|
+
return false;
|
|
376
|
+
this.screenReadAt.set(child.id, now);
|
|
377
|
+
try {
|
|
378
|
+
const screen = await this.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 });
|
|
379
|
+
const lines = screen.split('\n').filter((line) => line.trim().length > 0 && !/⏱|\[\d+% ·/.test(line));
|
|
380
|
+
const previous = this.lastScreen.get(child.id);
|
|
381
|
+
this.lastScreen.set(child.id, lines.join('\n'));
|
|
382
|
+
if (previous !== undefined && previous !== lines.join('\n')) {
|
|
383
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
384
|
+
entry.lastBusyAt = new Date().toISOString();
|
|
385
|
+
});
|
|
386
|
+
return true;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
lastScreen = new Map();
|
|
395
|
+
/** What the parent is told about a child event. */
|
|
396
|
+
async describe(child, event, quietSince, now) {
|
|
397
|
+
const age = this.age(Date.parse(child.startedAt));
|
|
398
|
+
if (event === 'exited')
|
|
399
|
+
return this.describeExit(child.name, child.exitCode);
|
|
400
|
+
if (event === 'blocked') {
|
|
401
|
+
const dialog = await this.client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }).catch(() => '');
|
|
402
|
+
return `${child.name} is blocked on a dialog after ${age}. The dialog:\n${trim(dialog)}\n\nAnswer it with agent_send keys, or answer the card your-attention posted.`;
|
|
403
|
+
}
|
|
404
|
+
// Measure the quiet period on the classifier's own clock. The registry's
|
|
405
|
+
// lastBusyAt can be written by another process that only sees file size.
|
|
406
|
+
if (event === 'stuck')
|
|
407
|
+
return `${child.name} has been quiet for ${this.age(quietSince, now)}. Last screen lines:\n${trim(await this.screenTail(child))}`;
|
|
408
|
+
const text = child.lastReport?.text?.trim() || (await this.lastMessage(child)) || trim(await this.screenTail(child));
|
|
409
|
+
return `${child.name} went idle after ${age}:${text ? `\n${text}` : ' no message and no readable screen.'}`;
|
|
410
|
+
}
|
|
411
|
+
describeExit(name, code) {
|
|
412
|
+
return `${name} exited${code === undefined ? '' : ` with code ${code}`}.`;
|
|
413
|
+
}
|
|
414
|
+
async screenTail(child, lines = 40) {
|
|
415
|
+
return this.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines }).catch(() => '');
|
|
416
|
+
}
|
|
417
|
+
/** The child's last assistant message, read from its transcript. */
|
|
418
|
+
async lastMessage(child) {
|
|
419
|
+
const transcript = await this.transcriptFor(child);
|
|
420
|
+
if (!transcript)
|
|
421
|
+
return undefined;
|
|
422
|
+
try {
|
|
423
|
+
const content = fs.readFileSync(transcript, 'utf8');
|
|
424
|
+
const lines = content.split('\n').filter((line) => line.trim().length > 0);
|
|
425
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
426
|
+
const entry = JSON.parse(lines[index] ?? 'null');
|
|
427
|
+
if (typeof entry !== 'object' || entry === null)
|
|
428
|
+
continue;
|
|
429
|
+
const record = entry;
|
|
430
|
+
const message = record['message'];
|
|
431
|
+
const role = record['type'] === 'assistant' ? 'assistant' : typeof message === 'object' && message !== null ? message['role'] : undefined;
|
|
432
|
+
if (role !== 'assistant')
|
|
433
|
+
continue;
|
|
434
|
+
const body = typeof message === 'object' && message !== null ? message['content'] : record['content'];
|
|
435
|
+
const text = flatten(body);
|
|
436
|
+
if (text)
|
|
437
|
+
return text;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return undefined;
|
|
442
|
+
}
|
|
443
|
+
return undefined;
|
|
444
|
+
}
|
|
445
|
+
offer(child, event, text) {
|
|
446
|
+
this.outbox.offer({ childId: child.id, name: child.name, kind: child.kind, paneId: child.paneId, event, text, at: new Date().toISOString() });
|
|
447
|
+
this.outbox.prune();
|
|
448
|
+
this.outbox.save(this.parentId);
|
|
449
|
+
}
|
|
450
|
+
publish() {
|
|
451
|
+
const pending = this.outbox.pending();
|
|
452
|
+
if (!pending.length)
|
|
453
|
+
return;
|
|
454
|
+
this.onEntries(pending);
|
|
455
|
+
}
|
|
456
|
+
/** Read parent_report lines the children appended to the spool. */
|
|
457
|
+
tailSpool() {
|
|
458
|
+
const file = spoolPath(this.parentId);
|
|
459
|
+
let content;
|
|
460
|
+
try {
|
|
461
|
+
content = fs.readFileSync(file, 'utf8');
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (content.length <= this.spoolOffset)
|
|
467
|
+
return;
|
|
468
|
+
const fresh = content.slice(this.spoolOffset);
|
|
469
|
+
this.spoolOffset = content.length;
|
|
470
|
+
mutateParent(this.parentId, (record) => {
|
|
471
|
+
record.spoolOffset = content.length;
|
|
472
|
+
});
|
|
473
|
+
for (const line of fresh.split('\n')) {
|
|
474
|
+
if (!line.trim())
|
|
475
|
+
continue;
|
|
476
|
+
try {
|
|
477
|
+
const report = JSON.parse(line);
|
|
478
|
+
this.acceptReport(report);
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
this.log('ignored an unreadable spool line');
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
acceptReport(report) {
|
|
486
|
+
const record = readParent(this.parentId);
|
|
487
|
+
const child = record?.children.find((entry) => entry.id === report.childId || entry.name === report.childName);
|
|
488
|
+
if (!child)
|
|
489
|
+
return;
|
|
490
|
+
updateChild(this.parentId, child.id, (entry) => {
|
|
491
|
+
entry.lastReport = { status: report.status, text: report.text, at: report.at, seq: report.seq };
|
|
492
|
+
entry.lastBusyAt = report.at;
|
|
493
|
+
entry.reportPending = true;
|
|
494
|
+
});
|
|
495
|
+
const state = this.states.get(child.id);
|
|
496
|
+
if (state)
|
|
497
|
+
this.states.set(child.id, markReported(state, this.now()));
|
|
498
|
+
const label = report.status === 'needs-input' ? 'needs input' : report.status;
|
|
499
|
+
this.offer(child, 'report', `${child.name} reported ${label}:\n${report.text}`);
|
|
500
|
+
this.publish();
|
|
501
|
+
}
|
|
502
|
+
async tick() {
|
|
503
|
+
if (this.stopped)
|
|
504
|
+
return;
|
|
505
|
+
this.tailSpool();
|
|
506
|
+
const record = readParent(this.parentId);
|
|
507
|
+
const children = (record?.children ?? []).filter((child) => !child.exitedAt);
|
|
508
|
+
// A new child, or one that left, changes the set of panes to watch. The
|
|
509
|
+
// tick reads only the local registry, so the steady state stays at zero
|
|
510
|
+
// herdr calls.
|
|
511
|
+
if (paneKey(children) !== this.subscribedKey) {
|
|
512
|
+
await this.reconcileAndSubscribe();
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
await this.evaluate();
|
|
516
|
+
if (!this.subscription)
|
|
517
|
+
this.scheduleReconnect();
|
|
518
|
+
}
|
|
519
|
+
age(since, now = this.now()) {
|
|
520
|
+
const seconds = Math.max(0, Math.round((now - since) / 1000));
|
|
521
|
+
if (seconds < 90)
|
|
522
|
+
return `${seconds}s`;
|
|
523
|
+
const minutes = Math.round(seconds / 60);
|
|
524
|
+
if (minutes < 90)
|
|
525
|
+
return `${minutes} min`;
|
|
526
|
+
return `${Math.round(minutes / 60)} h`;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function flatten(value) {
|
|
530
|
+
if (typeof value === 'string')
|
|
531
|
+
return value;
|
|
532
|
+
if (Array.isArray(value)) {
|
|
533
|
+
const parts = value.map((entry) => (typeof entry === 'string' ? entry : typeof entry === 'object' && entry !== null && typeof entry['text'] === 'string' ? String(entry['text']) : '')).filter(Boolean);
|
|
534
|
+
return parts.length ? parts.join('\n') : undefined;
|
|
535
|
+
}
|
|
536
|
+
return undefined;
|
|
537
|
+
}
|
|
538
|
+
function trim(value, limit = 3000) {
|
|
539
|
+
return value.trim().slice(-limit);
|
|
540
|
+
}
|
|
541
|
+
/** Read a byte range of a file, for the part appended since the last look. */
|
|
542
|
+
function readRange(file, from, to) {
|
|
543
|
+
const length = to - from;
|
|
544
|
+
if (length <= 0)
|
|
545
|
+
return '';
|
|
546
|
+
const fd = fs.openSync(file, 'r');
|
|
547
|
+
try {
|
|
548
|
+
const buffer = Buffer.alloc(length);
|
|
549
|
+
fs.readSync(fd, buffer, 0, length, from);
|
|
550
|
+
return buffer.toString('utf8');
|
|
551
|
+
}
|
|
552
|
+
finally {
|
|
553
|
+
fs.closeSync(fd);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Whether appended transcript bytes show the agent working. A session file also
|
|
558
|
+
* collects entries an extension writes, and this machine's `pi-cpu-sample`
|
|
559
|
+
* appends one every thirty seconds, so file size alone says nothing. Only an
|
|
560
|
+
* entry that is not a `custom` one counts as the conversation moving.
|
|
561
|
+
*/
|
|
562
|
+
function conversationGrowth(added) {
|
|
563
|
+
for (const line of added.split('\n')) {
|
|
564
|
+
if (!line.trim())
|
|
565
|
+
continue;
|
|
566
|
+
try {
|
|
567
|
+
const entry = JSON.parse(line);
|
|
568
|
+
if (entry['type'] !== 'custom')
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
// A half-written line is not evidence of work either way.
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* herdr names an event in a subscription request with dots and sends the frame
|
|
579
|
+
* with underscores, so both spellings are accepted here. A tab close arrives
|
|
580
|
+
* as `tab_closed` and names the tab rather than the pane.
|
|
581
|
+
*/
|
|
582
|
+
const CLOSE_EVENTS = new Set(['pane.exited', 'pane_exited', 'pane.closed', 'pane_closed', 'tab.closed', 'tab_closed']);
|
|
583
|
+
const STATUS_EVENTS = new Set(['pane.agent_status_changed', 'pane_agent_status_changed']);
|
|
584
|
+
/** How often to ask herdr for a child's session when no transcript is known. */
|
|
585
|
+
const TRANSCRIPT_LOOK_INTERVAL_MS = 60_000;
|
|
586
|
+
/** The set of panes the subscription must cover, as one comparable string. */
|
|
587
|
+
function paneKey(children) {
|
|
588
|
+
return children
|
|
589
|
+
.filter((child) => !child.exitedAt && child.paneId)
|
|
590
|
+
.map((child) => `${child.paneId}:${child.harness === 'other' ? 'raw' : 'agent'}`)
|
|
591
|
+
.sort()
|
|
592
|
+
.join(',');
|
|
593
|
+
}
|