@linxin666/dsh-remote-bridge 0.4.11 → 0.4.12

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.
@@ -1,32 +1,44 @@
1
1
  /**
2
- * When a finished turn may be announced: after the session it belongs to falls
2
+ * When a finished turn may be announced: after the family it belongs to falls
3
3
  * quiet, not when the frame arrives.
4
4
  *
5
5
  * A `turn/end` increment is a fact about one turn and nothing more. The work the
6
- * user started with it may still be going: the child sessions it delegated to and
7
- * the background jobs the host still holds under those sessions outlive the turn
8
- * that started them. A phone told "turn finished" at the frame wakes on a session
9
- * the roster still badges as running, reads a card that says ended while the work
10
- * goes on, and is told again by a second turn end it never asked for. §28's
11
- * notification and §29's card answer the same question — "is this session working
12
- * right now" — and that question has one answer, the one the client already
13
- * computes in `SessionRun`: the host's own `agentRunning` for the session, any
14
- * descendant session still running, and any job the host attributes to either.
6
+ * user started with it may still be going: the subagent sessions the host spawned
7
+ * under it at any depth, and the background jobs the host still holds under any of
8
+ * them, outlive the turn that started them. A phone told "turn finished" at the
9
+ * frame wakes on a roster that still badges a session running, reads a card that
10
+ * says ended while the work goes on, and is told again by a second turn end it
11
+ * never asked for. §28's notification and §29's card answer the same question — "is
12
+ * this work still going" — and that question has one answer, the family's.
15
13
  *
16
- * So a turn end is registered here instead of sent, and sent once the host says
17
- * the session is quiet. Three rules hold that together:
14
+ * The family is the root a session's parent chain climbs to, plus every session
15
+ * under that root at any depth. A leaf session's own turn end therefore waits for
16
+ * the root and for the siblings and cousins it shares that root with, which is the
17
+ * work the user actually started. So a turn end is registered here instead of sent,
18
+ * and sent once the host says the family is quiet. Three rules hold that together:
18
19
  *
19
- * - the answer comes from the host and nowhere else: one `session/list` read for
20
- * the running flag and the parent chain, and the host's job registry for the
21
- * jobs it attributes to a session. This module invents no timer-based guess and
22
- * reads no client state, because a guess that says "quiet" is a lock screen
23
- * saying the work finished when it did not;
20
+ * - the answer comes from the host and nowhere else: one `session/list` read for the
21
+ * running flags, the parent chain and each session's origin, and the host's job
22
+ * registry for the jobs it attributes to a session. This module invents no
23
+ * timer-based guess and reads no client state, because a guess that says "quiet"
24
+ * is a lock screen saying the work finished when it did not;
24
25
  * - nothing on the frame path waits: a registration stores five fields and arms a
25
26
  * timer, so a follow stream still publishes its increment at the speed it did
26
27
  * before;
27
- * - the wait is bounded. At {@link TURN_END_QUIET_MAX_MS} the announcement goes
28
- * out anyway and the line it logs names what was still going, because a
29
- * notification that never arrives is the failure this channel exists to prevent.
28
+ * - the wait has no deadline. A family that stays busy is never announced, and a
29
+ * host that cannot answer is asked again rather than read as quiet: announcing
30
+ * work that is still running is the failure this channel exists to prevent, and a
31
+ * notification that never arrives is the lesser one. One question, though, is
32
+ * bounded ({@link TURN_END_QUIET_PROBE_TIMEOUT_MS}): a read the gateway never
33
+ * returns is abandoned as that question's own failure and the entry asks again, so
34
+ * a stuck call cannot leave the entry holding no question to ask and no way to
35
+ * speak. One line at {@link TURN_END_QUIET_REPORT_MS} says the bridge is still
36
+ * waiting, so an operator is not left guessing why a phone stayed silent.
37
+ *
38
+ * Not every turn end is the phone's to hear. A session the host spawned as a
39
+ * subagent (`origin: "subagent"`) ends turns nobody asked this bridge about, so its
40
+ * turn end is dropped on its first answer unless the phone itself prompted that
41
+ * session over the wire.
30
42
  * @module dsh-remote-bridge/core/turn-end-quiet
31
43
  */
32
44
 
@@ -36,29 +48,68 @@ import type { LiveActivityNotifier } from './liveactivity.ts'
36
48
  import { pushEventOfTurnEnd, type PushEvent, type PushNotifier } from './push.ts'
37
49
  import { wireArgs, type BridgeGateway, type GatewayPeer } from './wire.ts'
38
50
 
39
- /** Longest a registered turn end waits for its session to fall quiet, in milliseconds. */
40
- export const TURN_END_QUIET_MAX_MS = 600_000
51
+ /**
52
+ * How long a held turn end waits before the bridge logs that it is still waiting,
53
+ * in milliseconds.
54
+ *
55
+ * A progress line and never a send: the wait itself has no cap, because announcing a
56
+ * turn while its family still works is exactly what this module exists to prevent.
57
+ */
58
+ export const TURN_END_QUIET_REPORT_MS = 600_000
41
59
 
42
60
  /**
43
61
  * How long a held turn end waits before asking the host again, in milliseconds.
44
62
  *
45
- * A turn end usually finds its session already quiet — the host clears the flag
46
- * as the turn finishes — so the first question is the one that matters, and five
63
+ * A turn end usually finds its family already quiet — the host clears the flag as
64
+ * the turn finishes — so the first question is the one that matters, and five
47
65
  * seconds is short enough that the notification a user waits for is not visibly
48
66
  * late. The interval is also what bounds how many questions one held turn end can
49
67
  * cost: at most one every five seconds, never more than one in flight.
50
68
  */
51
69
  export const TURN_END_QUIET_INTERVAL_MS = 5_000
52
70
 
53
- /** The host's answer about the work one session still holds. */
71
+ /**
72
+ * How long one question to the host may stay unanswered before the bridge abandons
73
+ * that question, in milliseconds.
74
+ *
75
+ * Three times {@link TURN_END_QUIET_INTERVAL_MS}. A `session/list` read the host is
76
+ * willing to make comes back well inside one interval, so a question that outlives
77
+ * three of them is a call that will not return — a stuck gateway request, not a slow
78
+ * host — and an entry that keeps waiting for it has no next question to ask, which is
79
+ * exactly how a phone goes permanently silent. The bound belongs to the question and
80
+ * never to the turn end: an abandoned question answers nothing, the entry stays held,
81
+ * and the next question leaves on the usual interval.
82
+ */
83
+ export const TURN_END_QUIET_PROBE_TIMEOUT_MS = 15_000
84
+
85
+ /**
86
+ * How many session ids the gate remembers the phone prompting, at most.
87
+ *
88
+ * The set exists to tell the phone's own subagent sessions from the ones it merely
89
+ * watches, and a bridge that runs for weeks must not grow it without end: the oldest
90
+ * id is dropped first, and a session dropped that way and prompted again enters as a
91
+ * new one.
92
+ */
93
+ export const TURN_END_PHONE_PROMPTED_MAX = 5_000
94
+
95
+ /** The host's answer about the work one session's family still holds. */
54
96
  export interface QuietAnswer {
55
- /** Whether nothing under this session is still going. */
97
+ /** Whether nothing in this session's family is still going. */
56
98
  readonly quiet: boolean
57
99
  /** What was still going when it was not, in one token for the log line. */
58
100
  readonly busy?: string
101
+ /**
102
+ * Present only when the host says another session spawned this one
103
+ * (`origin: "subagent"`).
104
+ *
105
+ * Absent is a host that said nothing about the session's origin, which is not the
106
+ * same as saying it has none: a turn end is announced for anything the host does
107
+ * not name as a subagent.
108
+ */
109
+ readonly subagent?: boolean
59
110
  }
60
111
 
61
- /** Whether one session is quiet right now, as the host answers it. */
112
+ /** Whether one session's family is quiet right now, as the host answers it. */
62
113
  export type QuietProbe = (sessionId: string) => Promise<QuietAnswer>
63
114
 
64
115
  export interface TurnEndQuietOptions {
@@ -69,20 +120,25 @@ export interface TurnEndQuietOptions {
69
120
  /**
70
121
  * The host's own answer, asked off the frame path.
71
122
  *
72
- * Absent is a bridge assembled without one, which cannot tell a quiet session
73
- * from a busy one and therefore reports at the frame rather than holding
74
- * anything back.
123
+ * Absent is a bridge assembled without one, which cannot tell a quiet family from
124
+ * a busy one — nor a subagent session from the phone's own — and therefore reports
125
+ * at the frame rather than holding anything back.
75
126
  */
76
127
  readonly probe?: QuietProbe
77
128
  readonly now?: () => number
78
129
  readonly log?: (message: string) => void
79
- /** The wait budget; the default is {@link TURN_END_QUIET_MAX_MS}, and a deployment moves it. */
80
- readonly maxWaitMs?: number
130
+ /** When the still-waiting line is logged; the default is {@link TURN_END_QUIET_REPORT_MS}. */
131
+ readonly reportAfterMs?: number
81
132
  /** The re-check interval; the default is {@link TURN_END_QUIET_INTERVAL_MS}. */
82
133
  readonly intervalMs?: number
134
+ /**
135
+ * How many phone-prompted session ids to remember; the default and the ceiling are
136
+ * both {@link TURN_END_PHONE_PROMPTED_MAX}, and a deployment lowers it for a suite.
137
+ */
138
+ readonly phonePromptLimit?: number
83
139
  }
84
140
 
85
- /** One turn end held until its session is quiet. */
141
+ /** One turn end held until its family is quiet. */
86
142
  interface Waiting {
87
143
  readonly sessionId: string
88
144
  /** §28's event, decided when the turn end was registered. */
@@ -90,15 +146,22 @@ interface Waiting {
90
146
  /** The host's own reason, kept because §29 decides ended versus failed from it. */
91
147
  reason: string
92
148
  readonly registeredAt: number
93
- readonly deadline: number
94
- /** The question to the host that is armed, if one is. */
149
+ /** The next question to the host that is armed, if one is. */
95
150
  check: NodeJS.Timeout | undefined
96
- /** The timer that announces at the deadline whatever the answer is then. */
97
- expiry: NodeJS.Timeout | undefined
151
+ /** The one-shot timer that says the wait is still going, if it has not fired. */
152
+ report: NodeJS.Timeout | undefined
98
153
  /** Why the last question answered "not quiet". */
99
154
  busy: string | undefined
100
- /** Set while a question is in flight, so one entry never has two out at once. */
101
- asking: boolean
155
+ /**
156
+ * The generation of the question in flight, or zero when none is out.
157
+ *
158
+ * A generation rather than a flag: a question the bound has abandoned settles under
159
+ * a number that is no longer current, so its answer can neither announce anything
160
+ * nor ask again, and one entry never has two questions out at once.
161
+ */
162
+ asking: number
163
+ /** The one-shot bound on the question in flight, until it answers or is abandoned. */
164
+ deadline: NodeJS.Timeout | undefined
102
165
  }
103
166
 
104
167
  /**
@@ -115,12 +178,19 @@ export class TurnEndQuietGate {
115
178
  readonly #log: (message: string) => void
116
179
  /** Held turn ends by session id; one session has one thing to announce. */
117
180
  readonly #waiting = new Map<string, Waiting>()
181
+ /** The sessions the phone itself prompted, oldest first. */
182
+ readonly #phonePrompted = new Set<string>()
183
+ readonly #phonePromptLimit: number
184
+ /** The last question generation handed out, so no question is ever minted twice. */
185
+ #asked = 0
118
186
  #disposed = false
119
187
 
120
188
  constructor(options: TurnEndQuietOptions) {
121
189
  this.#options = options
122
190
  this.#now = options.now ?? (() => Date.now())
123
191
  this.#log = options.log ?? (() => undefined)
192
+ // The ceiling is this module's own rule, so a configured limit can only lower it.
193
+ this.#phonePromptLimit = Math.max(1, Math.min(options.phonePromptLimit ?? TURN_END_PHONE_PROMPTED_MAX, TURN_END_PHONE_PROMPTED_MAX))
124
194
  }
125
195
 
126
196
  /** @returns whether either channel can send, which is the only case a turn end is held at all. */
@@ -135,7 +205,7 @@ export class TurnEndQuietGate {
135
205
  }
136
206
 
137
207
  /**
138
- * Hold one finished turn until its session is quiet, then announce it.
208
+ * Hold one finished turn until its family is quiet, then announce it.
139
209
  *
140
210
  * Returns at once and never awaits a host read: the caller is a follow stream
141
211
  * that has already published its increment.
@@ -151,6 +221,29 @@ export class TurnEndQuietGate {
151
221
  }
152
222
  }
153
223
 
224
+ /**
225
+ * Remember that the phone itself prompted one session.
226
+ *
227
+ * This is the one thing that makes a subagent session's turn end announceable: the
228
+ * host spawns those on its own, and a phone that never asked that session anything
229
+ * is not waiting to hear how its turn went. Bounded and first in, first out, so the
230
+ * memory is the recent work rather than everything since the bridge started.
231
+ * @param sessionId - the session a `session/prompt` frame carried.
232
+ */
233
+ notePhonePrompt(sessionId: string): void {
234
+ if (sessionId === '') return
235
+ // A session prompted again keeps its place: the question is whether the phone ever
236
+ // prompted it, and the oldest entry is the one whose answer is least likely to be
237
+ // asked again.
238
+ if (this.#phonePrompted.has(sessionId)) return
239
+ this.#phonePrompted.add(sessionId)
240
+ while (this.#phonePrompted.size > this.#phonePromptLimit) {
241
+ const oldest = this.#phonePrompted.values().next().value
242
+ if (oldest === undefined) break
243
+ this.#phonePrompted.delete(oldest)
244
+ }
245
+ }
246
+
154
247
  /**
155
248
  * Drop a held turn end because another turn is on.
156
249
  *
@@ -174,6 +267,7 @@ export class TurnEndQuietGate {
174
267
  this.#disposed = true
175
268
  for (const waiting of [...this.#waiting.values()]) this.#forget(waiting)
176
269
  this.#waiting.clear()
270
+ this.#phonePrompted.clear()
177
271
  }
178
272
 
179
273
  /** Store one registration, or fold it into the one already held for that session. */
@@ -181,8 +275,8 @@ export class TurnEndQuietGate {
181
275
  const held = this.#waiting.get(sessionId)
182
276
  if (held !== undefined) {
183
277
  // One session has one thing to announce, so a second turn end replaces what
184
- // will be said and keeps the deadline the first one registered: a session
185
- // that keeps ending turns cannot postpone its own announcement for ever.
278
+ // will be said and keeps the instant the first one registered: a session that
279
+ // keeps ending turns cannot postpone its own announcement for ever.
186
280
  held.event = pushEventOfTurnEnd(reason)
187
281
  held.reason = reason
188
282
  this.#log(`turn-end registered session=${sessionId} event=${held.event} replaces=held`)
@@ -194,11 +288,11 @@ export class TurnEndQuietGate {
194
288
  event: pushEventOfTurnEnd(reason),
195
289
  reason,
196
290
  registeredAt: now,
197
- deadline: now + Math.max(0, this.#options.maxWaitMs ?? TURN_END_QUIET_MAX_MS),
198
291
  check: undefined,
199
- expiry: undefined,
292
+ report: undefined,
293
+ deadline: undefined,
200
294
  busy: undefined,
201
- asking: false,
295
+ asking: 0,
202
296
  }
203
297
  this.#waiting.set(sessionId, waiting)
204
298
  if (this.#options.probe === undefined) {
@@ -206,81 +300,143 @@ export class TurnEndQuietGate {
206
300
  return
207
301
  }
208
302
  this.#log(`turn-end registered session=${sessionId} event=${waiting.event}`)
209
- const expiry = setTimeout(() => {
210
- waiting.expiry = undefined
211
- this.#deliver(waiting, waiting.busy ?? 'unanswered')
212
- }, Math.max(0, waiting.deadline - now))
303
+ const report = setTimeout(() => {
304
+ waiting.report = undefined
305
+ this.#stillWaiting(waiting)
306
+ }, Math.max(0, this.#options.reportAfterMs ?? TURN_END_QUIET_REPORT_MS))
213
307
  // A notification waiting on work it did not start must never keep the host
214
308
  // process alive.
215
- expiry.unref?.()
216
- waiting.expiry = expiry
309
+ report.unref?.()
310
+ waiting.report = report
217
311
  this.#arm(waiting)
218
312
  }
219
313
 
220
- /** Arm the next question to the host, unless the budget runs out first. */
314
+ /** Arm the next question to the host. */
221
315
  #arm(waiting: Waiting): void {
222
316
  if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
223
- const remaining = waiting.deadline - this.#now()
224
- // The expiry timer is what answers a budget that has run out, so no question
225
- // is armed past it: two timers due in the same millisecond would otherwise
226
- // turn into a zero-delay loop on a session that never falls quiet.
227
- if (remaining <= 0) return
228
- const interval = this.#options.intervalMs ?? TURN_END_QUIET_INTERVAL_MS
317
+ // A zero interval would turn the re-check into a zero-delay loop on a family that
318
+ // never falls quiet, so the floor is one millisecond.
319
+ const interval = Math.max(1, this.#options.intervalMs ?? TURN_END_QUIET_INTERVAL_MS)
229
320
  const timer = setTimeout(() => {
230
321
  waiting.check = undefined
231
322
  this.#check(waiting)
232
- }, Math.max(0, Math.min(interval, remaining)))
323
+ }, interval)
233
324
  timer.unref?.()
234
325
  waiting.check = timer
235
326
  }
236
327
 
237
- /** Ask the host once whether a held entry's session is quiet. */
328
+ /**
329
+ * Ask the host once whether a held entry's family is quiet.
330
+ *
331
+ * One question is out at a time, and every question carries its own bound: a read
332
+ * the gateway never returns would otherwise leave the entry holding a question that
333
+ * has no answer coming, with no next question armed behind it — the channel silenced
334
+ * for as long as the entry is held. The bound ends that one question only; the entry
335
+ * keeps waiting and the next question leaves on the usual interval.
336
+ */
238
337
  #check(waiting: Waiting): void {
239
338
  if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
240
339
  const probe = this.#options.probe
241
- if (probe === undefined || waiting.asking) return
242
- waiting.asking = true
340
+ if (probe === undefined || waiting.asking !== 0) return
341
+ // Every question is one generation, minted here and never reused. A question the
342
+ // bound abandons settles under a generation that is no longer in flight, so it can
343
+ // neither announce anything nor ask a second time.
344
+ const generation = ++this.#asked
345
+ waiting.asking = generation
243
346
  void Promise.resolve()
244
- .then(async () => await probe(waiting.sessionId))
347
+ .then(async (): Promise<QuietAnswer | undefined> => {
348
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return undefined
349
+ if (waiting.asking !== generation) return undefined
350
+ // The bound is armed here, where the question really leaves, rather than at the
351
+ // call site: it times the host read itself and not the turn of the loop that
352
+ // queued it. Nothing short of that loop never running can starve this line.
353
+ const deadline = setTimeout(() => {
354
+ waiting.deadline = undefined
355
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
356
+ // Only the question this bound was armed for is abandoned: one that has
357
+ // already answered has armed the next question and is not this bound's to
358
+ // touch.
359
+ if (waiting.asking !== generation) return
360
+ waiting.asking = 0
361
+ // An answer that never came is not a quiet answer: the token says which
362
+ // failure it was, one line says the question was given up on, and the entry
363
+ // asks again on its interval.
364
+ waiting.busy = 'unreadable'
365
+ this.#log(`turn-end quiet check unreadable session=${waiting.sessionId} after=${TURN_END_QUIET_PROBE_TIMEOUT_MS}ms`)
366
+ this.#arm(waiting)
367
+ }, TURN_END_QUIET_PROBE_TIMEOUT_MS)
368
+ // A question waiting on a host that may never answer must never keep the host
369
+ // process alive either.
370
+ deadline.unref?.()
371
+ waiting.deadline = deadline
372
+ return await probe(waiting.sessionId)
373
+ })
245
374
  .then((answer) => {
246
- waiting.asking = false
375
+ // Nothing to take an answer for: the question never left, or the bound has
376
+ // already abandoned this generation.
377
+ if (answer === undefined || waiting.asking !== generation) return
378
+ waiting.asking = 0
379
+ this.#dropDeadline(waiting)
247
380
  if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
381
+ // A session the host spawned as a subagent is not the phone's own work, so its
382
+ // turn end is dropped rather than announced — unless the phone prompted that
383
+ // session itself, in which case it is exactly what the phone is waiting for.
384
+ if (answer.subagent === true && !this.#phonePrompted.has(waiting.sessionId)) {
385
+ this.#forget(waiting)
386
+ this.#log(`turn-end dropped session=${waiting.sessionId} reason=subagent-not-prompted`)
387
+ return
388
+ }
248
389
  if (answer.quiet) {
249
390
  this.#deliver(waiting)
250
391
  return
251
392
  }
252
- // The reason is kept rather than logged here: a session that is busy for a
393
+ // The reason is kept rather than logged here: a family that is busy for a
253
394
  // minute would otherwise write twelve lines saying the same thing, and the
254
- // one line worth reading is the one the announcement carries.
395
+ // lines worth reading are the still-waiting one and the announcement's.
255
396
  waiting.busy = answer.busy ?? 'unstated'
256
397
  this.#arm(waiting)
257
398
  })
258
399
  .catch((error: unknown) => {
259
- waiting.asking = false
400
+ if (waiting.asking !== generation) return
401
+ waiting.asking = 0
402
+ this.#dropDeadline(waiting)
260
403
  if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
261
404
  // An unreadable answer is one line and another try: the host may answer the
262
- // next one, and the expiry timer bounds how long that can go on.
405
+ // next one, and nothing is announced on a question that got no answer.
263
406
  waiting.busy = 'unreadable'
264
407
  this.#log(`turn-end quiet check failed session=${waiting.sessionId}: ${failureText(error)}`)
265
408
  this.#arm(waiting)
266
409
  })
267
410
  }
268
411
 
412
+ /** Cancel the bound on the question in flight, if it is still armed. */
413
+ #dropDeadline(waiting: Waiting): void {
414
+ if (waiting.deadline !== undefined) clearTimeout(waiting.deadline)
415
+ waiting.deadline = undefined
416
+ }
417
+
418
+ /**
419
+ * Say once that a held turn end is still waiting, and keep holding it.
420
+ * @param waiting - the entry that has been held this long.
421
+ */
422
+ #stillWaiting(waiting: Waiting): void {
423
+ if (this.#disposed || this.#waiting.get(waiting.sessionId) !== waiting) return
424
+ const waited = this.#now() - waiting.registeredAt
425
+ this.#log(`turn-end still waiting session=${waiting.sessionId} waited=${waited}ms busy=${waiting.busy ?? 'unanswered'}, nothing announced`)
426
+ }
427
+
269
428
  /**
270
429
  * Announce one held turn end and forget it.
271
430
  *
272
431
  * The rate windows are booked inside the two calls below, at this instant: what
273
432
  * the channels admit is what they really send, never what was once registered.
274
433
  * @param waiting - the entry to announce.
275
- * @param stillBusy - what kept it waiting, when the budget ran out first.
276
434
  */
277
- #deliver(waiting: Waiting, stillBusy?: string): void {
435
+ #deliver(waiting: Waiting): void {
278
436
  this.#forget(waiting)
279
437
  const sessionId = waiting.sessionId
280
438
  const waited = this.#now() - waiting.registeredAt
281
- this.#log(stillBusy === undefined
282
- ? `turn-end quiet session=${sessionId} waited=${waited}ms event=${waiting.event}`
283
- : `turn-end session=${sessionId} still-busy(${stillBusy}) waited=${waited}ms, announcing anyway`)
439
+ this.#log(`turn-end quiet session=${sessionId} waited=${waited}ms event=${waiting.event}`)
284
440
  try {
285
441
  this.#options.push?.notify(waiting.event, sessionId)
286
442
  } catch (error) {
@@ -295,12 +451,16 @@ export class TurnEndQuietGate {
295
451
  }
296
452
  }
297
453
 
298
- /** Drop one entry and both of its timers. */
454
+ /** Drop one entry and every timer it holds. */
299
455
  #forget(waiting: Waiting): void {
300
456
  if (waiting.check !== undefined) clearTimeout(waiting.check)
301
- if (waiting.expiry !== undefined) clearTimeout(waiting.expiry)
457
+ if (waiting.report !== undefined) clearTimeout(waiting.report)
458
+ this.#dropDeadline(waiting)
302
459
  waiting.check = undefined
303
- waiting.expiry = undefined
460
+ waiting.report = undefined
461
+ // A question already in flight is disowned here, so its answer can neither
462
+ // announce nor ask again for an entry that is gone.
463
+ waiting.asking = 0
304
464
  if (this.#waiting.get(waiting.sessionId) === waiting) this.#waiting.delete(waiting.sessionId)
305
465
  }
306
466
  }
@@ -316,14 +476,14 @@ export interface SessionQuietProbeOptions {
316
476
  }
317
477
 
318
478
  /**
319
- * The host's answer to "is this session quiet", built from its own two facts.
479
+ * The host's answer to "is this session's family quiet", built from its own facts.
320
480
  *
321
- * The session list is where the running flag and the parent chain come from, and
322
- * the job registry is where a job's owner and status come from; neither is
323
- * captured once, because both move while a held turn end waits. A read that cannot
324
- * be made is thrown rather than answered as quiet: "the host did not answer" and
325
- * "nothing is running" are different facts, and the caller retries the one and
326
- * announces the other.
481
+ * The session list is where the running flags, the parent chain and each session's
482
+ * origin come from, and the job registry is where a job's owner and status come
483
+ * from; neither is captured once, because both move while a held turn end waits. A
484
+ * read that cannot be made is thrown rather than answered as quiet: "the host did
485
+ * not answer" and "nothing is running" are different facts, and the caller retries
486
+ * the one and announces the other.
327
487
  * @param options - the faces the answer is read through.
328
488
  * @returns the probe the gate asks.
329
489
  */
@@ -339,22 +499,32 @@ export function sessionQuietProbe(options: SessionQuietProbeOptions): QuietProbe
339
499
  if (!Array.isArray(items)) throw new Error('session/list returned no item table')
340
500
  const running = new Set<string>()
341
501
  const parents = new Map<string, string>()
502
+ let subagent: true | undefined
342
503
  for (const item of items) {
343
504
  if (typeof item !== 'object' || item === null) continue
344
- const row = item as { sessionId?: unknown; running?: unknown; parentSessionId?: unknown }
505
+ const row = item as { sessionId?: unknown; running?: unknown; parentSessionId?: unknown; origin?: unknown }
345
506
  if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
346
507
  if (row.running === true) running.add(row.sessionId)
347
508
  if (typeof row.parentSessionId === 'string' && row.parentSessionId !== '') parents.set(row.sessionId, row.parentSessionId)
509
+ // The subagent plugin writes `origin: "subagent"` on the sessions it spawned, so
510
+ // that one word is the whole of the host's own answer about provenance.
511
+ if (row.sessionId === sessionId && row.origin === 'subagent') subagent = true
348
512
  }
349
- // The host answers `running` for a session's own agent, so a parent reads idle
350
- // while the work it started goes on: the parent chain is walked here, to any
351
- // depth, and stops at an id it has already walked so a looping chain ends.
352
- if (running.has(sessionId)) return { quiet: false, busy: 'session-running' }
513
+ // The host answers `running` for a session's own agent, so every member of a
514
+ // family reads idle while the family's work goes on: the family is resolved here
515
+ // — the root the parent chain climbs to, and every session under that root at any
516
+ // depth — because a leaf's turn end waits for what its siblings are still doing.
517
+ const root = familyRootOf(sessionId, parents)
518
+ const family = new Set<string>([root])
519
+ for (const id of parents.keys()) if (descendsFrom(id, root, parents)) family.add(id)
520
+ if (running.has(sessionId)) return { quiet: false, busy: 'session-running', ...(subagent === undefined ? {} : { subagent }) }
353
521
  for (const id of running) {
354
- if (descendsFrom(id, sessionId, parents)) return { quiet: false, busy: `descendant-running(${id})` }
522
+ if (id === sessionId || !family.has(id)) continue
523
+ // The token says which side of the session the work sits on, because the log
524
+ // line is read by someone deciding whether the wait is reasonable.
525
+ const side = descendsFrom(id, sessionId, parents) ? 'descendant' : 'ancestor'
526
+ return { quiet: false, busy: `${side}-running(${id})`, ...(subagent === undefined ? {} : { subagent }) }
355
527
  }
356
- const family = new Set<string>([sessionId])
357
- for (const id of parents.keys()) if (descendsFrom(id, sessionId, parents)) family.add(id)
358
528
  for (const id of family) {
359
529
  const roster = options.jobs.read(id)
360
530
  // A host that composes no job registry holds no job this bridge can name,
@@ -362,17 +532,30 @@ export function sessionQuietProbe(options: SessionQuietProbeOptions): QuietProbe
362
532
  if (roster === undefined) continue
363
533
  for (const job of roster.jobs) {
364
534
  // Only the jobs the host names an owner for count: an unowned job is not a
365
- // fact about this session, and spreading it over the roster would be a
366
- // claim the payload does not support.
535
+ // fact about this family, and spreading it over the roster would be a claim
536
+ // the payload does not support.
367
537
  if (job.ownerSessionId === undefined || !family.has(job.ownerSessionId)) continue
368
- // The host's own projection omits `finishedAt` while a job is live, which
369
- // is what makes `stopping` count as work in progress and keeps a status
370
- // this bridge has never heard of from being read as a finished one.
371
- if (job.finishedAt === undefined) return { quiet: false, busy: `job-live(${job.id})` }
538
+ // The host's own projection omits `finishedAt` while a job is live, which is
539
+ // what makes `stopping` count as work in progress and keeps a status this
540
+ // bridge has never heard of from being read as a finished one.
541
+ if (job.finishedAt === undefined) return { quiet: false, busy: `job-live(${job.id})`, ...(subagent === undefined ? {} : { subagent }) }
372
542
  }
373
543
  }
374
- return { quiet: true }
544
+ return { quiet: true, ...(subagent === undefined ? {} : { subagent }) }
545
+ }
546
+ }
547
+
548
+ /** @returns the session a parent chain climbs to, stopping where the chain repeats. */
549
+ function familyRootOf(sessionId: string, parents: ReadonlyMap<string, string>): string {
550
+ const walked = new Set<string>([sessionId])
551
+ let root = sessionId
552
+ let cursor = parents.get(sessionId)
553
+ while (cursor !== undefined && !walked.has(cursor)) {
554
+ root = cursor
555
+ walked.add(cursor)
556
+ cursor = parents.get(cursor)
375
557
  }
558
+ return root
376
559
  }
377
560
 
378
561
  /** @returns whether one session sits under another in the host's own parent chain. */