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