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.
- package/CHANGELOG.md +19 -0
- package/README.md +46 -44
- package/bin/dsh-delegate-codex-agent.js +1 -1
- package/bin/dsh-delegate-mcp.js +4 -0
- package/codex/{dsh-delegate.toml → dsh-taskbridge.toml} +127 -33
- package/docs/INTRODUCTION.md +4 -2
- package/docs/INTRODUCTION.zh.md +7 -3
- package/docs/codex-integration.md +76 -30
- package/docs/conversation-placement.md +11 -0
- package/docs/plugin-market.md +1 -1
- package/docs/releases/1.4.0-token-benchmark.zh.md +40 -0
- package/docs/releases/1.4.0.zh.md +54 -0
- package/docs/runtime-compatibility.md +16 -11
- package/docs/silent-wait.md +73 -10
- package/docs/taskbridge-upgrade.md +6 -6
- package/lib/client.js +155 -53
- package/package.json +143 -137
- package/src/client/api.js +205 -46
- package/src/client/index.jsx +88 -33
- package/src/codex/installer.js +77 -13
- package/src/config/defaults.js +12 -0
- package/src/config/settings.js +12 -10
- package/src/config/validate.js +26 -11
- package/src/http/execution-plane.js +60 -4
- package/src/http/respond.js +179 -175
- package/src/index.d.ts +102 -2
- package/src/index.js +1 -1
- package/src/jobs/activity.js +1369 -1008
- package/src/jobs/diagnostics.js +15 -0
- package/src/jobs/engine.js +300 -10
- package/src/jobs/history.js +28 -0
- package/src/jobs/title.js +17 -0
- package/src/mcp/server.js +141 -14
- package/src/mcp/wait.js +49 -10
- package/src/runtime/agent-runner.js +2 -0
- package/src/runtime/session-placement.js +20 -2
package/src/jobs/activity.js
CHANGED
|
@@ -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
|
-
// * **
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
// delta
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
// The
|
|
81
|
-
|
|
82
|
-
'
|
|
83
|
-
//
|
|
84
|
-
|
|
85
|
-
//
|
|
86
|
-
'
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
//
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
//
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
this.
|
|
252
|
-
|
|
253
|
-
this.
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
this.
|
|
261
|
-
|
|
262
|
-
this.
|
|
263
|
-
/**
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
this.
|
|
271
|
-
/**
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
this.
|
|
301
|
-
if (
|
|
302
|
-
|
|
303
|
-
if (
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
*
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
*
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/**
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
498
|
-
*
|
|
499
|
-
*
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
*
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
*
|
|
534
|
-
* @param {
|
|
535
|
-
* @
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
this.
|
|
546
|
-
this.
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
638
|
-
*
|
|
639
|
-
*
|
|
640
|
-
*
|
|
641
|
-
*
|
|
642
|
-
* @
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
if (
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
*
|
|
800
|
-
*
|
|
801
|
-
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
804
|
-
*
|
|
805
|
-
*
|
|
806
|
-
*
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
this.
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
*
|
|
899
|
-
*
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
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
|
+
|