dsh-taskbridge 1.3.1 → 1.4.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.
@@ -1,1008 +1,1369 @@
1
- // Bounded activity bookkeeping for one running delegated task.
2
- //
3
- // This module answers exactly one question — "has this executor been silent, and
4
- // for how long?" — and records the minimum needed to answer it. It is deliberately
5
- // not a transcript, not a progress model and not a log:
6
- //
7
- // * **Only metadata is retained.** An event contributes a KIND, a COUNT and a
8
- // timestamp. Reasoning text, assistant text, tool result bodies and tool
9
- // arguments are read only far enough to decide *whether the event was
10
- // non-empty*; nothing derived from them is stored, so no buffer here can grow
11
- // with model output and nothing here can leak a transcript into a view,
12
- // a history row or a diagnostic.
13
- // * **The vocabulary is the harness's own.** The classified names are the
14
- // durable `SessionEventMap` types of `@deepseek-ai/dsh-session` (`step/start`,
15
- // `assistant/message`, `tool/call`, `tool/result`, plus the turn/step/usage
16
- // boundaries), the two stream-chunk types `@deepseek-ai/dsh-llm` emits
17
- // (`text-delta`, `reasoning-delta`), and the nested streaming envelopes the
18
- // runner accepts (`message/part`, `assistant/delta` wrapping a delta). An
19
- // event this module does not recognise is `unrelated`, which by contract never
20
- // resets idleness.
21
- // * **Only real activity resets the clock.** A non-empty output or reasoning
22
- // delta — top-level OR nested inside a streaming envelope — an assistant
23
- // message carrying text or reasoning, a step that actually started, a native
24
- // tool call and a tool result are activity. Empty deltas, bookkeeping events,
25
- // connection heartbeats and result polling are NOT: if they reset the clock, a
26
- // hung executor would look busy forever and the whole silent-wait mechanism
27
- // would never fire.
28
- // * **Silence, not duration, raises attention.** An open tool call changes how the
29
- // silence is DESCRIBED (`waitingOn: 'tool'`, with the call's elapsed span and a
30
- // `tool-running` self-check verdict) but not WHETHER it counts: a tool that
31
- // emits nothing for five minutes gets the self-check and for ten minutes gets
32
- // attention, exactly like any other silent executor. Treating an open call as
33
- // proof of progress would hide a genuinely hung tool. Nothing here ever fails,
34
- // cancels or restarts a run because of duration.
35
- //
36
- // The clock is injected (`now`) so tests can simulate twenty minutes of real
37
- // progress deterministically instead of sleeping.
38
-
39
- /**
40
- * How one event kind is classified for idleness.
41
- *
42
- * `activity` — the executor demonstrably produced something; resets the idle clock.
43
- * `structure` — a lifecycle boundary (turn/step boundaries, usage, an empty
44
- * delta). Observed and counted, never treated as progress.
45
- * `unrelated` — anything this build does not classify, including heartbeat and
46
- * polling traffic on an unrelated channel.
47
- */
48
- export const ACTIVITY_KINDS = Object.freeze({
49
- activity: 'activity',
50
- structure: 'structure',
51
- unrelated: 'unrelated',
52
- });
53
-
54
- /** How many distinct event types one summary keeps counts for. */
55
- const MAX_KIND_COUNTS = 32;
56
-
57
- /** Bound on a recorded tool name or call id; they are identifiers, not content. */
58
- const MAX_IDENTIFIER_CHARS = 200;
59
-
60
- /** Settled call ids remembered so a completion can be matched to its start. */
61
- const MAX_TRACKED_CALL_IDS = 64;
62
-
63
- /**
64
- * Session event types that are PROGRESS, keyed to the evidence they carry.
65
- *
66
- * These are `SessionEventMap` members of `@deepseek-ai/dsh-session` (and, for the
67
- * two delta names, `StreamChunk` types of `@deepseek-ai/dsh-llm`, which reach the
68
- * same listener). Whether a given event is *genuine* progress is decided by
69
- * {@link observeProgress}: several of these can arrive carrying nothing.
70
- */
71
- const ACTIVITY_EVENT_TYPES = Object.freeze({
72
- // The loop streamed model output. Genuine only when the delta is non-empty.
73
- 'text-delta': 'output-delta',
74
- 'reasoning-delta': 'reasoning-delta',
75
- // Nested streaming envelopes: `data.delta` carries the same chunk shape. The
76
- // runner accepts both spellings, so both must be classified — treating them as
77
- // structural would hide every token of a run that streams nested.
78
- 'message/part': 'output-delta',
79
- 'assistant/delta': 'output-delta',
80
- // The settled assistant message for one step. Genuine only when it carries text
81
- // or reasoning; an empty message is a structural event.
82
- 'assistant/message': 'assistant-message',
83
- // A step actually opened: the model was called.
84
- 'step/start': 'model-step',
85
- // The model requested one tool invocation.
86
- 'tool/call': 'tool-call',
87
- // One tool call settled with a model-facing result.
88
- 'tool/result': 'tool-result',
89
- });
90
-
91
- /**
92
- * Session event types that only ever open, close or describe a step.
93
- *
94
- * `assistant/message` is handled separately: it is progress only when it carries
95
- * content, which is the difference between the settled answer and an empty message.
96
- */
97
- const STRUCTURE_EVENT_TYPES = Object.freeze(new Set([
98
- 'turn/start',
99
- 'turn/end',
100
- 'step/end',
101
- 'assistant/attempt',
102
- 'usage',
103
- ]));
104
-
105
- /**
106
- * Classify one native event.
107
- *
108
- * @param {unknown} event - the object handed to `request.onEvent`.
109
- * @returns {{ kind: string, type: string | null, label: string, activity: boolean, tool: object | null }} classification.
110
- */
111
- export function classifyActivityEvent(event) {
112
- const unrelated = { kind: ACTIVITY_KINDS.unrelated, type: null, label: 'unrelated', activity: false, tool: null };
113
- if (event === null || typeof event !== 'object') return unrelated;
114
- const type = typeof event.type === 'string' ? event.type : null;
115
- if (type === null) return unrelated;
116
-
117
- const progress = ACTIVITY_EVENT_TYPES[type];
118
- if (progress !== undefined) {
119
- const observed = observeProgress(type, event);
120
- return {
121
- kind: observed.activity ? ACTIVITY_KINDS.activity : ACTIVITY_KINDS.structure,
122
- type,
123
- label: observed.activity ? progress : `${progress}-empty`,
124
- activity: observed.activity,
125
- tool: observed.tool,
126
- };
127
- }
128
- if (STRUCTURE_EVENT_TYPES.has(type)) {
129
- return { kind: ACTIVITY_KINDS.structure, type, label: type, activity: false, tool: null };
130
- }
131
- return unrelated;
132
- }
133
-
134
- /**
135
- * Read one progress-shaped event far enough to decide whether it carried
136
- * anything, and to recover the tool identity when it names one.
137
- *
138
- * This is the only place that touches payload fields. It reads text/content ONLY
139
- * to test emptiness: no string is returned, stored or concatenated.
140
- * @param {string} type - event type.
141
- * @param {object} event - event object.
142
- * @returns {{ activity: boolean, tool: object | null }} observation.
143
- */
144
- function observeProgress(type, event) {
145
- if (type === 'text-delta' || type === 'reasoning-delta') {
146
- const text = payloadOf(event).text;
147
- // A delta that carries no characters says nothing about progress: the loop
148
- // can emit an empty chunk while waiting on the provider. A whitespace-only
149
- // delta is still model output, so it counts.
150
- return { activity: typeof text === 'string' && text !== '', tool: null };
151
- }
152
- if (type === 'message/part' || type === 'assistant/delta') {
153
- // Nested streaming envelope: the chunk lives under `data.delta` (the runner
154
- // accepts `data.delta`, `delta`, then `data` itself). Only the delta's TYPE and
155
- // the emptiness of its text are read; the text is never returned.
156
- const payload = payloadOf(event);
157
- const delta = payload.delta ?? event.delta ?? payload;
158
- if (delta === null || typeof delta !== 'object') return { activity: false, tool: null };
159
- const deltaType = delta.type;
160
- if (deltaType !== 'text-delta' && deltaType !== 'reasoning-delta') {
161
- return { activity: false, tool: null };
162
- }
163
- const text = delta.text;
164
- return { activity: typeof text === 'string' && text !== '', tool: null };
165
- }
166
- if (type === 'assistant/message') {
167
- const payload = payloadOf(event);
168
- const message = payload.message ?? event.message ?? null;
169
- const content = Array.isArray(message?.content) ? message.content : [];
170
- for (const block of content) {
171
- if (block === null || typeof block !== 'object') continue;
172
- if ((block.type === 'text' || block.type === 'reasoning')
173
- && typeof block.text === 'string' && block.text !== '') {
174
- return { activity: true, tool: null };
175
- }
176
- }
177
- return { activity: false, tool: null };
178
- }
179
- if (type === 'tool/call') {
180
- // `payloadOf` already falls back to the event object itself, so this reads
181
- // `data.name` when the native envelope is present and a top-level `name`
182
- // otherwise. The ARGUMENTS are deliberately not read at all, so this module
183
- // cannot retain or forward them.
184
- const payload = payloadOf(event);
185
- const name = identifier(payload.name);
186
- const callId = identifier(payload.callId ?? payload.id);
187
- return { activity: name !== null, tool: { name, callId } };
188
- }
189
- if (type === 'tool/result') {
190
- // Native shape: `data.message.toolCallId` (the tool-role result message).
191
- const message = payloadOf(event).message;
192
- const callId = identifier(message?.toolCallId ?? payloadOf(event).callId);
193
- // Any settled tool result is progress, including a failed one: the tool ran.
194
- return { activity: true, tool: { name: null, callId } };
195
- }
196
- if (type === 'step/start') {
197
- return { activity: true, tool: null };
198
- }
199
- return { activity: false, tool: null };
200
- }
201
-
202
- /**
203
- * The payload of a native event.
204
- *
205
- * Native events carry their payload under `data` (`{ type, seq, time, data }`),
206
- * and the streaming shapes a fake or a legacy emitter produces put the same fields
207
- * at the top level. Both spellings are accepted, `data` first.
208
- * @param {object} event - event object.
209
- * @returns {object} payload object (never null).
210
- */
211
- function payloadOf(event) {
212
- const data = event.data;
213
- if (data !== null && typeof data === 'object' && !Array.isArray(data)) return data;
214
- return event;
215
- }
216
-
217
- /**
218
- * Bound an identifier-shaped value (a tool name or a call id).
219
- *
220
- * Bounded and type-checked, never interpreted: these names are published so an
221
- * operator can see WHAT is running, and a pathological value cannot grow a view.
222
- * @param {unknown} value - candidate.
223
- * @returns {string | null} bounded identifier, or null.
224
- */
225
- function identifier(value) {
226
- if (typeof value !== 'string') return null;
227
- const trimmed = value.slice(0, MAX_IDENTIFIER_CHARS);
228
- return trimmed === '' ? null : trimmed;
229
- }
230
-
231
- /**
232
- * Bounded activity state of one running task.
233
- *
234
- * Owned by the engine's per-task monitor. Every field is a scalar or a small
235
- * bounded map; there is no reference to the event object that produced it.
236
- */
237
- export class TaskActivity {
238
- /**
239
- * @param {object} [options] - `now` clock override (tests).
240
- */
241
- constructor(options = {}) {
242
- /** @type {() => number} */
243
- this.now = typeof options.now === 'function' ? options.now : Date.now;
244
- /** @type {number | null} */
245
- this.lastActivityAt = null;
246
- /** @type {number} */
247
- this.replacements = 0;
248
- /** @type {{ name: string | null, callId: string | null, startedAt: number } | null} */
249
- this.tool = null;
250
- /** Settled tool calls represented as a count only — never their content. */
251
- this.toolCallsStarted = 0;
252
- this.toolCallsFinished = 0;
253
- this.lastToolName = null;
254
- this.lastToolDurationMs = null;
255
- /** @type {Map<string, number>} */
256
- this.counts = new Map();
257
- /** @type {Map<string, number>} */
258
- this.openCalls = new Map();
259
- /** @type {Map<string, number>} */
260
- this.eventCounts = new Map();
261
- /** Bumped on every genuine activity; used to reset one wait's episode view. */
262
- this.sequence = 0;
263
- /**
264
- * Genuine activity events, counted independently of the label map.
265
- *
266
- * The map is bounded and its keys can be evicted, so summing it would make the
267
- * published count both imprecise (structure and unrelated labels would be
268
- * included) and lossy. This counter is only ever incremented for real progress.
269
- */
270
- this.activityCount = 0;
271
- /** Total observations, counted independently of the bounded per-type map. */
272
- this.eventCount = 0;
273
- /**
274
- * Set once the run reached a terminal state. From then on every elapsed value is
275
- * measured against the recorded end, so a stored record cannot appear to keep
276
- * growing (a "tool running for 4 hours" that ended twenty minutes ago).
277
- * @type {{ endedAt: number } | null}
278
- */
279
- this.final = null;
280
- }
281
-
282
- /**
283
- * Record one observation.
284
- *
285
- * @param {object} observation - result of {@link classifyActivityEvent}.
286
- * @param {number} [at] - observation timestamp.
287
- * @returns {boolean} whether this observation was real activity.
288
- */
289
- record(observation, at = this.now()) {
290
- assertObservation(observation);
291
- if (this.final !== null) return false;
292
- this.replacements += 1;
293
- if (this.eventCount < Number.MAX_SAFE_INTEGER) this.eventCount += 1;
294
- const counted = this.counts.get(observation.label) ?? 0;
295
- if (counted < Number.MAX_SAFE_INTEGER) this.counts.set(observation.label, counted + 1);
296
- if (observation.type !== null) {
297
- const perType = this.eventCounts.get(observation.type) ?? 0;
298
- if (perType < Number.MAX_SAFE_INTEGER) this.eventCounts.set(observation.type, perType + 1);
299
- }
300
- this.pruneCounts();
301
- if (observation.tool !== null) this.recordTool(observation.tool, at);
302
- if (observation.activity !== true) return false;
303
- if (this.activityCount < Number.MAX_SAFE_INTEGER) this.activityCount += 1;
304
- this.lastActivityAt = at;
305
- this.sequence += 1;
306
- return true;
307
- }
308
-
309
- /**
310
- * Freeze every elapsed value at the instant the run ended.
311
- *
312
- * Called once, when the task reaches a terminal state. A view or a stored record
313
- * read an hour later then reports the span the run actually had, not an idle or
314
- * tool-elapsed duration that keeps growing for a run nobody is following.
315
- * @param {number} endedAt - the recorded end time.
316
- * @returns {void}
317
- */
318
- finalize(endedAt) {
319
- if (this.final !== null) return;
320
- const at = Number.isFinite(endedAt) ? endedAt : this.now();
321
- this.final = { endedAt: at };
322
- }
323
-
324
- /**
325
- * The reference time elapsed values are measured against.
326
- *
327
- * Live: the caller's `at`. Finalized: the recorded end, so nothing grows.
328
- * @param {number} at - requested reference time.
329
- * @returns {number} the effective reference time.
330
- */
331
- referenceTime(at) {
332
- if (this.final !== null) return this.final.endedAt;
333
- return at;
334
- }
335
-
336
- /**
337
- * Track the tool call a `tool/call` (or `tool/result`) event named.
338
- *
339
- * A start opens a span; a result closes the matching span and records how long
340
- * it ran. Nothing about the tool's arguments or result is kept.
341
- * @param {{ name: string | null, callId: string | null }} tool - identity.
342
- * @param {number} at - observation timestamp.
343
- * @returns {void}
344
- */
345
- recordTool(tool, at) {
346
- const callId = tool.callId;
347
- if (tool.name !== null) {
348
- this.lastToolName = tool.name;
349
- this.toolCallsStarted += 1;
350
- this.tool = { name: tool.name, callId, startedAt: at };
351
- if (callId !== null) {
352
- this.openCalls.set(callId, at);
353
- while (this.openCalls.size > MAX_TRACKED_CALL_IDS) {
354
- const oldest = this.openCalls.keys().next();
355
- if (oldest.done === true) break;
356
- this.openCalls.delete(oldest.value);
357
- }
358
- }
359
- return;
360
- }
361
- if (callId !== null && this.openCalls.has(callId)) {
362
- const startedAt = this.openCalls.get(callId);
363
- this.openCalls.delete(callId);
364
- this.lastToolDurationMs = Math.max(0, at - startedAt);
365
- this.toolCallsFinished += 1;
366
- if (this.tool !== null && this.tool.callId === callId) this.tool = null;
367
- }
368
- }
369
-
370
- /**
371
- * Keep the counters bounded.
372
- *
373
- * Both maps are keyed by a closed vocabulary (the labels and types this module
374
- * classifies), so they cannot grow with model output; the cap exists so a future
375
- * classifier that learns more keys cannot turn this into unbounded memory.
376
- * @returns {void}
377
- */
378
- pruneCounts() {
379
- while (this.counts.size > MAX_KIND_COUNTS) {
380
- const oldest = this.counts.keys().next();
381
- if (oldest.done === true) break;
382
- this.counts.delete(oldest.value);
383
- }
384
- while (this.eventCounts.size > MAX_KIND_COUNTS) {
385
- const oldest = this.eventCounts.keys().next();
386
- if (oldest.done === true) break;
387
- this.eventCounts.delete(oldest.value);
388
- }
389
- }
390
-
391
- /** @returns {number} total observations recorded. */
392
- totalEvents() {
393
- return this.eventCount;
394
- }
395
-
396
- /** @returns {number} genuine activity events. */
397
- activityEvents() {
398
- return this.activityCount;
399
- }
400
-
401
- /**
402
- * Milliseconds since the last genuine activity, or null when there was none.
403
- * @param {number} [at] - reference time.
404
- * @returns {number | null} idle span.
405
- */
406
- idleForMs(at = this.now()) {
407
- if (this.lastActivityAt === null) return null;
408
- return Math.max(0, this.referenceTime(at) - this.lastActivityAt);
409
- }
410
-
411
- /**
412
- * The pending tool span, described without any argument or result text.
413
- * @param {number} [at] - reference time.
414
- * @returns {{ name: string | null, callId: string | null, startedAt: number, elapsedMs: number } | null} span.
415
- */
416
- toolSpan(at = this.now()) {
417
- if (this.tool === null) return null;
418
- return {
419
- name: this.tool.name,
420
- callId: this.tool.callId,
421
- startedAt: this.tool.startedAt,
422
- elapsedMs: Math.max(0, this.referenceTime(at) - this.tool.startedAt),
423
- };
424
- }
425
-
426
- /**
427
- * The bounded, publishable summary of this activity.
428
- *
429
- * Everything here is a count, a timestamp or an identifier. There is no field a
430
- * text fragment, an argument or a result body could be carried in.
431
- * @param {object} [options] - `at` reference time, `toolActive` whether a tool
432
- * call is currently outstanding.
433
- * @returns {object} summary.
434
- */
435
- summary({ at = this.now(), toolActive = false } = {}) {
436
- const span = toolActive ? this.toolSpan(at) : null;
437
- return {
438
- lastActivityAt: this.lastActivityAt,
439
- // `idleForMs` is the honest silence span. While a native tool call is
440
- // outstanding the executor is working, not idle, so the same field reports
441
- // the tool's elapsed span and `waitingOn` says which of the two it is.
442
- idleForMs: span === null ? this.idleForMs(at) : span.elapsedMs,
443
- waitingOn: span === null ? 'idle' : 'tool',
444
- currentTool: span === null
445
- ? null
446
- : { name: span.name, callId: span.callId, startedAt: span.startedAt, elapsedMs: span.elapsedMs },
447
- lastTool: this.lastToolName === null
448
- ? null
449
- : { name: this.lastToolName, durationMs: this.lastToolDurationMs },
450
- events: this.totalEvents(),
451
- activityEvents: this.activityEvents(),
452
- toolCallsStarted: this.toolCallsStarted,
453
- toolCallsFinished: this.toolCallsFinished,
454
- // Stated when the record was frozen, so a reader can tell "this is the final
455
- // span" from "this is still being measured".
456
- finalizedAt: this.final === null ? null : this.final.endedAt,
457
- // Per-kind counts, bounded and sorted for a stable view.
458
- kinds: Object.fromEntries([...this.counts.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
459
- };
460
- }
461
- }
462
-
463
- /**
464
- * Guard against a caller passing a value this class cannot read.
465
- * @param {unknown} observation - candidate observation.
466
- * @returns {void}
467
- */
468
- function assertObservation(observation) {
469
- if (observation === null || typeof observation !== 'object') {
470
- throw new TypeError('activity observation must be an object');
471
- }
472
- }
473
-
474
- /** Why one observation wait ended. */
475
- export const OBSERVE_REASONS = Object.freeze({
476
- heartbeat: 'heartbeat',
477
- attention: 'attention',
478
- permission: 'permission',
479
- ready: 'ready',
480
- failed: 'failed',
481
- cancelled: 'cancelled',
482
- interrupted: 'interrupted',
483
- });
484
-
485
- /**
486
- * Reasons no caller may ever receive from {@link TaskMonitor#observe}.
487
- *
488
- * `heartbeat` means "nothing to report, ask again"; handing it to a caller would
489
- * be indistinguishable from a real report, so the loop treats it as an internal
490
- * re-wait instead.
491
- */
492
- const INTERNAL_REASONS = Object.freeze(new Set([OBSERVE_REASONS.heartbeat]));
493
-
494
- /**
495
- * The task states that end an observation, mapped to the reason reported.
496
- *
497
- * Read from the engine's own lifecycle vocabulary rather than re-declared, so a
498
- * new terminal state cannot leave the monitor silently reporting `heartbeat` for a
499
- * finished run.
500
- */
501
- const TERMINAL_REASON = Object.freeze({
502
- 'awaiting-host-review': OBSERVE_REASONS.ready,
503
- failed: OBSERVE_REASONS.failed,
504
- cancelled: OBSERVE_REASONS.cancelled,
505
- });
506
-
507
- /** The phase a running task reports while a permission request is outstanding. */
508
- const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
509
-
510
- /**
511
- * One task's activity monitor.
512
- *
513
- * Owned by the engine and attached to the task record, so the counters live next
514
- * to the run that produced them and die with it. It owns three things and nothing
515
- * else:
516
- *
517
- * 1. the bounded activity state ({@link TaskActivity}), fed from the native
518
- * `onEvent` callback the runner already invokes;
519
- * 2. the *episode* bookkeeping that makes silent waiting silent — a
520
- * self-check fires once per idle episode, and an `attention` report is not
521
- * repeated until the interval has really elapsed and the caller has asked
522
- * again;
523
- * 3. the observation wait itself, built from injected `now`/`wait` seams so a test
524
- * can simulate twenty minutes in microseconds.
525
- *
526
- * What it must never do, and does not: run an LLM, read a diff or a workspace
527
- * file, mutate the task, restart/cancel/resubmit a run, or extend a deadline. The
528
- * self-check is a read of facts the engine already holds.
529
- */
530
- export class TaskMonitor {
531
- /**
532
- * @param {object} task - the engine's own task record for this run.
533
- * @param {object} [options] - seams and thresholds.
534
- * @param {() => number} [options.now] - clock.
535
- * @param {(ms: number) => Promise<void>} [options.wait] - bounded sleep.
536
- * @param {number} [options.selfCheckSeconds] - idle span for the self-check.
537
- * @param {number} [options.attentionSeconds] - idle span for `attention`.
538
- * @param {number} [options.waitSliceMs] - internal polling slice.
539
- * @param {(message: string, detail?: unknown) => void} [options.log] - diagnostic sink.
540
- */
541
- constructor(task, options = {}) {
542
- this.task = task;
543
- this.now = typeof options.now === 'function' ? options.now : Date.now;
544
- this.wait = typeof options.wait === 'function' ? options.wait : sleep;
545
- this.selfCheckMs = secondsToMs(options.selfCheckSeconds, 300);
546
- this.attentionMs = secondsToMs(options.attentionSeconds, 600);
547
- this.waitSliceMs = Number.isSafeInteger(options.waitSliceMs) && options.waitSliceMs > 0
548
- ? options.waitSliceMs
549
- : 1000;
550
- this.log = typeof options.log === 'function' ? options.log : null;
551
- this.activity = new TaskActivity({ now: this.now });
552
- /** Episode identity: bumped whenever genuine activity ends the idle episode. */
553
- this.episode = 0;
554
- /** The episode the self-check already ran for, or null. */
555
- this.checkedEpisode = null;
556
- /** The last self-check diagnostic, published on every summary. */
557
- this.selfCheck = { episode: null, checkedAt: null, verdict: null, detail: null };
558
- /**
559
- * When the most recent attention report was DELIVERED, and for which idle
560
- * episode.
561
- *
562
- * Exactly one pair, never a growing collection: the cooldown is a property of
563
- * the current silence, and an idle origin only moves forward, so an older entry
564
- * could never be reached again. `null` means "no attention has been delivered
565
- * for this episode yet".
566
- * @type {{ episode: number, origin: number, at: number } | null}
567
- */
568
- this.attentionDelivered = null;
569
- /**
570
- * Every observation currently waiting, so each one owns its own controller and
571
- * one observer can never cancel another. Bounded by the number of callers; an
572
- * entry is removed in its own `finally`.
573
- * @type {Set<object>}
574
- */
575
- this.waiters = new Set();
576
- this.disposed = false;
577
- }
578
-
579
- /**
580
- * Record one native event.
581
- *
582
- * Called from the runner's `onEvent` hook, which means it runs inside the
583
- * native dispatch path: nothing here may throw, await, or retain the event.
584
- * @param {unknown} event - native event object.
585
- * @param {number} [at] - observation time.
586
- * @returns {boolean} whether this event was real activity.
587
- */
588
- onEvent(event, at = this.now()) {
589
- if (this.disposed) return false;
590
- let observation;
591
- try {
592
- observation = classifyActivityEvent(event);
593
- } catch {
594
- // A malformed event is not a reason to disturb the run that produced it.
595
- return false;
596
- }
597
- try {
598
- const active = this.activity.record(observation, at);
599
- // Real activity ends the current idle episode. The episode identity is what
600
- // makes "once per episode" true for the self-check and the attention latch:
601
- // without it, a run that goes quiet, wakes, and goes quiet again would be
602
- // treated as the SAME silence and could never alert a second time.
603
- if (active) this.episode += 1;
604
- return active;
605
- } catch {
606
- return false;
607
- }
608
- }
609
-
610
- /**
611
- * The instant the current idle episode began.
612
- *
613
- * Before the executor has produced anything, the episode begins when its run
614
- * began — a model that never streams a token is silent from the start, and
615
- * measuring from "never" would hide it.
616
- * @returns {number} epoch milliseconds.
617
- */
618
- idleOrigin() {
619
- if (this.activity.lastActivityAt !== null) return this.activity.lastActivityAt;
620
- if (Number.isFinite(this.task?.startedAt)) return this.task.startedAt;
621
- if (Number.isFinite(this.task?.createdAt)) return this.task.createdAt;
622
- return this.now();
623
- }
624
-
625
- /**
626
- * Whether the current inactivity episode has reached the self-check threshold.
627
- * @param {number} [at] - reference time.
628
- * @returns {boolean} true when one read-only inspection is due.
629
- */
630
- selfCheckDue(at = this.now()) {
631
- return at - this.idleOrigin() >= this.selfCheckMs;
632
- }
633
-
634
- /**
635
- * Perform the 5-minute read-only inspection, at most once per idle episode.
636
- *
637
- * The inspection reads only what the engine itself already holds: whether the
638
- * task is alive, whether its executor settled, the phase, whether a permission
639
- * request is pending, and which tool call is outstanding. It performs no model
640
- * call, reads no diff or workspace file, changes no task state, and does not
641
- * touch the deadline.
642
- * @param {number} [at] - reference time.
643
- * @returns {object | null} the diagnostic, or null when none was due.
644
- */
645
- runSelfCheck(at = this.now()) {
646
- if (this.disposed) return null;
647
- if (!this.selfCheckDue(at)) return null;
648
- const episode = this.episode;
649
- if (this.checkedEpisode === episode) return null;
650
- this.checkedEpisode = episode;
651
- this.selfCheck = this.inspect(at, episode);
652
- return this.selfCheck;
653
- }
654
-
655
- /**
656
- * The last self-check diagnostic, or null when none ever ran.
657
- * @returns {object | null} diagnostic.
658
- */
659
- lastSelfCheck() {
660
- return this.selfCheck.checkedAt === null ? null : this.selfCheck;
661
- }
662
-
663
- /**
664
- * Build the read-only diagnostic for the current episode.
665
- * @param {number} at - reference time.
666
- * @param {number} episode - episode identity.
667
- * @returns {object} bounded diagnostic.
668
- */
669
- inspect(at, episode) {
670
- const task = this.task ?? {};
671
- const pending = task.permission?.pending ?? null;
672
- const span = this.activity.toolSpan(at);
673
- const idleMs = Math.max(0, at - this.idleOrigin());
674
- const nativeStarted = task.native?.started === true;
675
- const nativeSettled = task.native?.settled === true;
676
- let verdict;
677
- if (task.state === 'pending' || task.state === 'running') {
678
- if (pending !== null) verdict = 'waiting-for-permission';
679
- else if (span !== null) verdict = 'tool-running';
680
- else if (nativeStarted && !nativeSettled) verdict = 'executor-alive-silent';
681
- else if (!nativeStarted) verdict = 'executor-not-started';
682
- else verdict = 'idle-between-steps';
683
- } else {
684
- verdict = 'settled';
685
- }
686
- return {
687
- episode,
688
- checkedAt: at,
689
- idleMs,
690
- verdict,
691
- detail: {
692
- state: typeof task.state === 'string' ? task.state : null,
693
- phase: typeof task.phase === 'string' ? task.phase : null,
694
- nativeStarted,
695
- nativeSettled,
696
- permissionPending: pending !== null,
697
- permissionRequestId: pending !== null && typeof pending.requestId === 'string' ? pending.requestId : null,
698
- phaseIsPermissionWait: task.phase === PHASE_AWAITING_PERMISSION,
699
- currentTool: span === null ? null : { name: span.name, callId: span.callId, elapsedMs: span.elapsedMs },
700
- lastActivityAt: this.activity.lastActivityAt,
701
- activityEvents: this.activity.activityEvents(),
702
- events: this.activity.totalEvents(),
703
- },
704
- };
705
- }
706
-
707
- /**
708
- * Whether the current silence is old enough for an attention report, ignoring the
709
- * cooldown of an earlier delivery.
710
- * @param {number} [at] - reference time.
711
- * @returns {boolean} true when the idle span has reached the threshold.
712
- */
713
- attentionDue(at = this.now()) {
714
- return at - this.idleOrigin() >= this.attentionMs;
715
- }
716
-
717
- /**
718
- * The instant the next attention report may be delivered, or `Infinity` while the
719
- * thresholds have not been reached at all.
720
- *
721
- * The rule is a cooldown, not a one-shot latch: the FIRST report is due at
722
- * `idleOrigin + attentionSeconds`, and every later report for the same silence
723
- * needs a FURTHER `attentionSeconds` since the previous delivery. Genuine
724
- * activity resets both the origin and the delivery record, so a run that goes
725
- * quiet again can alert again.
726
- * @returns {number} the next deliverable instant.
727
- */
728
- nextAttentionAt() {
729
- const origin = this.idleOrigin();
730
- const delivered = this.attentionDelivered;
731
- let next = origin + this.attentionMs;
732
- if (delivered !== null && delivered.episode === this.episode && delivered.origin === origin) {
733
- next = Math.max(next, delivered.at + this.attentionMs);
734
- }
735
- return next;
736
- }
737
-
738
- /**
739
- * Whether an attention report may be delivered at `at`, and atomically claims it
740
- * if so.
741
- *
742
- * The claim happens in the same synchronous step as the test, so two observers
743
- * reaching the threshold together cannot both return `attention`: the first
744
- * claims, the second observes the fresh delivery record and keeps waiting.
745
- * @param {number} [at] - delivery instant.
746
- * @returns {boolean} true for the observer that won the claim.
747
- */
748
- claimAttention(at = this.now()) {
749
- if (at < this.nextAttentionAt()) return false;
750
- this.attentionDelivered = { episode: this.episode, origin: this.idleOrigin(), at };
751
- return true;
752
- }
753
-
754
- /**
755
- * Publishable activity summary for a task view.
756
- *
757
- * `toolActive` is passed by the caller because only the engine can decide what a
758
- * long tool span means: a pending permission request already reports its own
759
- * reason, and a settled run is not "waiting on a tool" at all.
760
- * @param {object} [options] - `at` reference time, `toolActive`.
761
- * @returns {object} bounded summary.
762
- */
763
- snapshot({ at = this.now(), toolActive = false } = {}) {
764
- const summary = this.activity.summary({ at, toolActive });
765
- return {
766
- ...summary,
767
- // Stated so a reader never has to derive the thresholds from a settings
768
- // document that may have changed since this task froze its own.
769
- selfCheckSeconds: Math.round(this.selfCheckMs / 1000),
770
- attentionSeconds: Math.round(this.attentionMs / 1000),
771
- idleForMs: this.activity.idleForMs(at),
772
- selfCheck: {
773
- episode: this.selfCheck.episode,
774
- checkedAt: this.selfCheck.checkedAt,
775
- verdict: this.selfCheck.verdict,
776
- },
777
- };
778
- }
779
-
780
- /**
781
- * Release every waiter this monitor owns. Called only by {@link dispose}.
782
- *
783
- * Each waiter aborts its own controller; one observation ending never touches
784
- * another.
785
- * @returns {void}
786
- */
787
- releaseWaiters() {
788
- for (const waiter of [...this.waiters]) {
789
- try {
790
- waiter.controller.abort();
791
- } catch {
792
- // Abort is idempotent.
793
- }
794
- }
795
- this.waiters.clear();
796
- }
797
-
798
- /**
799
- * The bounded observation wait documented for adapters (HTTP/MCP).
800
- *
801
- * What it reports, in precedence order, re-checked on every slice:
802
- *
803
- * 1. `interrupted` — this observer's own signal aborted, or the monitor was
804
- * disposed. The WORKER is untouched;
805
- * 2. `ready`/`failed`/`cancelled` — the task reached a terminal state. This wins
806
- * over a disposal wake, so an observation released by engine teardown still
807
- * reports the outcome the run actually reached;
808
- * 3. `permission` — a per-call decision is outstanding. Waiting for approval is
809
- * not a stall;
810
- * 4. `attention` — the silence reached `attentionSeconds` (once, then on the
811
- * cooldown) AND the claim was won. Genuine progress never produces this: it
812
- * resets the silence instead, which is the whole point of the feature;
813
- * 5. `heartbeat` — the bounded wait expired with nothing to report.
814
- *
815
- * The self-check runs inside the loop, so a monitor with no observer costs
816
- * nothing. Every caller gets its own controller and timer, so an observation
817
- * never cancels another.
818
- * @param {object} [options] - `waitMs`, `signal`.
819
- * @returns {Promise<{ reason: string, activitySinceWait: boolean, waitedMs: number, selfCheck: object | null }>} outcome.
820
- */
821
- async observe(options = {}) {
822
- const signal = options.signal ?? null;
823
- // A terminal outcome is a READ of the task record, so it is answered even by a
824
- // disposed monitor: engine teardown stops the observation loops, but it must
825
- // never turn a finished run into "interrupted".
826
- const settledNow = terminalReason(this.task);
827
- if (settledNow !== null) return this.outcome(settledNow, false, 0, this.lastSelfCheck());
828
- if (this.disposed) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
829
- if (signal !== null && signal.aborted === true) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
830
-
831
- const waitMs = boundedWait(options.waitMs);
832
- const startedAt = this.now();
833
- const startingSequence = this.activity.sequence;
834
- const waiter = { controller: new AbortController() };
835
- this.waiters.add(waiter);
836
- const onAbort = () => {
837
- try {
838
- waiter.controller.abort();
839
- } catch {
840
- // Unreachable; abort is idempotent.
841
- }
842
- };
843
- if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
844
-
845
- let selfCheck = null;
846
- try {
847
- for (;;) {
848
- const at = this.now();
849
- const activitySinceWait = this.activity.sequence !== startingSequence;
850
- // A pure read of local facts, run BEFORE any reason is returned so every
851
- // report carries the diagnostic that explains the silence.
852
- const checked = this.runSelfCheck(at);
853
- if (checked !== null) selfCheck = checked;
854
-
855
- // (2) The run's own outcome outranks a wake-up: a task that ended must be
856
- // reported as ended even if the monitor was disposed in the same instant.
857
- const terminal = terminalReason(this.task);
858
- if (terminal !== null) return this.outcome(terminal, activitySinceWait, at - startedAt, selfCheck);
859
-
860
- // (1) Only one's OWN abort (or disposal) interrupts.
861
- if (this.disposed || waiter.controller.aborted === true || (signal !== null && signal.aborted === true)) {
862
- return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, at - startedAt, selfCheck);
863
- }
864
-
865
- if (this.task?.permission?.pending !== null && this.task?.permission?.pending !== undefined) {
866
- return this.outcome(OBSERVE_REASONS.permission, activitySinceWait, at - startedAt, selfCheck);
867
- }
868
- // (4) `claimAttention` is false while genuine progress has reset the clock,
869
- // because the origin moved into the future relative to `nextAttentionAt()`.
870
- if (this.claimAttention(at)) {
871
- return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck);
872
- }
873
- const elapsed = at - startedAt;
874
- if (elapsed >= waitMs) {
875
- return this.outcome(OBSERVE_REASONS.heartbeat, activitySinceWait, elapsed, selfCheck);
876
- }
877
- const untilAttention = this.nextAttentionAt() - at;
878
- const slice = Math.max(1, Math.min(this.waitSliceMs, waitMs - elapsed, untilAttention));
879
- try {
880
- await this.wait(slice, { signal: waiter.controller.signal });
881
- } catch {
882
- // A wait seam that rejects ends THIS observation only. The worker and
883
- // every other observer are untouched.
884
- return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, this.now() - startedAt, selfCheck);
885
- }
886
- }
887
- } finally {
888
- this.waiters.delete(waiter);
889
- if (signal !== null) signal.removeEventListener?.('abort', onAbort);
890
- }
891
- }
892
-
893
- /**
894
- * Build one observation outcome.
895
- * @param {string} reason - reported reason.
896
- * @param {boolean} activitySinceWait - whether progress arrived during the wait.
897
- * @param {number} waitedMs - observed duration.
898
- * @param {object | null} selfCheck - the last self-check diagnostic.
899
- * @returns {object} outcome.
900
- */
901
- outcome(reason, activitySinceWait, waitedMs, selfCheck) {
902
- return {
903
- reason,
904
- activitySinceWait: activitySinceWait === true,
905
- waitedMs: Math.max(0, Math.trunc(waitedMs)),
906
- selfCheck,
907
- };
908
- }
909
-
910
- /**
911
- * Drop every listener/timer this monitor owns. Idempotent.
912
- *
913
- * Marking the activity final first freezes the elapsed values at the end
914
- * recorded on the task, so nothing published afterwards grows.
915
- * @param {number} [endedAt] - the run's recorded end, when known.
916
- * @returns {void}
917
- */
918
- dispose(endedAt = undefined) {
919
- if (typeof endedAt === 'number') this.activity.finalize(endedAt);
920
- if (this.disposed) return;
921
- this.disposed = true;
922
- this.releaseWaiters();
923
- }
924
- }
925
-
926
- /**
927
- * Whether one internal reason may be handed to a caller.
928
- * @param {string} reason - reason value.
929
- * @returns {boolean} true when a caller should receive it.
930
- */
931
- export function isPublicReason(reason) {
932
- return typeof reason === 'string' && Object.values(OBSERVE_REASONS).includes(reason) && !INTERNAL_REASONS.has(reason);
933
- }
934
-
935
- /**
936
- * The reason a task's current state implies, or null while it is still running.
937
- * @param {object} task - engine task record.
938
- * @returns {string | null} reason.
939
- */
940
- export function terminalReason(task) {
941
- const state = task?.state;
942
- if (typeof state !== 'string') return null;
943
- return TERMINAL_REASON[state] ?? null;
944
- }
945
-
946
- /**
947
- * Clamp a caller-requested wait to the documented bound.
948
- * @param {unknown} waitMs - requested wait.
949
- * @returns {number} a whole number of milliseconds within bounds.
950
- */
951
- function boundedWait(waitMs) {
952
- if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs <= 0) return 25_000;
953
- return Math.min(25_000, Math.max(1, Math.trunc(waitMs)));
954
- }
955
-
956
- /**
957
- * Convert a validated seconds threshold to milliseconds, with the documented
958
- * default when the value is absent.
959
- * @param {unknown} value - seconds.
960
- * @param {number} fallbackSeconds - default.
961
- * @returns {number} milliseconds.
962
- */
963
- function secondsToMs(value, fallbackSeconds) {
964
- const seconds = Number.isSafeInteger(value) && value > 0 ? value : fallbackSeconds;
965
- return seconds * 1000;
966
- }
967
-
968
- /**
969
- * Default wait seam: a real, unref'd timeout that honours an abort signal.
970
- *
971
- * `unref()` matters: an observation waiting on a timer must not by itself keep the
972
- * process alive, and the timer is cleared on abort so an abandoned observation
973
- * leaves nothing behind.
974
- * @param {number} ms - slice length.
975
- * @param {object} [options] - `signal`.
976
- * @returns {Promise<void>} resolves after the slice.
977
- */
978
- export function sleep(ms, options = {}) {
979
- const signal = options?.signal ?? null;
980
- return new Promise((resolvePromise, rejectPromise) => {
981
- if (signal !== null && signal.aborted === true) {
982
- rejectPromise(abortError());
983
- return;
984
- }
985
- const timer = setTimeout(() => {
986
- cleanup();
987
- resolvePromise();
988
- }, ms);
989
- timer.unref?.();
990
- const onAbort = () => {
991
- cleanup();
992
- rejectPromise(abortError());
993
- };
994
- const cleanup = () => {
995
- clearTimeout(timer);
996
- if (signal !== null) signal.removeEventListener?.('abort', onAbort);
997
- };
998
- if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
999
- });
1000
- }
1001
-
1002
- /** @returns {Error} a DOM-shaped abort error. */
1003
- function abortError() {
1004
- const error = new Error('the wait was aborted');
1005
- error.name = 'AbortError';
1006
- return error;
1007
- }
1008
-
1
+ // Bounded activity bookkeeping for one running delegated task.
2
+ //
3
+ // This module answers exactly one question — "has this executor been silent, and
4
+ // for how long?" — and records the minimum needed to answer it. It is deliberately
5
+ // not a transcript, not a progress model and not a log:
6
+ //
7
+ // * **Only metadata is retained.** An event contributes a KIND, a COUNT and a
8
+ // timestamp. Reasoning text, assistant text, tool result bodies and tool
9
+ // arguments are read only far enough to decide *whether the event was
10
+ // non-empty*; nothing derived from them is stored, so no buffer here can grow
11
+ // with model output and nothing here can leak a transcript into a view,
12
+ // a history row or a diagnostic.
13
+ // * **A published failure label is allowlisted, never echoed.** A tool's own
14
+ // `error.code`/`error.name` is free text that can carry a path or a token, so it
15
+ // travels only when it matches a small set of well-known codes; otherwise the
16
+ // generic `TOOL_ERROR` is published. The complete native identity is hashed for
17
+ // episode distinction only, and no free text (reason, result content) is retained.
18
+ // * **The vocabulary is the harness's own.** The classified names are the
19
+ // durable `SessionEventMap` types of `@deepseek-ai/dsh-session` (`step/start`,
20
+ // `assistant/message`, `tool/call`, `tool/result`, plus the turn/step/usage
21
+ // boundaries), the two stream-chunk types `@deepseek-ai/dsh-llm` emits
22
+ // (`text-delta`, `reasoning-delta`), and the nested streaming envelopes the
23
+ // runner accepts (`message/part`, `assistant/delta` wrapping a delta). An
24
+ // event this module does not recognise is `unrelated`, which by contract never
25
+ // resets idleness.
26
+ // * **Only real activity resets the clock.** A non-empty output or reasoning
27
+ // delta — top-level OR nested inside a streaming envelope — an assistant
28
+ // message carrying text or reasoning, a step that actually started, a native
29
+ // tool call and a tool result are activity. Empty deltas, bookkeeping events,
30
+ // connection heartbeats and result polling are NOT: if they reset the clock, a
31
+ // hung executor would look busy forever and the whole silent-wait mechanism
32
+ // would never fire.
33
+ // * **Silence, not duration, raises attention.** An open tool call changes how the
34
+ // silence is DESCRIBED (`waitingOn: 'tool'`, with the call's elapsed span and a
35
+ // `tool-running` self-check verdict) but not WHETHER it counts: a tool that
36
+ // emits nothing for five minutes gets the self-check and for ten minutes gets
37
+ // attention, exactly like any other silent executor. Treating an open call as
38
+ // proof of progress would hide a genuinely hung tool. Nothing here ever fails,
39
+ // cancels or restarts a run because of duration.
40
+ //
41
+ // The clock is injected (`now`) so tests can simulate twenty minutes of real
42
+ // progress deterministically instead of sleeping.
43
+
44
+ import { createHash } from 'node:crypto';
45
+ import { REPEATED_FAILURE_KIND } from './diagnostics.js';
46
+
47
+ /**
48
+ * How one event kind is classified for idleness.
49
+ *
50
+ * `activity` — the executor demonstrably produced something; resets the idle clock.
51
+ * `structure` — a lifecycle boundary (turn/step boundaries, usage, an empty
52
+ * delta). Observed and counted, never treated as progress.
53
+ * `unrelated` — anything this build does not classify, including heartbeat and
54
+ * polling traffic on an unrelated channel.
55
+ */
56
+ export const ACTIVITY_KINDS = Object.freeze({
57
+ activity: 'activity',
58
+ structure: 'structure',
59
+ unrelated: 'unrelated',
60
+ });
61
+
62
+ /** How many distinct event types one summary keeps counts for. */
63
+ const MAX_KIND_COUNTS = 32;
64
+
65
+ /** Bound on a recorded tool name or call id; they are identifiers, not content. */
66
+ const MAX_IDENTIFIER_CHARS = 200;
67
+
68
+ /** Settled call ids remembered so a completion can be matched to its start. */
69
+ const MAX_TRACKED_CALL_IDS = 64;
70
+
71
+ /**
72
+ * Session event types that are PROGRESS, keyed to the evidence they carry.
73
+ *
74
+ * These are `SessionEventMap` members of `@deepseek-ai/dsh-session` (and, for the
75
+ * two delta names, `StreamChunk` types of `@deepseek-ai/dsh-llm`, which reach the
76
+ * same listener). Whether a given event is *genuine* progress is decided by
77
+ * {@link observeProgress}: several of these can arrive carrying nothing.
78
+ */
79
+ const ACTIVITY_EVENT_TYPES = Object.freeze({
80
+ // The loop streamed model output. Genuine only when the delta is non-empty.
81
+ 'text-delta': 'output-delta',
82
+ 'reasoning-delta': 'reasoning-delta',
83
+ // Nested streaming envelopes: `data.delta` carries the same chunk shape. The
84
+ // runner accepts both spellings, so both must be classified — treating them as
85
+ // structural would hide every token of a run that streams nested.
86
+ 'message/part': 'output-delta',
87
+ 'assistant/delta': 'output-delta',
88
+ // The settled assistant message for one step. Genuine only when it carries text
89
+ // or reasoning; an empty message is a structural event.
90
+ 'assistant/message': 'assistant-message',
91
+ // A step actually opened: the model was called.
92
+ 'step/start': 'model-step',
93
+ // The model requested one tool invocation.
94
+ 'tool/call': 'tool-call',
95
+ // One tool call settled with a model-facing result.
96
+ 'tool/result': 'tool-result',
97
+ });
98
+
99
+ /**
100
+ * Session event types that only ever open, close or describe a step.
101
+ *
102
+ * `assistant/message` is handled separately: it is progress only when it carries
103
+ * content, which is the difference between the settled answer and an empty message.
104
+ */
105
+ const STRUCTURE_EVENT_TYPES = Object.freeze(new Set([
106
+ 'turn/start',
107
+ 'turn/end',
108
+ 'step/end',
109
+ 'assistant/attempt',
110
+ 'usage',
111
+ ]));
112
+
113
+ /**
114
+ * Classify one native event.
115
+ *
116
+ * @param {unknown} event - the object handed to `request.onEvent`.
117
+ * @returns {{ kind: string, type: string | null, label: string, activity: boolean, tool: object | null }} classification.
118
+ */
119
+ export function classifyActivityEvent(event) {
120
+ const unrelated = { kind: ACTIVITY_KINDS.unrelated, type: null, label: 'unrelated', activity: false, tool: null };
121
+ if (event === null || typeof event !== 'object') return unrelated;
122
+ const type = typeof event.type === 'string' ? event.type : null;
123
+ if (type === null) return unrelated;
124
+
125
+ const progress = ACTIVITY_EVENT_TYPES[type];
126
+ if (progress !== undefined) {
127
+ const observed = observeProgress(type, event);
128
+ return {
129
+ kind: observed.activity ? ACTIVITY_KINDS.activity : ACTIVITY_KINDS.structure,
130
+ type,
131
+ label: observed.activity ? progress : `${progress}-empty`,
132
+ activity: observed.activity,
133
+ tool: observed.tool,
134
+ };
135
+ }
136
+ if (STRUCTURE_EVENT_TYPES.has(type)) {
137
+ return { kind: ACTIVITY_KINDS.structure, type, label: type, activity: false, tool: null };
138
+ }
139
+ return unrelated;
140
+ }
141
+
142
+ /**
143
+ * Read one progress-shaped event far enough to decide whether it carried
144
+ * anything, and to recover the tool identity when it names one.
145
+ *
146
+ * This is the only place that touches payload fields. It reads text/content ONLY
147
+ * to test emptiness: no string is returned, stored or concatenated.
148
+ * @param {string} type - event type.
149
+ * @param {object} event - event object.
150
+ * @returns {{ activity: boolean, tool: object | null }} observation.
151
+ */
152
+ function observeProgress(type, event) {
153
+ if (type === 'text-delta' || type === 'reasoning-delta') {
154
+ const text = payloadOf(event).text;
155
+ // A delta that carries no characters says nothing about progress: the loop
156
+ // can emit an empty chunk while waiting on the provider. A whitespace-only
157
+ // delta is still model output, so it counts.
158
+ return { activity: typeof text === 'string' && text !== '', tool: null };
159
+ }
160
+ if (type === 'message/part' || type === 'assistant/delta') {
161
+ // Nested streaming envelope: the chunk lives under `data.delta` (the runner
162
+ // accepts `data.delta`, `delta`, then `data` itself). Only the delta's TYPE and
163
+ // the emptiness of its text are read; the text is never returned.
164
+ const payload = payloadOf(event);
165
+ const delta = payload.delta ?? event.delta ?? payload;
166
+ if (delta === null || typeof delta !== 'object') return { activity: false, tool: null };
167
+ const deltaType = delta.type;
168
+ if (deltaType !== 'text-delta' && deltaType !== 'reasoning-delta') {
169
+ return { activity: false, tool: null };
170
+ }
171
+ const text = delta.text;
172
+ return { activity: typeof text === 'string' && text !== '', tool: null };
173
+ }
174
+ if (type === 'assistant/message') {
175
+ const payload = payloadOf(event);
176
+ const message = payload.message ?? event.message ?? null;
177
+ const content = Array.isArray(message?.content) ? message.content : [];
178
+ for (const block of content) {
179
+ if (block === null || typeof block !== 'object') continue;
180
+ if ((block.type === 'text' || block.type === 'reasoning')
181
+ && typeof block.text === 'string' && block.text !== '') {
182
+ return { activity: true, tool: null };
183
+ }
184
+ }
185
+ return { activity: false, tool: null };
186
+ }
187
+ if (type === 'tool/call') {
188
+ // `payloadOf` already falls back to the event object itself, so this reads
189
+ // `data.name` when the native envelope is present and a top-level `name`
190
+ // otherwise. The ARGUMENTS are deliberately not read at all, so this module
191
+ // cannot retain or forward them.
192
+ const payload = payloadOf(event);
193
+ const name = identifier(payload.name);
194
+ const callId = identifier(payload.callId ?? payload.id);
195
+ return { activity: name !== null, tool: { name, callId } };
196
+ }
197
+ if (type === 'tool/result') {
198
+ // Native shape: `data.message.toolCallId` (the tool-role result message).
199
+ const message = payloadOf(event).message;
200
+ const callId = identifier(message?.toolCallId ?? payloadOf(event).callId);
201
+ // Any settled tool result is progress, including a failed one: the tool ran.
202
+ return { activity: true, tool: { name: null, callId } };
203
+ }
204
+ if (type === 'step/start') {
205
+ return { activity: true, tool: null };
206
+ }
207
+ return { activity: false, tool: null };
208
+ }
209
+
210
+ /**
211
+ * The payload of a native event.
212
+ *
213
+ * Native events carry their payload under `data` (`{ type, seq, time, data }`),
214
+ * and the streaming shapes a fake or a legacy emitter produces put the same fields
215
+ * at the top level. Both spellings are accepted, `data` first.
216
+ * @param {object} event - event object.
217
+ * @returns {object} payload object (never null).
218
+ */
219
+ function payloadOf(event) {
220
+ const data = event.data;
221
+ if (data !== null && typeof data === 'object' && !Array.isArray(data)) return data;
222
+ return event;
223
+ }
224
+
225
+ /**
226
+ * Bound an identifier-shaped value (a tool name or a call id).
227
+ *
228
+ * Bounded and type-checked, never interpreted: these names are published so an
229
+ * operator can see WHAT is running, and a pathological value cannot grow a view.
230
+ * @param {unknown} value - candidate.
231
+ * @returns {string | null} bounded identifier, or null.
232
+ */
233
+ function identifier(value) {
234
+ if (typeof value !== 'string') return null;
235
+ const trimmed = value.slice(0, MAX_IDENTIFIER_CHARS);
236
+ return trimmed === '' ? null : trimmed;
237
+ }
238
+
239
+ /**
240
+ * Bounded activity state of one running task.
241
+ *
242
+ * Owned by the engine's per-task monitor. Every field is a scalar or a small
243
+ * bounded map; there is no reference to the event object that produced it.
244
+ */
245
+ export class TaskActivity {
246
+ /**
247
+ * @param {object} [options] - `now` clock override (tests).
248
+ */
249
+ constructor(options = {}) {
250
+ /** @type {() => number} */
251
+ this.now = typeof options.now === 'function' ? options.now : Date.now;
252
+ /** @type {number | null} */
253
+ this.lastActivityAt = null;
254
+ /** @type {number} */
255
+ this.replacements = 0;
256
+ /** @type {{ name: string | null, callId: string | null, startedAt: number } | null} */
257
+ this.tool = null;
258
+ /** Settled tool calls represented as a count only — never their content. */
259
+ this.toolCallsStarted = 0;
260
+ this.toolCallsFinished = 0;
261
+ this.lastToolName = null;
262
+ this.lastToolDurationMs = null;
263
+ /** @type {Map<string, number>} */
264
+ this.counts = new Map();
265
+ /** @type {Map<string, number>} */
266
+ this.openCalls = new Map();
267
+ /** @type {Map<string, number>} */
268
+ this.eventCounts = new Map();
269
+ /** Bumped on every genuine activity; used to reset one wait's episode view. */
270
+ this.sequence = 0;
271
+ /**
272
+ * Genuine activity events, counted independently of the label map.
273
+ *
274
+ * The map is bounded and its keys can be evicted, so summing it would make the
275
+ * published count both imprecise (structure and unrelated labels would be
276
+ * included) and lossy. This counter is only ever incremented for real progress.
277
+ */
278
+ this.activityCount = 0;
279
+ /** Total observations, counted independently of the bounded per-type map. */
280
+ this.eventCount = 0;
281
+ /**
282
+ * Set once the run reached a terminal state. From then on every elapsed value is
283
+ * measured against the recorded end, so a stored record cannot appear to keep
284
+ * growing (a "tool running for 4 hours" that ended twenty minutes ago).
285
+ * @type {{ endedAt: number } | null}
286
+ */
287
+ this.final = null;
288
+ }
289
+
290
+ /**
291
+ * Record one observation.
292
+ *
293
+ * @param {object} observation - result of {@link classifyActivityEvent}.
294
+ * @param {number} [at] - observation timestamp.
295
+ * @returns {boolean} whether this observation was real activity.
296
+ */
297
+ record(observation, at = this.now()) {
298
+ assertObservation(observation);
299
+ if (this.final !== null) return false;
300
+ this.replacements += 1;
301
+ if (this.eventCount < Number.MAX_SAFE_INTEGER) this.eventCount += 1;
302
+ const counted = this.counts.get(observation.label) ?? 0;
303
+ if (counted < Number.MAX_SAFE_INTEGER) this.counts.set(observation.label, counted + 1);
304
+ if (observation.type !== null) {
305
+ const perType = this.eventCounts.get(observation.type) ?? 0;
306
+ if (perType < Number.MAX_SAFE_INTEGER) this.eventCounts.set(observation.type, perType + 1);
307
+ }
308
+ this.pruneCounts();
309
+ if (observation.tool !== null) this.recordTool(observation.tool, at);
310
+ if (observation.activity !== true) return false;
311
+ if (this.activityCount < Number.MAX_SAFE_INTEGER) this.activityCount += 1;
312
+ this.lastActivityAt = at;
313
+ this.sequence += 1;
314
+ return true;
315
+ }
316
+
317
+ /**
318
+ * Freeze every elapsed value at the instant the run ended.
319
+ *
320
+ * Called once, when the task reaches a terminal state. A view or a stored record
321
+ * read an hour later then reports the span the run actually had, not an idle or
322
+ * tool-elapsed duration that keeps growing for a run nobody is following.
323
+ * @param {number} endedAt - the recorded end time.
324
+ * @returns {void}
325
+ */
326
+ finalize(endedAt) {
327
+ if (this.final !== null) return;
328
+ const at = Number.isFinite(endedAt) ? endedAt : this.now();
329
+ this.final = { endedAt: at };
330
+ }
331
+
332
+ /**
333
+ * The reference time elapsed values are measured against.
334
+ *
335
+ * Live: the caller's `at`. Finalized: the recorded end, so nothing grows.
336
+ * @param {number} at - requested reference time.
337
+ * @returns {number} the effective reference time.
338
+ */
339
+ referenceTime(at) {
340
+ if (this.final !== null) return this.final.endedAt;
341
+ return at;
342
+ }
343
+
344
+ /**
345
+ * Track the tool call a `tool/call` (or `tool/result`) event named.
346
+ *
347
+ * A start opens a span; a result closes the matching span and records how long
348
+ * it ran. Nothing about the tool's arguments or result is kept.
349
+ * @param {{ name: string | null, callId: string | null }} tool - identity.
350
+ * @param {number} at - observation timestamp.
351
+ * @returns {void}
352
+ */
353
+ recordTool(tool, at) {
354
+ const callId = tool.callId;
355
+ if (tool.name !== null) {
356
+ this.lastToolName = tool.name;
357
+ this.toolCallsStarted += 1;
358
+ this.tool = { name: tool.name, callId, startedAt: at };
359
+ if (callId !== null) {
360
+ this.openCalls.set(callId, at);
361
+ while (this.openCalls.size > MAX_TRACKED_CALL_IDS) {
362
+ const oldest = this.openCalls.keys().next();
363
+ if (oldest.done === true) break;
364
+ this.openCalls.delete(oldest.value);
365
+ }
366
+ }
367
+ return;
368
+ }
369
+ if (callId !== null && this.openCalls.has(callId)) {
370
+ const startedAt = this.openCalls.get(callId);
371
+ this.openCalls.delete(callId);
372
+ this.lastToolDurationMs = Math.max(0, at - startedAt);
373
+ this.toolCallsFinished += 1;
374
+ if (this.tool !== null && this.tool.callId === callId) this.tool = null;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Keep the counters bounded.
380
+ *
381
+ * Both maps are keyed by a closed vocabulary (the labels and types this module
382
+ * classifies), so they cannot grow with model output; the cap exists so a future
383
+ * classifier that learns more keys cannot turn this into unbounded memory.
384
+ * @returns {void}
385
+ */
386
+ pruneCounts() {
387
+ while (this.counts.size > MAX_KIND_COUNTS) {
388
+ const oldest = this.counts.keys().next();
389
+ if (oldest.done === true) break;
390
+ this.counts.delete(oldest.value);
391
+ }
392
+ while (this.eventCounts.size > MAX_KIND_COUNTS) {
393
+ const oldest = this.eventCounts.keys().next();
394
+ if (oldest.done === true) break;
395
+ this.eventCounts.delete(oldest.value);
396
+ }
397
+ }
398
+
399
+ /** @returns {number} total observations recorded. */
400
+ totalEvents() {
401
+ return this.eventCount;
402
+ }
403
+
404
+ /** @returns {number} genuine activity events. */
405
+ activityEvents() {
406
+ return this.activityCount;
407
+ }
408
+
409
+ /**
410
+ * Milliseconds since the last genuine activity, or null when there was none.
411
+ * @param {number} [at] - reference time.
412
+ * @returns {number | null} idle span.
413
+ */
414
+ idleForMs(at = this.now()) {
415
+ if (this.lastActivityAt === null) return null;
416
+ return Math.max(0, this.referenceTime(at) - this.lastActivityAt);
417
+ }
418
+
419
+ /**
420
+ * The pending tool span, described without any argument or result text.
421
+ * @param {number} [at] - reference time.
422
+ * @returns {{ name: string | null, callId: string | null, startedAt: number, elapsedMs: number } | null} span.
423
+ */
424
+ toolSpan(at = this.now()) {
425
+ if (this.tool === null) return null;
426
+ return {
427
+ name: this.tool.name,
428
+ callId: this.tool.callId,
429
+ startedAt: this.tool.startedAt,
430
+ elapsedMs: Math.max(0, this.referenceTime(at) - this.tool.startedAt),
431
+ };
432
+ }
433
+
434
+ /**
435
+ * The bounded, publishable summary of this activity.
436
+ *
437
+ * Everything here is a count, a timestamp or an identifier. There is no field a
438
+ * text fragment, an argument or a result body could be carried in.
439
+ * @param {object} [options] - `at` reference time, `toolActive` whether a tool
440
+ * call is currently outstanding.
441
+ * @returns {object} summary.
442
+ */
443
+ summary({ at = this.now(), toolActive = false } = {}) {
444
+ const span = toolActive ? this.toolSpan(at) : null;
445
+ return {
446
+ lastActivityAt: this.lastActivityAt,
447
+ // `idleForMs` is the honest silence span. While a native tool call is
448
+ // outstanding the executor is working, not idle, so the same field reports
449
+ // the tool's elapsed span and `waitingOn` says which of the two it is.
450
+ idleForMs: span === null ? this.idleForMs(at) : span.elapsedMs,
451
+ waitingOn: span === null ? 'idle' : 'tool',
452
+ currentTool: span === null
453
+ ? null
454
+ : { name: span.name, callId: span.callId, startedAt: span.startedAt, elapsedMs: span.elapsedMs },
455
+ lastTool: this.lastToolName === null
456
+ ? null
457
+ : { name: this.lastToolName, durationMs: this.lastToolDurationMs },
458
+ events: this.totalEvents(),
459
+ activityEvents: this.activityEvents(),
460
+ toolCallsStarted: this.toolCallsStarted,
461
+ toolCallsFinished: this.toolCallsFinished,
462
+ // Stated when the record was frozen, so a reader can tell "this is the final
463
+ // span" from "this is still being measured".
464
+ finalizedAt: this.final === null ? null : this.final.endedAt,
465
+ // Per-kind counts, bounded and sorted for a stable view.
466
+ kinds: Object.fromEntries([...this.counts.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
467
+ };
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Guard against a caller passing a value this class cannot read.
473
+ * @param {unknown} observation - candidate observation.
474
+ * @returns {void}
475
+ */
476
+ function assertObservation(observation) {
477
+ if (observation === null || typeof observation !== 'object') {
478
+ throw new TypeError('activity observation must be an object');
479
+ }
480
+ }
481
+
482
+ /** The kind carried in an `attention` diagnostic that reports repeated failures. */
483
+ export { REPEATED_FAILURE_KIND };
484
+
485
+ /** Bound on tracked calls and on retained failure episodes. */
486
+ const MAX_TRACKED_FAILURES = 32;
487
+
488
+ /**
489
+ * Detects the same tool failing the same way over and over, and says so ONCE.
490
+ *
491
+ * Independent of the silence clock: a run can be busy and still be retrying the same
492
+ * broken operation, which is exactly what neither existing timer catches.
493
+ *
494
+ * What is a failure: ONLY the native structured marker on a settled call —
495
+ * `tool/result.message.isError === true` (the durable `ToolResultMessage` contract).
496
+ * Text containing "error", a quiet run, reasoning-only output, a long test or a run
497
+ * that changed no files are never treated as failures.
498
+ *
499
+ * What is retained: a tool name, a sanitized failure code, a 16-hex digest of
500
+ * (tool + operation + code + the error's own reason text), counts and two timestamps.
501
+ * Arguments, result content, the reason text itself and model output are read only to
502
+ * compute that digest and are never stored, published or forwarded.
503
+ *
504
+ * Identity: tool + operation + code + reason digest. Two failures with the same code but
505
+ * a different REAL reason ("file not found: a.txt" vs "file not found: b.txt") are
506
+ * different episodes, because the operation arguments are equal and the code is only the
507
+ * class of failure.
508
+ *
509
+ * When it fires: the same identity failing `threshold` times CONSECUTIVELY. A different
510
+ * identity starts a new episode; a success ends the current one; further failures in an
511
+ * already-reported episode do not report again. A later episode can report again.
512
+ */
513
+ export class RepeatedFailureTracker {
514
+ /**
515
+ * @param {object} [options] - `threshold` (0 disables), `digest` seam (tests only).
516
+ */
517
+ constructor(options = {}) {
518
+ const threshold = Number(options.threshold);
519
+ this.threshold = Number.isSafeInteger(threshold) && threshold > 0 ? threshold : 0;
520
+ this.digest = typeof options.digest === 'function' ? options.digest : sha256Hex;
521
+ /** callId -> { name, operationDigest } for calls whose result has not arrived yet. */
522
+ this.openCalls = new Map();
523
+ /**
524
+ * The episode being counted, or null:
525
+ * `{ identity, count, reported, code, tool, operationDigest, firstSeenAt, lastSeenAt }`.
526
+ */
527
+ this.episode = null;
528
+ /** Bounded evidence of reported episodes: hash and counts only. */
529
+ this.reported = [];
530
+ }
531
+
532
+ /**
533
+ * Record one `tool/call`. Arguments are hashed now and immediately dropped.
534
+ * @param {object} event - native `tool/call` event.
535
+ * @returns {void}
536
+ */
537
+ onCall(event) {
538
+ if (this.threshold === 0) return;
539
+ const payload = payloadOf(event);
540
+ const callId = identifier(payload.callId ?? payload.id);
541
+ const name = identifier(payload.name);
542
+ if (callId === null || name === null) return;
543
+ // The raw arguments string exists only as hash input; it is never retained.
544
+ const operation = typeof payload.arguments === 'string' ? payload.arguments : '';
545
+ this.openCalls.set(callId, { name, operationDigest: this.digest(operation).slice(0, 16) });
546
+ while (this.openCalls.size > MAX_TRACKED_FAILURES) {
547
+ const oldest = this.openCalls.keys().next();
548
+ if (oldest.done === true) break;
549
+ this.openCalls.delete(oldest.value);
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Record one `tool/result`.
555
+ *
556
+ * Answers whether this result is the threshold-th consecutive identical failure, in
557
+ * which case the caller reports it exactly once.
558
+ * @param {object} event - native `tool/result` event.
559
+ * @param {number} at - observation time.
560
+ * @returns {object | null} the diagnostic to report, or null.
561
+ */
562
+ onResult(event, at) {
563
+ if (this.threshold === 0) return null;
564
+ const payload = payloadOf(event);
565
+ const message = payload.message ?? null;
566
+ const callId = identifier(message?.toolCallId ?? payload.callId);
567
+ // A result with no matching call cannot be attributed. A DUPLICATE result for the
568
+ // same call is dropped here, because the call was consumed by the first one.
569
+ const call = callId === null ? undefined : this.openCalls.get(callId);
570
+ if (callId === null || call === undefined) return null;
571
+ this.openCalls.delete(callId);
572
+
573
+ if (message?.isError !== true) {
574
+ // A completed call ends the episode: whatever was failing is not failing now.
575
+ this.episode = null;
576
+ return null;
577
+ }
578
+ // The PUBLISHED label is an allowlisted code or the generic one; the COMPLETE native
579
+ // identity (code/name/reason, or the result content when the block is absent) is hashed
580
+ // so two failures that both publish `TOOL_ERROR` still separate into their own episodes.
581
+ // No free text is retained: only this 16-hex digest.
582
+ const code = failureCode(payload.error);
583
+ const identityHash = this.digest(failureIdentity(payload.error, message)).slice(0, 16);
584
+ const identity = `${call.name}\u0000${call.operationDigest}\u0000${code}\u0000${identityHash}`;
585
+ if (this.episode === null || this.episode.identity !== identity) {
586
+ this.episode = {
587
+ identity,
588
+ count: 0,
589
+ reported: false,
590
+ code,
591
+ tool: call.name,
592
+ operationDigest: call.operationDigest,
593
+ // A monotonically increasing internal sequence identifies the episode itself, so a
594
+ // parked reminder can be matched to it EXACTLY. A timestamp cannot do that: several
595
+ // episodes can start in the same millisecond, which is precisely how a stale
596
+ // reminder used to survive a switch to a different failure.
597
+ sequence: this.nextEpisode(),
598
+ // The FIRST failure of this episode, not the one that reached the threshold.
599
+ firstSeenAt: at,
600
+ lastSeenAt: at,
601
+ };
602
+ }
603
+ this.episode.count += 1;
604
+ this.episode.lastSeenAt = at;
605
+ if (this.episode.reported || this.episode.count < this.threshold) return null;
606
+ this.episode.reported = true;
607
+ const entry = {
608
+ kind: REPEATED_FAILURE_KIND,
609
+ toolName: call.name,
610
+ failureCode: code,
611
+ operationDigest: call.operationDigest,
612
+ consecutive: this.episode.count,
613
+ threshold: this.threshold,
614
+ firstSeenAt: this.episode.firstSeenAt,
615
+ lastSeenAt: this.episode.lastSeenAt,
616
+ // Internal only: matched against the parked reminder, never published.
617
+ episodeSequence: this.episode.sequence,
618
+ };
619
+ this.reported.push(entry);
620
+ while (this.reported.length > MAX_TRACKED_FAILURES) this.reported.shift();
621
+ // The internal `episodeSequence` stays on this object (the parked reminder is matched
622
+ // against the live episode through it) and is stripped at every PUBLICATION boundary:
623
+ // `claimFailureReport` and the snapshot projection below both drop it.
624
+ return { ...entry };
625
+ }
626
+
627
+ /** @returns {number} the next internal episode identifier. */
628
+ nextEpisode() {
629
+ this.episodeSequence = (this.episodeSequence ?? 0) + 1;
630
+ return this.episodeSequence;
631
+ }
632
+
633
+ /**
634
+ * Whether the currently parked reminder still describes the CURRENT episode.
635
+ *
636
+ * Matched by the episode's internal SEQUENCE, not by its fields or its start time. The
637
+ * fields can collide (two episodes can share a tool, a code, an operation digest and even
638
+ * a start millisecond), so any comparison built from them would let a stale reminder
639
+ * survive a switch to a genuinely different failure. A reminder is valid only while the
640
+ * sequence it was produced for is still the live one; `reported` stays as evidence.
641
+ * @param {object | null} report - a parked diagnostic.
642
+ * @returns {boolean} true when it still belongs to the live episode.
643
+ */
644
+ isCurrent(report) {
645
+ if (report === null || report === undefined) return false;
646
+ const episode = this.episode;
647
+ if (episode === null) return false;
648
+ return report.episodeSequence === episode.sequence;
649
+ }
650
+
651
+ /** Release the open-call map. The reported trail survives as bounded evidence. */
652
+ dispose() {
653
+ this.openCalls.clear();
654
+ }
655
+ }
656
+
657
+ /**
658
+ * Common tool failure codes that are safe to publish as-is.
659
+ *
660
+ * A closed allowlist, not a character filter. Substituting the punctuation of an arbitrary
661
+ * string does not redact it: `sk-TASKBRIDGE-MOCK-SECRET-987654321` and
662
+ * `/home/alice/.ssh/id_rsa` are already identifier-shaped, so a `[A-Za-z0-9._-]` cleanup
663
+ * would publish both unchanged. Only a value this list recognizes travels; everything else
664
+ * becomes {@link GENERIC_FAILURE_CODE}, and the FULL error identity is hashed internally so
665
+ * different failures still form different episodes.
666
+ * @type {ReadonlySet<string>}
667
+ */
668
+ const KNOWN_FAILURE_CODES = Object.freeze(new Set([
669
+ 'ABORT_ERR', 'ABORTED', 'ALREADY_EXISTS', 'AUTH', 'BUGBUG', 'CANCELLED', 'CONFLICT',
670
+ 'DENIED', 'EACCES', 'EAGAIN', 'EBADF', 'EBADMSG', 'EBUSY', 'ECANCELED', 'ECONNREFUSED',
671
+ 'ECONNRESET', 'EEXIST', 'EFBIG', 'EINTR', 'EINVAL', 'EIO', 'EISDIR', 'ELOOP', 'EMFILE',
672
+ 'ENAMETOOLONG', 'ENENT', 'ENFILE', 'ENOENT', 'ENOEXEC', 'ENOMEM', 'ENOSPC', 'ENOSYS',
673
+ 'ENOTDIR', 'ENOTEMPTY', 'ENOTFOUND', 'ENOTSUP', 'EPERM', 'EPIPE', 'ERANGE', 'EROFS',
674
+ 'ESRCH', 'ETIMEDOUT', 'ETXTBSY', 'EXDEV', 'FAILED', 'FORBIDDEN', 'INTERNAL', 'INVALID',
675
+ 'LIMIT', 'MISSING', 'NETWORK', 'NOTFOUND', 'NOT_FOUND', 'PERMISSION_DENIED', 'RATE_LIMIT',
676
+ 'REFUSED', 'SERVICE_UNAVAILABLE', 'TIMEOUT', 'UNAUTHORIZED', 'UNAVAILABLE', 'UNKNOWN',
677
+ 'UNSUPPORTED', 'VALIDATION',
678
+ ]));
679
+
680
+ /** The published code for any failure this build does not positively recognize. */
681
+ const GENERIC_FAILURE_CODE = 'TOOL_ERROR';
682
+
683
+ /**
684
+ * The stable, PUBLISHABLE failure code carried by a settled tool result.
685
+ *
686
+ * Both native fields (`error.code`, then `error.name`) are free-form strings a tool can fill
687
+ * with anything — including a path or a token that happens to be identifier-shaped. So the
688
+ * value is published only when it matches the closed allowlist above; otherwise the generic
689
+ * label is used. Nothing about the original string travels when it is not recognized, and
690
+ * the complete identity is still hashed internally for episode distinction.
691
+ * @param {unknown} error - the event's `error` block.
692
+ * @returns {string} an allowlisted code or {@link GENERIC_FAILURE_CODE}.
693
+ */
694
+ function failureCode(error) {
695
+ if (error !== null && typeof error === 'object') {
696
+ for (const key of ['code', 'name']) {
697
+ const value = error[key];
698
+ if (typeof value !== 'string') continue;
699
+ if (KNOWN_FAILURE_CODES.has(value.toUpperCase())) return value.toUpperCase();
700
+ }
701
+ }
702
+ return GENERIC_FAILURE_CODE;
703
+ }
704
+
705
+ /**
706
+ * The COMPLETE failure identity, used only as hash input for episode distinction.
707
+ *
708
+ * This is where an unrecognized code, a name and the free-text reason are allowed to
709
+ * appear — as input to a one-way digest that is never published. So two failures that both
710
+ * publish `TOOL_ERROR` still separate into different episodes when their real identity
711
+ * differs.
712
+ * @param {unknown} error - the event's `error` block.
713
+ * @param {unknown} message - the settled `ToolResultMessage` (the fallback identity).
714
+ * @returns {string} hash input; never published.
715
+ */
716
+ function failureIdentity(error, message) {
717
+ if (error !== null && typeof error === 'object') {
718
+ const code = typeof error.code === 'string' ? error.code : '';
719
+ const name = typeof error.name === 'string' ? error.name : '';
720
+ const reason = typeof error.reason === 'string' ? error.reason : '';
721
+ if (code !== '' || name !== '' || reason !== '') return `${code}\u0000${name}\u0000${reason}`;
722
+ }
723
+ // A native `isError` result whose structured `error` block is absent still has content;
724
+ // its digest is what distinguishes one such failure from another. Only the SHA is kept.
725
+ const content = Array.isArray(message?.content) ? message.content : [];
726
+ const parts = [];
727
+ for (const block of content) {
728
+ if (block === null || typeof block !== 'object') continue;
729
+ if (typeof block.text === 'string' && block.text !== '') parts.push(block.text);
730
+ }
731
+ return parts.length === 0 ? '' : `content\u0000${parts.join('\u0000')}`;
732
+ }
733
+
734
+ /** @param {string} value - text @returns {string} lowercase hex sha256. */
735
+ function sha256Hex(value) {
736
+ return createHash('sha256').update(value, 'utf8').digest('hex');
737
+ }
738
+
739
+ /** Why one observation wait ended. */
740
+ export const OBSERVE_REASONS = Object.freeze({
741
+ heartbeat: 'heartbeat',
742
+ attention: 'attention',
743
+ permission: 'permission',
744
+ ready: 'ready',
745
+ failed: 'failed',
746
+ cancelled: 'cancelled',
747
+ interrupted: 'interrupted',
748
+ });
749
+
750
+ /**
751
+ * Reasons no caller may ever receive from {@link TaskMonitor#observe}.
752
+ *
753
+ * `heartbeat` means "nothing to report, ask again"; handing it to a caller would
754
+ * be indistinguishable from a real report, so the loop treats it as an internal
755
+ * re-wait instead.
756
+ */
757
+ const INTERNAL_REASONS = Object.freeze(new Set([OBSERVE_REASONS.heartbeat]));
758
+
759
+ /**
760
+ * The task states that end an observation, mapped to the reason reported.
761
+ *
762
+ * Read from the engine's own lifecycle vocabulary rather than re-declared, so a
763
+ * new terminal state cannot leave the monitor silently reporting `heartbeat` for a
764
+ * finished run.
765
+ */
766
+ const TERMINAL_REASON = Object.freeze({
767
+ 'awaiting-host-review': OBSERVE_REASONS.ready,
768
+ failed: OBSERVE_REASONS.failed,
769
+ cancelled: OBSERVE_REASONS.cancelled,
770
+ });
771
+
772
+ /** The phase a running task reports while a permission request is outstanding. */
773
+ const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
774
+
775
+ /**
776
+ * One task's activity monitor.
777
+ *
778
+ * Owned by the engine and attached to the task record, so the counters live next
779
+ * to the run that produced them and die with it. It owns three things and nothing
780
+ * else:
781
+ *
782
+ * 1. the bounded activity state ({@link TaskActivity}), fed from the native
783
+ * `onEvent` callback the runner already invokes;
784
+ * 2. the *episode* bookkeeping that makes silent waiting silent — a
785
+ * self-check fires once per idle episode, and an `attention` report is not
786
+ * repeated until the interval has really elapsed and the caller has asked
787
+ * again;
788
+ * 3. the observation wait itself, built from injected `now`/`wait` seams so a test
789
+ * can simulate twenty minutes in microseconds.
790
+ *
791
+ * What it must never do, and does not: run an LLM, read a diff or a workspace
792
+ * file, mutate the task, restart/cancel/resubmit a run, or extend a deadline. The
793
+ * self-check is a read of facts the engine already holds.
794
+ */
795
+ export class TaskMonitor {
796
+ /**
797
+ * @param {object} task - the engine's own task record for this run.
798
+ * @param {object} [options] - seams and thresholds.
799
+ * @param {() => number} [options.now] - clock.
800
+ * @param {(ms: number) => Promise<void>} [options.wait] - bounded sleep.
801
+ * @param {number} [options.selfCheckSeconds] - idle span for the self-check.
802
+ * @param {number} [options.attentionSeconds] - idle span for `attention`.
803
+ * @param {number} [options.repeatFailureThreshold] - consecutive identical tool
804
+ * failures reported once, or 0 to disable that reminder.
805
+ * @param {number} [options.waitSliceMs] - internal polling slice.
806
+ * @param {(message: string, detail?: unknown) => void} [options.log] - diagnostic sink.
807
+ */
808
+ constructor(task, options = {}) {
809
+ this.task = task;
810
+ this.now = typeof options.now === 'function' ? options.now : Date.now;
811
+ this.wait = typeof options.wait === 'function' ? options.wait : sleep;
812
+ this.selfCheckMs = secondsToMs(options.selfCheckSeconds, 300);
813
+ this.attentionMs = secondsToMs(options.attentionSeconds, 600);
814
+ this.waitSliceMs = Number.isSafeInteger(options.waitSliceMs) && options.waitSliceMs > 0
815
+ ? options.waitSliceMs
816
+ : 1000;
817
+ this.log = typeof options.log === 'function' ? options.log : null;
818
+ this.activity = new TaskActivity({ now: this.now });
819
+ /**
820
+ * The repeated-failure detector. It is a SEPARATE clock from the two silence
821
+ * thresholds on purpose: it counts distinct failed operations, not quiet time.
822
+ */
823
+ this.failures = new RepeatedFailureTracker({ threshold: options.repeatFailureThreshold });
824
+ /**
825
+ * The one failure reminder waiting to be delivered, or null.
826
+ *
827
+ * A single slot, not a queue: the reminder is about the CURRENT episode, and an
828
+ * undelivered older one is superseded rather than replayed.
829
+ * @type {object | null}
830
+ */
831
+ this.pendingFailure = null;
832
+ /** Episode identity: bumped whenever genuine activity ends the idle episode. */
833
+ this.episode = 0;
834
+ /** The episode the self-check already ran for, or null. */
835
+ this.checkedEpisode = null;
836
+ /** The last self-check diagnostic, published on every summary. */
837
+ this.selfCheck = { episode: null, checkedAt: null, verdict: null, detail: null };
838
+ /**
839
+ * When the most recent attention report was DELIVERED, and for which idle
840
+ * episode.
841
+ *
842
+ * Exactly one pair, never a growing collection: the cooldown is a property of
843
+ * the current silence, and an idle origin only moves forward, so an older entry
844
+ * could never be reached again. `null` means "no attention has been delivered
845
+ * for this episode yet".
846
+ * @type {{ episode: number, origin: number, at: number } | null}
847
+ */
848
+ this.attentionDelivered = null;
849
+ /**
850
+ * Every observation currently waiting, so each one owns its own controller and
851
+ * one observer can never cancel another. Bounded by the number of callers; an
852
+ * entry is removed in its own `finally`.
853
+ * @type {Set<object>}
854
+ */
855
+ this.waiters = new Set();
856
+ this.disposed = false;
857
+ }
858
+
859
+ /**
860
+ * Record one native event.
861
+ *
862
+ * Called from the runner's `onEvent` hook, which means it runs inside the
863
+ * native dispatch path: nothing here may throw, await, or retain the event.
864
+ * @param {unknown} event - native event object.
865
+ * @param {number} [at] - observation time.
866
+ * @returns {boolean} whether this event was real activity.
867
+ */
868
+ onEvent(event, at = this.now()) {
869
+ if (this.disposed) return false;
870
+ let observation;
871
+ try {
872
+ observation = classifyActivityEvent(event);
873
+ } catch {
874
+ // A malformed event is not a reason to disturb the run that produced it.
875
+ return false;
876
+ }
877
+ // The failure detector reads the same events but keeps its own, separate state.
878
+ // It never feeds the silence clock, and a modelled output delta never clears it.
879
+ try {
880
+ this.observeFailure(event, at);
881
+ } catch {
882
+ // Same rule as above: bookkeeping must never disturb the run.
883
+ }
884
+ try {
885
+ const active = this.activity.record(observation, at);
886
+ // Real activity ends the current idle episode. The episode identity is what
887
+ // makes "once per episode" true for the self-check and the attention latch:
888
+ // without it, a run that goes quiet, wakes, and goes quiet again would be
889
+ // treated as the SAME silence and could never alert a second time.
890
+ if (active) this.episode += 1;
891
+ return active;
892
+ } catch {
893
+ return false;
894
+ }
895
+ }
896
+
897
+ /**
898
+ * Feed one event to the repeated-failure detector.
899
+ *
900
+ * Only the two native tool events matter; everything else is ignored. When the
901
+ * detector decides the threshold was reached it parks the diagnostic here, and the
902
+ * next observation delivers it — so the reminder rides the existing wait loop
903
+ * instead of starting a poller of its own.
904
+ * @param {object} event - native event.
905
+ * @param {number} at - observation time.
906
+ * @returns {void}
907
+ */
908
+ observeFailure(event, at) {
909
+ if (event === null || typeof event !== 'object') return;
910
+ if (event.type === 'tool/call') this.failures.onCall(event);
911
+ else if (event.type === 'tool/result') {
912
+ const diagnostic = this.failures.onResult(event, at);
913
+ if (diagnostic !== null) this.pendingFailure = diagnostic;
914
+ // A completed or differently-failing result ends the episode that a parked
915
+ // reminder belonged to, so that reminder is no longer news.
916
+ else if (!this.failures.isCurrent(this.pendingFailure)) this.pendingFailure = null;
917
+ }
918
+ }
919
+
920
+ /**
921
+ * Take the failure reminder that is waiting to be delivered, if any.
922
+ *
923
+ * Claimed once, like the attention latch: the diagnostic reaches exactly one
924
+ * observation, so a run is not woken on every subsequent identical failure. A reminder
925
+ * whose episode has ended or changed since it was parked is DROPPED rather than
926
+ * delivered: the run already recovered or moved on, so it is history, not news.
927
+ * @returns {object | null} the diagnostic, or null.
928
+ */
929
+ claimFailureReport() {
930
+ const report = this.pendingFailure;
931
+ this.pendingFailure = null;
932
+ if (!this.failures.isCurrent(report)) return null;
933
+ // Published form: the internal episode sequence does not leave this module.
934
+ const { episodeSequence, ...published } = report;
935
+ void episodeSequence;
936
+ return published;
937
+ }
938
+
939
+ /**
940
+ * The instant the current idle episode began.
941
+ *
942
+ * Before the executor has produced anything, the episode begins when its run
943
+ * began — a model that never streams a token is silent from the start, and
944
+ * measuring from "never" would hide it.
945
+ * @returns {number} epoch milliseconds.
946
+ */
947
+ idleOrigin() {
948
+ if (this.activity.lastActivityAt !== null) return this.activity.lastActivityAt;
949
+ if (Number.isFinite(this.task?.startedAt)) return this.task.startedAt;
950
+ if (Number.isFinite(this.task?.createdAt)) return this.task.createdAt;
951
+ return this.now();
952
+ }
953
+
954
+ /**
955
+ * Whether the current inactivity episode has reached the self-check threshold.
956
+ * @param {number} [at] - reference time.
957
+ * @returns {boolean} true when one read-only inspection is due.
958
+ */
959
+ selfCheckDue(at = this.now()) {
960
+ return at - this.idleOrigin() >= this.selfCheckMs;
961
+ }
962
+
963
+ /**
964
+ * Perform the 5-minute read-only inspection, at most once per idle episode.
965
+ *
966
+ * The inspection reads only what the engine itself already holds: whether the
967
+ * task is alive, whether its executor settled, the phase, whether a permission
968
+ * request is pending, and which tool call is outstanding. It performs no model
969
+ * call, reads no diff or workspace file, changes no task state, and does not
970
+ * touch the deadline.
971
+ * @param {number} [at] - reference time.
972
+ * @returns {object | null} the diagnostic, or null when none was due.
973
+ */
974
+ runSelfCheck(at = this.now()) {
975
+ if (this.disposed) return null;
976
+ if (!this.selfCheckDue(at)) return null;
977
+ const episode = this.episode;
978
+ if (this.checkedEpisode === episode) return null;
979
+ this.checkedEpisode = episode;
980
+ this.selfCheck = this.inspect(at, episode);
981
+ return this.selfCheck;
982
+ }
983
+
984
+ /**
985
+ * The last self-check diagnostic, or null when none ever ran.
986
+ * @returns {object | null} diagnostic.
987
+ */
988
+ lastSelfCheck() {
989
+ return this.selfCheck.checkedAt === null ? null : this.selfCheck;
990
+ }
991
+
992
+ /**
993
+ * Build the read-only diagnostic for the current episode.
994
+ * @param {number} at - reference time.
995
+ * @param {number} episode - episode identity.
996
+ * @returns {object} bounded diagnostic.
997
+ */
998
+ inspect(at, episode) {
999
+ const task = this.task ?? {};
1000
+ const pending = task.permission?.pending ?? null;
1001
+ const span = this.activity.toolSpan(at);
1002
+ const idleMs = Math.max(0, at - this.idleOrigin());
1003
+ const nativeStarted = task.native?.started === true;
1004
+ const nativeSettled = task.native?.settled === true;
1005
+ let verdict;
1006
+ if (task.state === 'pending' || task.state === 'running') {
1007
+ if (pending !== null) verdict = 'waiting-for-permission';
1008
+ else if (span !== null) verdict = 'tool-running';
1009
+ else if (nativeStarted && !nativeSettled) verdict = 'executor-alive-silent';
1010
+ else if (!nativeStarted) verdict = 'executor-not-started';
1011
+ else verdict = 'idle-between-steps';
1012
+ } else {
1013
+ verdict = 'settled';
1014
+ }
1015
+ return {
1016
+ episode,
1017
+ checkedAt: at,
1018
+ idleMs,
1019
+ verdict,
1020
+ detail: {
1021
+ state: typeof task.state === 'string' ? task.state : null,
1022
+ phase: typeof task.phase === 'string' ? task.phase : null,
1023
+ nativeStarted,
1024
+ nativeSettled,
1025
+ permissionPending: pending !== null,
1026
+ permissionRequestId: pending !== null && typeof pending.requestId === 'string' ? pending.requestId : null,
1027
+ phaseIsPermissionWait: task.phase === PHASE_AWAITING_PERMISSION,
1028
+ currentTool: span === null ? null : { name: span.name, callId: span.callId, elapsedMs: span.elapsedMs },
1029
+ lastActivityAt: this.activity.lastActivityAt,
1030
+ activityEvents: this.activity.activityEvents(),
1031
+ events: this.activity.totalEvents(),
1032
+ },
1033
+ };
1034
+ }
1035
+
1036
+ /**
1037
+ * Whether the current silence is old enough for an attention report, ignoring the
1038
+ * cooldown of an earlier delivery.
1039
+ * @param {number} [at] - reference time.
1040
+ * @returns {boolean} true when the idle span has reached the threshold.
1041
+ */
1042
+ attentionDue(at = this.now()) {
1043
+ return at - this.idleOrigin() >= this.attentionMs;
1044
+ }
1045
+
1046
+ /**
1047
+ * The instant the next attention report may be delivered, or `Infinity` while the
1048
+ * thresholds have not been reached at all.
1049
+ *
1050
+ * The rule is a cooldown, not a one-shot latch: the FIRST report is due at
1051
+ * `idleOrigin + attentionSeconds`, and every later report for the same silence
1052
+ * needs a FURTHER `attentionSeconds` since the previous delivery. Genuine
1053
+ * activity resets both the origin and the delivery record, so a run that goes
1054
+ * quiet again can alert again.
1055
+ * @returns {number} the next deliverable instant.
1056
+ */
1057
+ nextAttentionAt() {
1058
+ const origin = this.idleOrigin();
1059
+ const delivered = this.attentionDelivered;
1060
+ let next = origin + this.attentionMs;
1061
+ if (delivered !== null && delivered.episode === this.episode && delivered.origin === origin) {
1062
+ next = Math.max(next, delivered.at + this.attentionMs);
1063
+ }
1064
+ return next;
1065
+ }
1066
+
1067
+ /**
1068
+ * Whether an attention report may be delivered at `at`, and atomically claims it
1069
+ * if so.
1070
+ *
1071
+ * The claim happens in the same synchronous step as the test, so two observers
1072
+ * reaching the threshold together cannot both return `attention`: the first
1073
+ * claims, the second observes the fresh delivery record and keeps waiting.
1074
+ * @param {number} [at] - delivery instant.
1075
+ * @returns {boolean} true for the observer that won the claim.
1076
+ */
1077
+ claimAttention(at = this.now()) {
1078
+ if (at < this.nextAttentionAt()) return false;
1079
+ this.attentionDelivered = { episode: this.episode, origin: this.idleOrigin(), at };
1080
+ return true;
1081
+ }
1082
+
1083
+ /**
1084
+ * Publishable activity summary for a task view.
1085
+ *
1086
+ * `toolActive` is passed by the caller because only the engine can decide what a
1087
+ * long tool span means: a pending permission request already reports its own
1088
+ * reason, and a settled run is not "waiting on a tool" at all.
1089
+ * @param {object} [options] - `at` reference time, `toolActive`.
1090
+ * @returns {object} bounded summary.
1091
+ */
1092
+ snapshot({ at = this.now(), toolActive = false } = {}) {
1093
+ const summary = this.activity.summary({ at, toolActive });
1094
+ return {
1095
+ ...summary,
1096
+ // Stated so a reader never has to derive the thresholds from a settings
1097
+ // document that may have changed since this task froze its own.
1098
+ selfCheckSeconds: Math.round(this.selfCheckMs / 1000),
1099
+ attentionSeconds: Math.round(this.attentionMs / 1000),
1100
+ idleForMs: this.activity.idleForMs(at),
1101
+ selfCheck: {
1102
+ episode: this.selfCheck.episode,
1103
+ checkedAt: this.selfCheck.checkedAt,
1104
+ verdict: this.selfCheck.verdict,
1105
+ },
1106
+ // The repeated-failure reminder, as bounded evidence: one small object per
1107
+ // reported episode, never arguments, output or error prose.
1108
+ repeatFailure: {
1109
+ threshold: this.failures.threshold,
1110
+ // Projected field by field, so the internal episode sequence cannot reach a view,
1111
+ // a stored record or a client.
1112
+ reported: this.failures.reported.map((entry) => ({
1113
+ kind: entry.kind,
1114
+ toolName: entry.toolName,
1115
+ failureCode: entry.failureCode,
1116
+ operationDigest: entry.operationDigest,
1117
+ consecutive: entry.consecutive,
1118
+ threshold: entry.threshold,
1119
+ firstSeenAt: entry.firstSeenAt,
1120
+ lastSeenAt: entry.lastSeenAt,
1121
+ })),
1122
+ },
1123
+ };
1124
+ }
1125
+
1126
+ /**
1127
+ * Release every waiter this monitor owns. Called only by {@link dispose}.
1128
+ *
1129
+ * Each waiter aborts its own controller; one observation ending never touches
1130
+ * another.
1131
+ * @returns {void}
1132
+ */
1133
+ releaseWaiters() {
1134
+ for (const waiter of [...this.waiters]) {
1135
+ try {
1136
+ waiter.controller.abort();
1137
+ } catch {
1138
+ // Abort is idempotent.
1139
+ }
1140
+ }
1141
+ this.waiters.clear();
1142
+ }
1143
+
1144
+ /**
1145
+ * The bounded observation wait documented for adapters (HTTP/MCP).
1146
+ *
1147
+ * What it reports, in precedence order, re-checked on every slice:
1148
+ *
1149
+ * 1. `interrupted` — this observer's own signal aborted, or the monitor was
1150
+ * disposed. The WORKER is untouched;
1151
+ * 2. `ready`/`failed`/`cancelled` — the task reached a terminal state. This wins
1152
+ * over a disposal wake, so an observation released by engine teardown still
1153
+ * reports the outcome the run actually reached;
1154
+ * 3. `permission` — a per-call decision is outstanding. Waiting for approval is
1155
+ * not a stall;
1156
+ * 4. `attention` — the silence reached `attentionSeconds` (once, then on the
1157
+ * cooldown) AND the claim was won. Genuine progress never produces this: it
1158
+ * resets the silence instead, which is the whole point of the feature;
1159
+ * 5. `heartbeat` — the bounded wait expired with nothing to report.
1160
+ *
1161
+ * The self-check runs inside the loop, so a monitor with no observer costs
1162
+ * nothing. Every caller gets its own controller and timer, so an observation
1163
+ * never cancels another.
1164
+ * @param {object} [options] - `waitMs`, `signal`.
1165
+ * @returns {Promise<{ reason: string, activitySinceWait: boolean, waitedMs: number, selfCheck: object | null }>} outcome.
1166
+ */
1167
+ async observe(options = {}) {
1168
+ const signal = options.signal ?? null;
1169
+ // A terminal outcome is a READ of the task record, so it is answered even by a
1170
+ // disposed monitor: engine teardown stops the observation loops, but it must
1171
+ // never turn a finished run into "interrupted".
1172
+ const settledNow = terminalReason(this.task);
1173
+ if (settledNow !== null) return this.outcome(settledNow, false, 0, this.lastSelfCheck());
1174
+ if (this.disposed) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
1175
+ if (signal !== null && signal.aborted === true) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
1176
+
1177
+ const waitMs = boundedWait(options.waitMs);
1178
+ const startedAt = this.now();
1179
+ const startingSequence = this.activity.sequence;
1180
+ const waiter = { controller: new AbortController() };
1181
+ this.waiters.add(waiter);
1182
+ const onAbort = () => {
1183
+ try {
1184
+ waiter.controller.abort();
1185
+ } catch {
1186
+ // Unreachable; abort is idempotent.
1187
+ }
1188
+ };
1189
+ if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
1190
+
1191
+ let selfCheck = null;
1192
+ try {
1193
+ for (;;) {
1194
+ const at = this.now();
1195
+ const activitySinceWait = this.activity.sequence !== startingSequence;
1196
+ // A pure read of local facts, run BEFORE any reason is returned so every
1197
+ // report carries the diagnostic that explains the silence.
1198
+ const checked = this.runSelfCheck(at);
1199
+ if (checked !== null) selfCheck = checked;
1200
+
1201
+ // (2) The run's own outcome outranks a wake-up: a task that ended must be
1202
+ // reported as ended even if the monitor was disposed in the same instant.
1203
+ const terminal = terminalReason(this.task);
1204
+ if (terminal !== null) return this.outcome(terminal, activitySinceWait, at - startedAt, selfCheck);
1205
+
1206
+ // (1) Only one's OWN abort (or disposal) interrupts.
1207
+ if (this.disposed || waiter.controller.aborted === true || (signal !== null && signal.aborted === true)) {
1208
+ return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, at - startedAt, selfCheck);
1209
+ }
1210
+
1211
+ if (this.task?.permission?.pending !== null && this.task?.permission?.pending !== undefined) {
1212
+ return this.outcome(OBSERVE_REASONS.permission, activitySinceWait, at - startedAt, selfCheck);
1213
+ }
1214
+ // (3b) Repeated failures. Same reason as the silence report — it needs the
1215
+ // commander — but it carries its own typed diagnostic and is NOT gated on
1216
+ // silence: a busy run that keeps failing the same operation must still reach
1217
+ // the host. Permission and a terminal state above outrank it.
1218
+ const failure = this.claimFailureReport();
1219
+ if (failure !== null) {
1220
+ return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck, failure);
1221
+ }
1222
+ // (4) `claimAttention` is false while genuine progress has reset the clock,
1223
+ // because the origin moved into the future relative to `nextAttentionAt()`.
1224
+ if (this.claimAttention(at)) {
1225
+ return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck);
1226
+ }
1227
+ const elapsed = at - startedAt;
1228
+ if (elapsed >= waitMs) {
1229
+ return this.outcome(OBSERVE_REASONS.heartbeat, activitySinceWait, elapsed, selfCheck);
1230
+ }
1231
+ const untilAttention = this.nextAttentionAt() - at;
1232
+ const slice = Math.max(1, Math.min(this.waitSliceMs, waitMs - elapsed, untilAttention));
1233
+ try {
1234
+ await this.wait(slice, { signal: waiter.controller.signal });
1235
+ } catch {
1236
+ // A wait seam that rejects ends THIS observation only. The worker and
1237
+ // every other observer are untouched.
1238
+ return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, this.now() - startedAt, selfCheck);
1239
+ }
1240
+ }
1241
+ } finally {
1242
+ this.waiters.delete(waiter);
1243
+ if (signal !== null) signal.removeEventListener?.('abort', onAbort);
1244
+ }
1245
+ }
1246
+
1247
+ /**
1248
+ * Build one observation outcome.
1249
+ * @param {string} reason - reported reason.
1250
+ * @param {boolean} activitySinceWait - whether progress arrived during the wait.
1251
+ * @param {number} waitedMs - observed duration.
1252
+ * @param {object | null} selfCheck - the last self-check diagnostic.
1253
+ * @param {object | null} [failure] - the repeated-failure diagnostic, when that is
1254
+ * what ended the wait.
1255
+ * @returns {object} outcome.
1256
+ */
1257
+ outcome(reason, activitySinceWait, waitedMs, selfCheck, failure = null) {
1258
+ return {
1259
+ reason,
1260
+ failure,
1261
+ activitySinceWait: activitySinceWait === true,
1262
+ waitedMs: Math.max(0, Math.trunc(waitedMs)),
1263
+ selfCheck,
1264
+ };
1265
+ }
1266
+
1267
+ /**
1268
+ * Drop every listener/timer this monitor owns. Idempotent.
1269
+ *
1270
+ * Marking the activity final first freezes the elapsed values at the end
1271
+ * recorded on the task, so nothing published afterwards grows.
1272
+ * @param {number} [endedAt] - the run's recorded end, when known.
1273
+ * @returns {void}
1274
+ */
1275
+ dispose(endedAt = undefined) {
1276
+ if (typeof endedAt === 'number') this.activity.finalize(endedAt);
1277
+ if (this.disposed) return;
1278
+ this.disposed = true;
1279
+ // Open calls can never produce a result for a run that has ended; the reported
1280
+ // trail stays as bounded evidence. The undelivered reminder is dropped with it.
1281
+ this.failures.dispose();
1282
+ this.pendingFailure = null;
1283
+ this.releaseWaiters();
1284
+ }
1285
+ }
1286
+
1287
+ /**
1288
+ * Whether one internal reason may be handed to a caller.
1289
+ * @param {string} reason - reason value.
1290
+ * @returns {boolean} true when a caller should receive it.
1291
+ */
1292
+ export function isPublicReason(reason) {
1293
+ return typeof reason === 'string' && Object.values(OBSERVE_REASONS).includes(reason) && !INTERNAL_REASONS.has(reason);
1294
+ }
1295
+
1296
+ /**
1297
+ * The reason a task's current state implies, or null while it is still running.
1298
+ * @param {object} task - engine task record.
1299
+ * @returns {string | null} reason.
1300
+ */
1301
+ export function terminalReason(task) {
1302
+ const state = task?.state;
1303
+ if (typeof state !== 'string') return null;
1304
+ return TERMINAL_REASON[state] ?? null;
1305
+ }
1306
+
1307
+ /**
1308
+ * Clamp a caller-requested wait to the documented bound.
1309
+ * @param {unknown} waitMs - requested wait.
1310
+ * @returns {number} a whole number of milliseconds within bounds.
1311
+ */
1312
+ function boundedWait(waitMs) {
1313
+ if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs <= 0) return 25_000;
1314
+ return Math.min(25_000, Math.max(1, Math.trunc(waitMs)));
1315
+ }
1316
+
1317
+ /**
1318
+ * Convert a validated seconds threshold to milliseconds, with the documented
1319
+ * default when the value is absent.
1320
+ * @param {unknown} value - seconds.
1321
+ * @param {number} fallbackSeconds - default.
1322
+ * @returns {number} milliseconds.
1323
+ */
1324
+ function secondsToMs(value, fallbackSeconds) {
1325
+ const seconds = Number.isSafeInteger(value) && value > 0 ? value : fallbackSeconds;
1326
+ return seconds * 1000;
1327
+ }
1328
+
1329
+ /**
1330
+ * Default wait seam: a real, unref'd timeout that honours an abort signal.
1331
+ *
1332
+ * `unref()` matters: an observation waiting on a timer must not by itself keep the
1333
+ * process alive, and the timer is cleared on abort so an abandoned observation
1334
+ * leaves nothing behind.
1335
+ * @param {number} ms - slice length.
1336
+ * @param {object} [options] - `signal`.
1337
+ * @returns {Promise<void>} resolves after the slice.
1338
+ */
1339
+ export function sleep(ms, options = {}) {
1340
+ const signal = options?.signal ?? null;
1341
+ return new Promise((resolvePromise, rejectPromise) => {
1342
+ if (signal !== null && signal.aborted === true) {
1343
+ rejectPromise(abortError());
1344
+ return;
1345
+ }
1346
+ const timer = setTimeout(() => {
1347
+ cleanup();
1348
+ resolvePromise();
1349
+ }, ms);
1350
+ timer.unref?.();
1351
+ const onAbort = () => {
1352
+ cleanup();
1353
+ rejectPromise(abortError());
1354
+ };
1355
+ const cleanup = () => {
1356
+ clearTimeout(timer);
1357
+ if (signal !== null) signal.removeEventListener?.('abort', onAbort);
1358
+ };
1359
+ if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
1360
+ });
1361
+ }
1362
+
1363
+ /** @returns {Error} a DOM-shaped abort error. */
1364
+ function abortError() {
1365
+ const error = new Error('the wait was aborted');
1366
+ error.name = 'AbortError';
1367
+ return error;
1368
+ }
1369
+