@elecnix/bellwether 0.1.2 → 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.
@@ -7,11 +7,16 @@
7
7
  // happened in between. After a disconnect the watcher takes a fresh snapshot
8
8
  // for the same reason.
9
9
  import fs from 'node:fs';
10
- import { DEFAULT_LIMITS, advance, initialState, markReported } from './classifier.js';
10
+ import { DEFAULT_LIMITS, advance, limitsFor, markReported, seedFor } from './classifier.js';
11
+ import { LOCAL_HOST, hostOf } from './machine.js';
11
12
  import { Outbox } from './outbox.js';
12
13
  import { mutateParent, readParent, updateChild } from './registry.js';
13
- import { resolveTranscript, sessionValueFrom } from './transcript.js';
14
+ import { DIALOG_NAMES, detectDialog, watchStartup } from './startup-dialogs.js';
15
+ import { resolveTranscript, sessionFrom } from './transcript.js';
16
+ import { removeChildFiles } from './mcp-config.js';
17
+ import { childLabel } from './label.js';
14
18
  import { spoolPath } from './paths.js';
19
+ import { realRetireOps, reapChild, retirementPending } from './retire.js';
15
20
  /** herdr's status for a pane, or the child's last known status. */
16
21
  function isRecord(value) {
17
22
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -21,7 +26,7 @@ function statusOf(pane, fallback) {
21
26
  return typeof value === 'string' && ['idle', 'working', 'blocked', 'done', 'unknown'].includes(value) ? value : fallback;
22
27
  }
23
28
  export class Watcher {
24
- client;
29
+ clientFor;
25
30
  parentId;
26
31
  limits;
27
32
  onEntries;
@@ -29,20 +34,27 @@ export class Watcher {
29
34
  tickMs;
30
35
  screenPollMs;
31
36
  log;
37
+ retireOps;
38
+ retireBusy;
39
+ /** Retirements in flight, so an exit event and a start never clean the same child at once. */
40
+ retiring = new Map();
32
41
  outbox;
33
42
  states = new Map();
34
43
  screenReadAt = new Map();
35
44
  transcriptSizes = new Map();
36
45
  transcriptLookAt = new Map();
37
46
  controller;
38
- subscription;
39
- subscribedKey = '';
47
+ /** One subscription per herdr host, since pane ids are scoped to one server. */
48
+ links = new Map();
49
+ /** When a host that failed may be tried again, so a dead machine is not dialled every tick. */
50
+ retryAt = new Map();
40
51
  ticker;
41
52
  reconnecting = false;
42
53
  spoolOffset = 0;
43
54
  stopped = true;
44
55
  constructor(options) {
45
- this.client = options.client;
56
+ const local = options.client;
57
+ this.clientFor = options.clientFor ?? ((host) => (host === LOCAL_HOST ? Promise.resolve(local) : Promise.reject(new Error(`no herdr client for host ${host}`))));
46
58
  this.parentId = options.parentId;
47
59
  this.limits = options.limits ?? DEFAULT_LIMITS;
48
60
  this.onEntries = options.onEntries;
@@ -50,6 +62,8 @@ export class Watcher {
50
62
  this.tickMs = options.tickMs ?? 5_000;
51
63
  this.screenPollMs = options.screenPollMs ?? 30_000;
52
64
  this.log = options.log ?? (() => { });
65
+ this.retireOps = options.retireOps ?? realRetireOps();
66
+ this.retireBusy = { retries: options.retireBusyRetries, delayMs: options.retireBusyDelayMs };
53
67
  this.outbox = Outbox.load(this.parentId);
54
68
  }
55
69
  start() {
@@ -63,25 +77,93 @@ export class Watcher {
63
77
  this.ticker = setInterval(() => void this.tick(), this.tickMs);
64
78
  this.ticker.unref?.();
65
79
  void this.reconcileAndSubscribe();
80
+ // A daemon that stopped part of the way through a retirement finishes it.
81
+ for (const child of readParent(this.parentId)?.children ?? []) {
82
+ if (child.exitedAt && retirementPending(child))
83
+ void this.retire(child.id);
84
+ }
85
+ }
86
+ /** Wait for the retirements in flight, for a test or a drain. */
87
+ async retirements() {
88
+ await Promise.all([...this.retiring.values()]);
89
+ }
90
+ /**
91
+ * Clean up after a child that asked to be retired, once it has exited. The
92
+ * cleanup itself refuses anything still alive or out of bounds.
93
+ */
94
+ retire(childId) {
95
+ const running = this.retiring.get(childId);
96
+ if (running)
97
+ return running;
98
+ const job = reapChild(this.parentId, childId, {
99
+ ops: this.retireOps,
100
+ paneOrTabLive: (child) => this.paneOrTabLive(child),
101
+ log: this.log,
102
+ busyRetries: this.retireBusy.retries,
103
+ busyDelayMs: this.retireBusy.delayMs,
104
+ })
105
+ .then(() => undefined)
106
+ .catch((error) => this.log(`retirement of ${childId} failed: ${String(error)}`))
107
+ .finally(() => this.retiring.delete(childId));
108
+ this.retiring.set(childId, job);
109
+ return job;
110
+ }
111
+ /** Whether herdr still lists the child's pane, or any pane in its tab. */
112
+ async paneOrTabLive(child) {
113
+ const client = await this.clientFor(hostOf(child));
114
+ const result = await client.request('pane.list', {});
115
+ const panes = isRecord(result) && Array.isArray(result['panes']) ? result['panes'] : [];
116
+ return panes.some((pane) => (child.paneId && pane['pane_id'] === child.paneId) || (child.tabId && pane['tab_id'] === child.tabId));
66
117
  }
67
118
  stop() {
68
119
  this.stopped = true;
69
120
  if (this.ticker)
70
121
  clearInterval(this.ticker);
71
122
  this.ticker = undefined;
72
- this.subscription?.close();
73
- this.subscription = undefined;
123
+ for (const link of this.links.values())
124
+ link.subscription.close();
125
+ this.links.clear();
74
126
  this.controller?.abort();
75
127
  this.controller = undefined;
76
128
  }
129
+ /**
130
+ * Forget what the watcher measured for a child, for one that comes back in a
131
+ * new pane: its classifier state and baselines belong to the old one.
132
+ */
133
+ reset(childId) {
134
+ this.states.delete(childId);
135
+ this.screenReadAt.delete(childId);
136
+ this.transcriptSizes.delete(childId);
137
+ this.transcriptLookAt.delete(childId);
138
+ this.lastScreen.delete(childId);
139
+ }
77
140
  outboxEntries() {
78
141
  return this.outbox.all();
79
142
  }
143
+ /**
144
+ * Unread entries ready to deliver, after any a newer child state made stale
145
+ * has been settled. A reconnect replays these, so it never replays a dialog
146
+ * someone already answered.
147
+ */
148
+ pendingEntries() {
149
+ this.settleStale();
150
+ return this.outbox.pending();
151
+ }
80
152
  markRead(receipt) {
81
153
  if (!this.outbox.markRead(receipt))
82
154
  return;
83
155
  this.outbox.save(this.parentId);
84
156
  }
157
+ /** Forget a child whose spawn failed: no state, and no event left to send. */
158
+ forget(childId) {
159
+ this.states.delete(childId);
160
+ this.screenReadAt.delete(childId);
161
+ this.transcriptSizes.delete(childId);
162
+ this.transcriptLookAt.delete(childId);
163
+ this.lastScreen.delete(childId);
164
+ if (this.outbox.drop(childId))
165
+ this.outbox.save(this.parentId);
166
+ }
85
167
  /** Record that a receipt has been sent to the parent, so a burst is sent once. */
86
168
  markDelivered(receipt) {
87
169
  this.outbox.markDelivered(receipt);
@@ -99,62 +181,82 @@ export class Watcher {
99
181
  const signal = this.controller?.signal;
100
182
  if (!signal)
101
183
  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;
184
+ const record = readParent(this.parentId);
185
+ const byHost = groupByHost((record?.children ?? []).filter((child) => !child.exitedAt));
186
+ // A host whose last child left needs no subscription.
187
+ for (const [host, link] of this.links) {
188
+ if (byHost.has(host))
189
+ continue;
190
+ link.subscription.close();
191
+ this.links.delete(host);
192
+ }
193
+ let failed = false;
194
+ for (const [host, children] of byHost) {
195
+ if ((this.retryAt.get(host)?.at ?? 0) > Date.now())
196
+ continue;
197
+ try {
198
+ const client = await this.clientFor(host);
199
+ const live = await this.livePanes(client, signal);
200
+ const addressable = [];
201
+ for (const child of children) {
202
+ // A record written a moment ago may predate its pane. Leave it be.
203
+ if (!child.paneId || Date.now() - Date.parse(child.startedAt) < 15_000 || live.has(child.paneId)) {
204
+ if (child.paneId)
205
+ addressable.push(child);
206
+ continue;
207
+ }
208
+ this.markExited(child, undefined);
115
209
  }
116
- this.markExited(child, undefined);
210
+ await this.ensureSubscription(host, client, addressable, signal);
211
+ await this.reconcile(client, addressable, signal);
212
+ this.retryAt.delete(host);
213
+ }
214
+ catch (error) {
215
+ const delay = Math.min((this.retryAt.get(host)?.delay ?? 500) * 2, 60_000);
216
+ this.retryAt.set(host, { at: Date.now() + delay, delay });
217
+ // One unreachable host must not silence the children on the others.
218
+ this.log(`reconcile failed on ${host}: ${String(error)}`);
219
+ this.links.get(host)?.subscription.close();
220
+ this.links.delete(host);
221
+ failed = true;
117
222
  }
118
- await this.ensureSubscription(addressable, signal);
119
- await this.reconcile(addressable, signal);
120
- this.publish();
121
223
  }
122
- catch (error) {
123
- this.log(`reconcile failed: ${String(error)}`);
124
- this.subscribedKey = '';
224
+ this.publish();
225
+ if (failed)
125
226
  this.scheduleReconnect();
126
- }
127
227
  }
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
- }
228
+ /**
229
+ * Every pane id one herdr currently knows about. A failure throws, because
230
+ * an empty answer would read as every child having exited.
231
+ */
232
+ async livePanes(client, signal) {
233
+ const result = await client.request('pane.list', {}, { signal });
234
+ const list = isRecord(result) && Array.isArray(result['panes']) ? result['panes'] : [];
235
+ return new Set(list.map((pane) => pane['pane_id']).filter((id) => typeof id === 'string'));
139
236
  }
140
237
  markExited(child, code) {
238
+ // The session and transcript stay on the record, so a retired child can
239
+ // still be resumed.
141
240
  updateChild(this.parentId, child.id, (entry) => {
142
241
  entry.exitedAt = new Date().toISOString();
143
242
  entry.exitCode = code;
144
243
  entry.lastStatus = 'unknown';
145
244
  });
146
- this.offer(child, 'exited', this.describeExit(child.name, code));
245
+ removeChildFiles(child.id);
246
+ this.offer(child, 'exited', this.describeExit(child, code));
247
+ void this.retire(child.id);
147
248
  }
148
249
  /**
149
250
  * herdr's status subscriptions are per pane, so the subscription is rebuilt
150
251
  * whenever the set of child panes changes.
151
252
  */
152
- async ensureSubscription(children, signal) {
253
+ async ensureSubscription(host, client, children, signal) {
153
254
  const key = paneKey(children);
154
- if (key === this.subscribedKey && this.subscription)
255
+ const current = this.links.get(host);
256
+ if (current && current.key === key)
155
257
  return;
156
- this.subscription?.close();
157
- this.subscription = undefined;
258
+ current?.subscription.close();
259
+ this.links.delete(host);
158
260
  const subscriptions = [
159
261
  { type: 'pane.exited' },
160
262
  { type: 'pane.closed' },
@@ -164,12 +266,13 @@ export class Watcher {
164
266
  { type: 'pane.agent_detected' },
165
267
  ...children.filter((child) => !child.exitedAt).map((child) => ({ type: 'pane.agent_status_changed', pane_id: child.paneId })),
166
268
  ];
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 = '';
269
+ const subscription = await client.subscribe(subscriptions, (event) => void this.onHerdrEvent(host, event), signal);
270
+ this.links.set(host, { subscription, key });
271
+ this.log(`subscribed to ${children.length} child pane(s) on ${host}`);
272
+ void subscription.closed.catch((error) => {
273
+ this.log(`subscription lost on ${host}: ${String(error)}`);
274
+ if (this.links.get(host)?.subscription === subscription)
275
+ this.links.delete(host);
173
276
  this.scheduleReconnect();
174
277
  });
175
278
  }
@@ -192,35 +295,42 @@ export class Watcher {
192
295
  };
193
296
  setTimeout(attempt, delay).unref?.();
194
297
  }
195
- async onHerdrEvent(event) {
298
+ async onHerdrEvent(host, event) {
196
299
  const paneId = typeof event.data['pane_id'] === 'string' ? event.data['pane_id'] : undefined;
197
300
  const tabId = typeof event.data['tab_id'] === 'string' ? event.data['tab_id'] : undefined;
198
301
  if (!paneId && !tabId) {
199
302
  if (event.event === 'events.lost' || event.event === 'events_lost') {
200
- this.log('herdr reported lost events; resubscribing');
201
- this.subscribedKey = '';
303
+ this.log(`herdr on ${host} reported lost events; resubscribing`);
304
+ this.dropLink(host);
202
305
  void this.reconcileAndSubscribe();
203
306
  }
204
307
  return;
205
308
  }
206
309
  const record = readParent(this.parentId);
207
310
  // 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));
311
+ const child = record?.children.find((entry) => hostOf(entry) === host && ((paneId !== undefined && entry.paneId === paneId) || (tabId !== undefined && entry.tabId === tabId)));
209
312
  if (!child)
210
313
  return;
211
314
  if (CLOSE_EVENTS.has(event.event)) {
212
315
  const code = typeof event.data['exit_code'] === 'number' ? event.data['exit_code'] : undefined;
213
316
  this.markExited(child, code);
214
317
  // The subscription named that pane, so it has to be rebuilt without it.
215
- this.subscribedKey = '';
318
+ this.dropLink(host);
216
319
  void this.reconcileAndSubscribe();
217
320
  return;
218
321
  }
219
322
  if (STATUS_EVENTS.has(event.event)) {
220
323
  const status = statusOf(event.data, child.lastStatus);
324
+ const stateSeq = typeof event.data['state_change_seq'] === 'number' ? event.data['state_change_seq'] : undefined;
221
325
  updateChild(this.parentId, child.id, (entry) => {
222
- if (entry.lastStatus !== status)
326
+ if (entry.lastStatus !== status) {
223
327
  entry.statusChangedAt = new Date().toISOString();
328
+ // herdr 0.9.5 sends no state_change_seq on this event, so a seq
329
+ // read before the change no longer describes the status.
330
+ entry.stateChangeSeq = stateSeq;
331
+ }
332
+ else if (stateSeq !== undefined)
333
+ entry.stateChangeSeq = stateSeq;
224
334
  entry.lastStatus = status;
225
335
  });
226
336
  // Read the registry again rather than reusing the copy taken above,
@@ -231,18 +341,22 @@ export class Watcher {
231
341
  if (event.event === 'pane.agent_detected') {
232
342
  const signal = this.controller?.signal;
233
343
  if (signal)
234
- await this.reconcile(record?.children ?? [], signal);
344
+ await this.reconcile(await this.clientFor(host), (record?.children ?? []).filter((entry) => hostOf(entry) === host), signal);
235
345
  }
236
346
  }
347
+ dropLink(host) {
348
+ this.links.get(host)?.subscription.close();
349
+ this.links.delete(host);
350
+ }
237
351
  /** Read the live status of every child and fold it into the classifier. */
238
- async reconcile(children, signal) {
352
+ async reconcile(client, children, signal) {
239
353
  if (!children.length)
240
354
  return;
241
355
  let panes = [];
242
356
  let agents = [];
243
357
  try {
244
358
  // session.snapshot answers {type, snapshot: {panes, agents, tabs, ...}}.
245
- const result = await this.client.snapshot(signal);
359
+ const result = await client.snapshot(signal);
246
360
  const snapshot = isRecord(result['snapshot']) ? result['snapshot'] : result;
247
361
  const paneList = snapshot['panes'] ?? snapshot['pane_list'];
248
362
  panes = Array.isArray(paneList) ? paneList : [];
@@ -267,13 +381,25 @@ export class Watcher {
267
381
  continue;
268
382
  const status = statusOf(pane, child.lastStatus);
269
383
  const seq = typeof pane['completion_seq'] === 'number' ? pane['completion_seq'] : undefined;
270
- if (status !== child.lastStatus || (seq !== undefined && seq !== child.completionSeq)) {
384
+ const stateSeq = typeof pane['state_change_seq'] === 'number' ? pane['state_change_seq'] : undefined;
385
+ const session = sessionFrom(pane['agent_session']);
386
+ const sessionChanged = session !== undefined && (session.value !== child.session?.value || session.kind !== child.session?.kind);
387
+ if (status !== child.lastStatus || (seq !== undefined && seq !== child.completionSeq) || (stateSeq !== undefined && stateSeq !== child.stateChangeSeq) || sessionChanged) {
271
388
  updateChild(this.parentId, child.id, (entry) => {
389
+ const at = new Date().toISOString();
272
390
  if (entry.lastStatus !== status)
273
- entry.statusChangedAt = new Date().toISOString();
391
+ entry.statusChangedAt = at;
392
+ // A new turn is activity even when the status did not change. The
393
+ // record keeps it, so a restarted parent does not lose the period.
394
+ if (seq !== undefined && seq !== entry.completionSeq)
395
+ entry.lastBusyAt = at;
274
396
  entry.lastStatus = status;
275
397
  if (seq !== undefined)
276
398
  entry.completionSeq = seq;
399
+ if (stateSeq !== undefined)
400
+ entry.stateChangeSeq = stateSeq;
401
+ if (session)
402
+ entry.session = session;
277
403
  });
278
404
  }
279
405
  }
@@ -291,15 +417,29 @@ export class Watcher {
291
417
  for (const child of record.children) {
292
418
  if (child.exitedAt)
293
419
  continue;
294
- const state = this.states.get(child.id) ?? initialState(child.lastStatus, now);
420
+ // The spawn is answering this child's startup dialogs. Its first state
421
+ // is read once the spawn is done.
422
+ if (child.startingUntil && Date.parse(child.startingUntil) > Date.now()) {
423
+ this.states.delete(child.id);
424
+ continue;
425
+ }
426
+ if (child.lastStatus !== 'blocked')
427
+ this.gaveUp.delete(child.id);
428
+ const state = this.states.get(child.id) ?? seedFor(child, now);
295
429
  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);
430
+ // A spawn can set its own stuck and inactivity thresholds. The stuck one
431
+ // is what the lab uses to reach that event in seconds rather than minutes.
432
+ const { state: next, event } = advance(state, { status: child.lastStatus, completionSeq: child.completionSeq, busy }, now, limitsFor(child, this.limits));
300
433
  this.states.set(child.id, next);
301
434
  if (!event)
302
435
  continue;
436
+ if (event === 'inactive') {
437
+ // Written before the offer, so a restart cannot send the same period again.
438
+ const notifiedFor = new Date(next.lastActivityAt).toISOString();
439
+ updateChild(this.parentId, child.id, (entry) => {
440
+ entry.inactiveNotifiedFor = notifiedFor;
441
+ });
442
+ }
303
443
  // A report for this turn already told the parent everything the idle
304
444
  // event would say, so keep the one message.
305
445
  if (event === 'idle' && child.reportPending) {
@@ -313,10 +453,57 @@ export class Watcher {
313
453
  this.states.set(child.id, markReported(next, now));
314
454
  continue;
315
455
  }
316
- this.offer(child, event, await this.describe(child, event, next.lastBusyAt, now));
456
+ if (event === 'blocked') {
457
+ const dialog = await this.clientFor(hostOf(child))
458
+ .then((client) => client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }))
459
+ .catch(() => '');
460
+ if (this.answerStartupDialog(child, dialog))
461
+ continue;
462
+ this.offer(child, event, this.describeBlocked(child, dialog));
463
+ continue;
464
+ }
465
+ const quietSince = event === 'inactive' ? next.lastActivityAt : next.lastBusyAt;
466
+ this.offer(child, event, await this.describe(child, event, quietSince, now));
317
467
  }
318
468
  this.publish();
319
469
  }
470
+ answering = new Set();
471
+ /** Children whose startup dialog outlasted its wait in this blocked spell. */
472
+ gaveUp = new Set();
473
+ /**
474
+ * A Claude Code startup dialog on a child's screen is Bellwether's to
475
+ * answer, never the operator's: a resumed session shows the development
476
+ * channel question again, long after its spawn returned. Answer it here and
477
+ * publish nothing. Returns false for any other dialog, and for one whose
478
+ * answer already failed, which then reaches the parent as blocked.
479
+ */
480
+ answerStartupDialog(child, screen) {
481
+ const dialog = detectDialog(screen);
482
+ if (!dialog || child.kind !== 'claude' || this.gaveUp.has(child.id))
483
+ return false;
484
+ if (this.answering.has(child.id))
485
+ return true;
486
+ this.answering.add(child.id);
487
+ this.log(`${child.name} is on ${DIALOG_NAMES[dialog]}; answering it`);
488
+ void (async () => {
489
+ const watch = await watchStartup(await this.clientFor(hostOf(child)), child.paneId, this.controller?.signal);
490
+ try {
491
+ await watch.answer();
492
+ }
493
+ finally {
494
+ watch.close();
495
+ }
496
+ })()
497
+ .catch((error) => {
498
+ this.log(`answering ${child.name}'s startup dialog failed: ${String(error)}`);
499
+ this.gaveUp.add(child.id);
500
+ const state = this.states.get(child.id);
501
+ if (state)
502
+ this.states.set(child.id, { ...state, firedBlocked: undefined });
503
+ })
504
+ .finally(() => this.answering.delete(child.id));
505
+ return true;
506
+ }
320
507
  /**
321
508
  * The child's transcript. A spawn can finish before herdr has detected the
322
509
  * agent, so the path is resolved lazily rather than only at spawn time.
@@ -324,6 +511,9 @@ export class Watcher {
324
511
  async transcriptFor(child) {
325
512
  if (child.transcript)
326
513
  return child.transcript;
514
+ // A remote child's transcript sits on its own machine's disk.
515
+ if (hostOf(child) !== LOCAL_HOST)
516
+ return undefined;
327
517
  // A child whose harness keeps no transcript would otherwise cost one
328
518
  // herdr call per tick forever. Look again once a minute at most, because
329
519
  // herdr can report the session a little after the spawn returns.
@@ -332,12 +522,16 @@ export class Watcher {
332
522
  return undefined;
333
523
  this.transcriptLookAt.set(child.id, this.now());
334
524
  try {
335
- const result = await this.client.request('agent.get', { target: child.paneId });
525
+ const result = await (await this.clientFor(LOCAL_HOST)).request('agent.get', { target: child.paneId });
336
526
  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)
527
+ const session = sessionFrom(record?.['agent_session']);
528
+ const path = resolveTranscript(child.harness, session?.value, child.cwd);
529
+ if (path || session)
339
530
  updateChild(this.parentId, child.id, (entry) => {
340
- entry.transcript = path;
531
+ if (path)
532
+ entry.transcript = path;
533
+ if (session)
534
+ entry.session = session;
341
535
  });
342
536
  return path;
343
537
  }
@@ -375,7 +569,7 @@ export class Watcher {
375
569
  return false;
376
570
  this.screenReadAt.set(child.id, now);
377
571
  try {
378
- const screen = await this.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 });
572
+ const screen = await (await this.clientFor(hostOf(child))).paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines: 40 });
379
573
  const lines = screen.split('\n').filter((line) => line.trim().length > 0 && !/⏱|\[\d+% ·/.test(line));
380
574
  const previous = this.lastScreen.get(child.id);
381
575
  this.lastScreen.set(child.id, lines.join('\n'));
@@ -396,23 +590,32 @@ export class Watcher {
396
590
  async describe(child, event, quietSince, now) {
397
591
  const age = this.age(Date.parse(child.startedAt));
398
592
  if (event === 'exited')
399
- return this.describeExit(child.name, child.exitCode);
593
+ return this.describeExit(child, child.exitCode);
400
594
  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.`;
595
+ const dialog = await this.clientFor(hostOf(child))
596
+ .then((client) => client.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }))
597
+ .catch(() => '');
598
+ return this.describeBlocked(child, dialog);
403
599
  }
404
600
  // Measure the quiet period on the classifier's own clock. The registry's
405
601
  // lastBusyAt can be written by another process that only sees file size.
406
602
  if (event === 'stuck')
407
- return `${child.name} has been quiet for ${this.age(quietSince, now)}. Last screen lines:\n${trim(await this.screenTail(child))}`;
603
+ return `${childLabel(child)} has been quiet for ${this.age(quietSince, now)}. Last screen lines:\n${trim(await this.screenTail(child))}`;
604
+ if (event === 'inactive')
605
+ return `${childLabel(child)} has shown no activity for ${this.age(quietSince, now)}, and its status is ${child.lastStatus}. Last screen lines:\n${trim(await this.screenTail(child))}`;
408
606
  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.'}`;
607
+ return `${childLabel(child)} went idle after ${age}:${text ? `\n${text}` : ' no message and no readable screen.'}`;
410
608
  }
411
- describeExit(name, code) {
412
- return `${name} exited${code === undefined ? '' : ` with code ${code}`}.`;
609
+ describeBlocked(child, dialog) {
610
+ return `${childLabel(child)} is blocked on a dialog after ${this.age(Date.parse(child.startedAt))}. The dialog:\n${trim(dialog)}\n\nAnswer it with agent_send keys, or answer the card your-attention posted.`;
611
+ }
612
+ describeExit(child, code) {
613
+ return `${childLabel(child)} exited${code === undefined ? '' : ` with code ${code}`}.`;
413
614
  }
414
615
  async screenTail(child, lines = 40) {
415
- return this.client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines }).catch(() => '');
616
+ return this.clientFor(hostOf(child))
617
+ .then((client) => client.paneRead({ paneId: child.paneId, source: 'recent_unwrapped', lines }))
618
+ .catch(() => '');
416
619
  }
417
620
  /** The child's last assistant message, read from its transcript. */
418
621
  async lastMessage(child) {
@@ -443,15 +646,29 @@ export class Watcher {
443
646
  return undefined;
444
647
  }
445
648
  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() });
649
+ const state = event === 'blocked' || event === 'stuck' || event === 'idle' ? { status: child.lastStatus, stateChangeSeq: child.stateChangeSeq } : {};
650
+ this.outbox.offer({ childId: child.id, name: child.name, kind: child.kind, paneId: child.paneId, event, text, at: new Date().toISOString(), ...state });
447
651
  this.outbox.prune();
448
652
  this.outbox.save(this.parentId);
449
653
  }
654
+ /** Settle the entries a newer child state made stale, against the registry as it is now. */
655
+ settleStale() {
656
+ const children = readParent(this.parentId)?.children ?? [];
657
+ if (this.outbox.settleSuperseded(children).length)
658
+ this.outbox.save(this.parentId);
659
+ }
660
+ /**
661
+ * Hand the adapter every unread entry, plus each entry settled without a
662
+ * receipt since the last call, marked read, so a client holding one drops
663
+ * it instead of sending it again.
664
+ */
450
665
  publish() {
666
+ this.settleStale();
667
+ const settled = this.outbox.takeSettled();
451
668
  const pending = this.outbox.pending();
452
- if (!pending.length)
669
+ if (!pending.length && !settled.length)
453
670
  return;
454
- this.onEntries(pending);
671
+ this.onEntries([...settled, ...pending]);
455
672
  }
456
673
  /** Read parent_report lines the children appended to the spool. */
457
674
  tailSpool() {
@@ -496,7 +713,7 @@ export class Watcher {
496
713
  if (state)
497
714
  this.states.set(child.id, markReported(state, this.now()));
498
715
  const label = report.status === 'needs-input' ? 'needs input' : report.status;
499
- this.offer(child, 'report', `${child.name} reported ${label}:\n${report.text}`);
716
+ this.offer(child, 'report', `${childLabel(child)} reported ${label}:\n${report.text}`);
500
717
  this.publish();
501
718
  }
502
719
  async tick() {
@@ -504,17 +721,17 @@ export class Watcher {
504
721
  return;
505
722
  this.tailSpool();
506
723
  const record = readParent(this.parentId);
507
- const children = (record?.children ?? []).filter((child) => !child.exitedAt);
724
+ const byHost = groupByHost((record?.children ?? []).filter((child) => !child.exitedAt));
508
725
  // A new child, or one that left, changes the set of panes to watch. The
509
726
  // tick reads only the local registry, so the steady state stays at zero
510
727
  // herdr calls.
511
- if (paneKey(children) !== this.subscribedKey) {
728
+ const due = (host) => (this.retryAt.get(host)?.at ?? 0) <= Date.now();
729
+ const changed = [...byHost].some(([host, children]) => due(host) && this.links.get(host)?.key !== paneKey(children)) || [...this.links.keys()].some((host) => !byHost.has(host));
730
+ if (changed) {
512
731
  await this.reconcileAndSubscribe();
513
732
  return;
514
733
  }
515
734
  await this.evaluate();
516
- if (!this.subscription)
517
- this.scheduleReconnect();
518
735
  }
519
736
  age(since, now = this.now()) {
520
737
  const seconds = Math.max(0, Math.round((now - since) / 1000));
@@ -583,6 +800,17 @@ const CLOSE_EVENTS = new Set(['pane.exited', 'pane_exited', 'pane.closed', 'pane
583
800
  const STATUS_EVENTS = new Set(['pane.agent_status_changed', 'pane_agent_status_changed']);
584
801
  /** How often to ask herdr for a child's session when no transcript is known. */
585
802
  const TRANSCRIPT_LOOK_INTERVAL_MS = 60_000;
803
+ /** Live children grouped by the herdr host they run on. */
804
+ function groupByHost(children) {
805
+ const groups = new Map();
806
+ for (const child of children) {
807
+ const host = hostOf(child);
808
+ const group = groups.get(host) ?? [];
809
+ group.push(child);
810
+ groups.set(host, group);
811
+ }
812
+ return groups;
813
+ }
586
814
  /** The set of panes the subscription must cover, as one comparable string. */
587
815
  function paneKey(children) {
588
816
  return children