@xiangyixie/dsh-superagent 0.10.0 → 0.11.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 +210 -87
- package/README.md +276 -38
- package/bin/archive.js +185 -0
- package/bin/doctor.js +84 -0
- package/lib/cost.js +267 -0
- package/lib/doctor.js +876 -0
- package/lib/index.js +1547 -1104
- package/lib/ledger.js +270 -0
- package/lib/memory.js +736 -503
- package/lib/orchestrator.js +1377 -183
- package/lib/report.js +1068 -733
- package/lib/store.js +873 -402
- package/lib/templates.js +690 -0
- package/lib/watch.js +810 -458
- package/lib/workspace.js +433 -0
- package/package.json +13 -3
package/lib/index.js
CHANGED
|
@@ -1,1104 +1,1547 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
|
|
3
|
-
*
|
|
4
|
-
* One goal enters; a planner decomposes it into independent subtasks
|
|
5
|
-
*
|
|
6
|
-
* Runs survive a host restart, can be
|
|
7
|
-
* read back from the child sessions'
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import {
|
|
20
|
-
import
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
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
|
-
|
|
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
|
-
if (
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
merged
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
merged.
|
|
194
|
-
merged.
|
|
195
|
-
merged.
|
|
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
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
`
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
if (
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
+
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
if (
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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
|
-
if (run.
|
|
331
|
-
lines.push(
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
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
|
-
const
|
|
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
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
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
|
-
const
|
|
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
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
},
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* One goal enters; a planner decomposes it into subtasks; independent subtasks
|
|
5
|
+
* run in parallel child agents while a declared dependency holds the rest back;
|
|
6
|
+
* an aggregator merges their reports. Runs survive a host restart, can be
|
|
7
|
+
* cancelled, and have their token usage read back from the child sessions'
|
|
8
|
+
* durable logs.
|
|
9
|
+
*
|
|
10
|
+
* Registered tools: superagent_start, superagent_status, superagent_list,
|
|
11
|
+
* superagent_cancel, superagent_resume, superagent_followup,
|
|
12
|
+
* superagent_answer, superagent_memory, superagent_template.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-superagent
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from 'node:crypto'
|
|
17
|
+
import os from 'node:os'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import { fileURLToPath } from 'node:url'
|
|
20
|
+
import pkg from '../package.json' with { type: 'json' }
|
|
21
|
+
import { createOrchestrator, followupEffect } from './orchestrator.js'
|
|
22
|
+
import { createControlPlane } from './control.js'
|
|
23
|
+
import { formatMoney } from './cost.js'
|
|
24
|
+
import { classifyError, describeError, summarizeError } from './errors.js'
|
|
25
|
+
import { createLedger } from './ledger.js'
|
|
26
|
+
import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
|
|
27
|
+
import { createNotifyPolicy, createOutbox } from './notify.js'
|
|
28
|
+
import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
|
|
29
|
+
import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
|
|
30
|
+
import { createUsageReader } from './usage.js'
|
|
31
|
+
import { describeWorkspace } from './workspace.js'
|
|
32
|
+
|
|
33
|
+
export const name = 'dsh-superagent'
|
|
34
|
+
// The host menu and sessions are required. `subagents` is read through
|
|
35
|
+
// `ctx.get('subagents')`, so a profile without it still mounts the eight tools;
|
|
36
|
+
// they then report what is missing instead of the plugin silently vanishing.
|
|
37
|
+
export const inject = ['tools', 'agents']
|
|
38
|
+
|
|
39
|
+
const DEFAULTS = {
|
|
40
|
+
/** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
|
|
41
|
+
stateDir: null,
|
|
42
|
+
/** Child backend registered on `ctx.subagents`. */
|
|
43
|
+
provider: 'spawn',
|
|
44
|
+
/** Optional provider override for every child agent; unset inherits the parent's model route. */
|
|
45
|
+
childProvider: null,
|
|
46
|
+
/** Optional model override for every child agent; unset inherits the parent's model. */
|
|
47
|
+
childModel: null,
|
|
48
|
+
/**
|
|
49
|
+
* Optional agent preset for child agents. A preset owns the child's tool
|
|
50
|
+
* composition, which is the only way this host version can restrict it.
|
|
51
|
+
*/
|
|
52
|
+
childPreset: null,
|
|
53
|
+
/**
|
|
54
|
+
* Delegation depth granted to child agents. 1 means a worker may not create
|
|
55
|
+
* children of its own; `provider-managed` leaves the cap to the backend.
|
|
56
|
+
*/
|
|
57
|
+
maxSubagentDepth: 1,
|
|
58
|
+
/** Upper bound on planned subtasks per run. */
|
|
59
|
+
maxSubtasks: 8,
|
|
60
|
+
/** Upper bound on subtasks executing at once. */
|
|
61
|
+
maxParallel: 3,
|
|
62
|
+
/** Runs allowed to be active at the same time; a start over this waits instead of failing. */
|
|
63
|
+
maxActiveRuns: 2,
|
|
64
|
+
/** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
|
|
65
|
+
maxQueuedRuns: 5,
|
|
66
|
+
/** How long a queued run waits before it fails, in minutes. */
|
|
67
|
+
queueTimeoutMinutes: 30,
|
|
68
|
+
/**
|
|
69
|
+
* Queue starts that did not ask for it with `queue: true`. Off by default: a
|
|
70
|
+
* caller opts in, so a script that relied on the quota error keeps seeing it.
|
|
71
|
+
*/
|
|
72
|
+
queueOnFull: false,
|
|
73
|
+
/** Attempts per subtask before it is marked failed. */
|
|
74
|
+
attempts: 2,
|
|
75
|
+
/** Wall-clock budget for a whole run, in minutes. */
|
|
76
|
+
deadlineMinutes: 120,
|
|
77
|
+
/** Hard cap on child model calls per run; 0 disables the cap. */
|
|
78
|
+
maxModelCallsPerRun: 80,
|
|
79
|
+
/** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
|
|
80
|
+
maxTokensPerRun: 2_000_000,
|
|
81
|
+
/**
|
|
82
|
+
* List prices per 1M tokens, keyed by model id as it appears in usage logs.
|
|
83
|
+
* Only models listed here are priced; everything else is reported as unpriced
|
|
84
|
+
* rather than guessed. Nothing is shipped: a stale price is worse than none.
|
|
85
|
+
*/
|
|
86
|
+
pricing: {},
|
|
87
|
+
/** Bytes kept from one subtask report. */
|
|
88
|
+
resultCapBytes: 32 * 1024,
|
|
89
|
+
/** Write one message back to the owning session when a run finishes unattended. */
|
|
90
|
+
notifyOnComplete: true,
|
|
91
|
+
/**
|
|
92
|
+
* Proactive messages allowed per rolling hour. Runs that finish after the cap
|
|
93
|
+
* are folded into one summary instead of waking the session again.
|
|
94
|
+
*/
|
|
95
|
+
maxNotificationsPerHour: 3,
|
|
96
|
+
/**
|
|
97
|
+
* Extra rounds that retry failed subtasks before the failure is reported, so
|
|
98
|
+
* a transient error is healed automatically instead of asking the user.
|
|
99
|
+
*/
|
|
100
|
+
autoResumeRounds: 1,
|
|
101
|
+
/**
|
|
102
|
+
* Delivery attempts for one wake-up. A followup can fail while the session
|
|
103
|
+
* loop is busy; retrying it is the difference between a lost result and a
|
|
104
|
+
* late one. 0 means one attempt.
|
|
105
|
+
*/
|
|
106
|
+
notifyRetries: 2,
|
|
107
|
+
/** First delay between delivery attempts; it doubles per attempt. */
|
|
108
|
+
notifyRetryDelayMs: 2000,
|
|
109
|
+
/**
|
|
110
|
+
* Child model used on a self-heal round when the failure looks transient
|
|
111
|
+
* (quota, rate limit, timeout). `null` keeps the configured route.
|
|
112
|
+
*/
|
|
113
|
+
childModelFallback: null,
|
|
114
|
+
/**
|
|
115
|
+
* Cross-run notebook. Notes live under `stateDir` and never enter the package
|
|
116
|
+
* or a default commit; see the privacy section of the README.
|
|
117
|
+
*/
|
|
118
|
+
memory: true,
|
|
119
|
+
/** Notebook scope; each scope is one file, so unrelated projects stay apart. */
|
|
120
|
+
memoryScope: 'default',
|
|
121
|
+
/** Notes kept before the notebook is compacted. */
|
|
122
|
+
memoryMaxEntries: 60,
|
|
123
|
+
/** Notes older than this are ignored, then compacted away. */
|
|
124
|
+
memoryMaxAgeDays: 30,
|
|
125
|
+
/** Notes injected into the planner and aggregator prompts. */
|
|
126
|
+
memoryDigestEntries: 12,
|
|
127
|
+
/** Character budget for the note part of that prompt context. */
|
|
128
|
+
memoryDigestChars: 1600,
|
|
129
|
+
/** Delete terminal runs older than this many days on mount; 0 keeps everything. */
|
|
130
|
+
keepRuns: 0,
|
|
131
|
+
/**
|
|
132
|
+
* Loopback HTTP port for the embedding surface. `null` (default) keeps the
|
|
133
|
+
* socket closed; `0` asks the OS for a free port. The bound address and its
|
|
134
|
+
* bearer token are written to `<stateDir>/control.json`.
|
|
135
|
+
*/
|
|
136
|
+
controlPort: null,
|
|
137
|
+
/**
|
|
138
|
+
* Run every worker in its own git worktree of `workspaceRoot`, so parallel
|
|
139
|
+
* workers cannot overwrite each other's files. Off by default: it needs a
|
|
140
|
+
* git repository and it moves files, which is not something a plugin should
|
|
141
|
+
* start doing unasked.
|
|
142
|
+
*/
|
|
143
|
+
workspaceIsolation: false,
|
|
144
|
+
/** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
|
|
145
|
+
workspaceRoot: null,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const REPORT_PREVIEW_CHARS = 8000
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Coerce one numeric setting into its documented range. A value like "abc"
|
|
152
|
+
* would otherwise become NaN and silently remove a limit (NaN comparisons are
|
|
153
|
+
* always false), which is how a quota disappears without any error.
|
|
154
|
+
*/
|
|
155
|
+
function bounded(value, fallback, min, max) {
|
|
156
|
+
const number = Number(value)
|
|
157
|
+
if (!Number.isFinite(number)) return fallback
|
|
158
|
+
return Math.min(max, Math.max(min, Math.trunc(number)))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* A port is a whole number in 0–65535, or nothing. A malformed value must not
|
|
163
|
+
* silently open a socket somewhere unexpected, so anything else stays off.
|
|
164
|
+
*/
|
|
165
|
+
function controlPortOf(value) {
|
|
166
|
+
if (value === null || value === undefined || value === false) return null
|
|
167
|
+
// Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
|
|
168
|
+
// real number or a plain digit string may enable the surface.
|
|
169
|
+
if (typeof value === 'number') {
|
|
170
|
+
return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
|
|
171
|
+
}
|
|
172
|
+
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
|
173
|
+
const number = Number(value.trim())
|
|
174
|
+
return number <= 65535 ? number : null
|
|
175
|
+
}
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Read a YAML/JSON boolean without letting the string "false" mean true. */
|
|
180
|
+
function flag(value, fallback) {
|
|
181
|
+
if (value === undefined) return fallback
|
|
182
|
+
if (typeof value === 'string') return !/^(false|0|off|no)$/i.test(value.trim())
|
|
183
|
+
return Boolean(value)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function resolveConfig(config) {
|
|
187
|
+
const merged = { ...DEFAULTS }
|
|
188
|
+
if (config && typeof config === 'object') {
|
|
189
|
+
for (const [key, value] of Object.entries(config)) {
|
|
190
|
+
if (value !== undefined) merged[key] = value
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
|
|
194
|
+
merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
|
|
195
|
+
merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
|
|
196
|
+
merged.maxQueuedRuns = bounded(merged.maxQueuedRuns, DEFAULTS.maxQueuedRuns, 0, 32)
|
|
197
|
+
merged.queueTimeoutMinutes = bounded(merged.queueTimeoutMinutes, DEFAULTS.queueTimeoutMinutes, 1, 720)
|
|
198
|
+
merged.queueOnFull = flag(merged.queueOnFull, DEFAULTS.queueOnFull)
|
|
199
|
+
merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
|
|
200
|
+
merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
|
|
201
|
+
merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
|
|
202
|
+
merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
|
|
203
|
+
merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
|
|
204
|
+
merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
|
|
205
|
+
merged.controlPort = controlPortOf(merged.controlPort)
|
|
206
|
+
merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
|
|
207
|
+
? 'provider-managed'
|
|
208
|
+
: bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
|
|
209
|
+
// Per-model prices merge, so a user can add one route without restating the
|
|
210
|
+
// built-in table.
|
|
211
|
+
merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
|
|
212
|
+
merged.memory = flag(merged.memory, DEFAULTS.memory)
|
|
213
|
+
merged.memoryScope = normalizeScope(merged.memoryScope)
|
|
214
|
+
merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
|
|
215
|
+
merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
|
|
216
|
+
merged.memoryDigestEntries = bounded(merged.memoryDigestEntries, DEFAULTS.memoryDigestEntries, 1, 50)
|
|
217
|
+
merged.memoryDigestChars = bounded(merged.memoryDigestChars, DEFAULTS.memoryDigestChars, 200, 8000)
|
|
218
|
+
merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
|
|
219
|
+
merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
|
|
220
|
+
merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
|
|
221
|
+
merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
|
|
222
|
+
merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
|
|
223
|
+
? merged.childModelFallback.trim()
|
|
224
|
+
: null
|
|
225
|
+
merged.workspaceIsolation = flag(merged.workspaceIsolation, DEFAULTS.workspaceIsolation)
|
|
226
|
+
// A blank path would resolve to the cwd, which is how isolation would silently
|
|
227
|
+
// point at the wrong repository; blank therefore means "use the default".
|
|
228
|
+
merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
|
|
229
|
+
? merged.workspaceRoot.trim()
|
|
230
|
+
: null
|
|
231
|
+
return merged
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function preview(text, limit = REPORT_PREVIEW_CHARS) {
|
|
235
|
+
if (typeof text !== 'string') return ''
|
|
236
|
+
if (text.length <= limit) return text
|
|
237
|
+
return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function durationText(ms) {
|
|
241
|
+
const seconds = Math.max(0, ms / 1000)
|
|
242
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`
|
|
243
|
+
const minutes = Math.floor(seconds / 60)
|
|
244
|
+
return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function elapsed(run) {
|
|
248
|
+
const start = Date.parse(run.startedAt)
|
|
249
|
+
const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
|
|
250
|
+
if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
|
|
251
|
+
const wall = Math.max(0, end - start)
|
|
252
|
+
const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
|
|
253
|
+
// A resumed run can span hours of downtime. Reporting one number would make
|
|
254
|
+
// it look like the model worked all that time.
|
|
255
|
+
if (run.resumedAt && wall - active > 5000) {
|
|
256
|
+
return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
|
|
257
|
+
}
|
|
258
|
+
return durationText(wall)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function usageLine(usage, status) {
|
|
262
|
+
if (!usage || !usage.modelCalls) {
|
|
263
|
+
if (ACTIVE_STATUSES.has(status)) {
|
|
264
|
+
return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
|
|
265
|
+
}
|
|
266
|
+
return 'usage: not recorded — no child session log was readable for this run '
|
|
267
|
+
+ '(usually a run created before usage tracking, or a sessions directory that moved); '
|
|
268
|
+
+ 'token and cost figures are unavailable'
|
|
269
|
+
}
|
|
270
|
+
const models = Object.entries(usage.models ?? {})
|
|
271
|
+
.map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
|
|
272
|
+
.join('; ')
|
|
273
|
+
const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
|
|
274
|
+
return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
|
|
275
|
+
+ (models ? ` (${models})` : '')
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Cost line for one run. The number is an estimate from the configured list
|
|
280
|
+
* prices; models without a price are named instead of guessed so a user can
|
|
281
|
+
* always tell how much of the spend the figure covers.
|
|
282
|
+
*/
|
|
283
|
+
function costLine(run) {
|
|
284
|
+
if (!run.usage || !run.usage.modelCalls) return null
|
|
285
|
+
const models = Object.keys(run.usage.models ?? {})
|
|
286
|
+
const cost = run.cost
|
|
287
|
+
// An all-unpriced run has no priced line at all. Printing 0.0000 there would
|
|
288
|
+
// claim the run was free, which is the one thing an estimate must not do.
|
|
289
|
+
const priced = Boolean(cost) && Object.keys(cost.byModel ?? {}).length > 0
|
|
290
|
+
if (!priced) {
|
|
291
|
+
const named = cost?.unpriced?.length ? cost.unpriced.join(', ') : (models.join(', ') || 'this model')
|
|
292
|
+
return `cost: not computed — no price configured for ${named}; `
|
|
293
|
+
+ 'add a pricing entry in cordis.patch.yml to get an estimate'
|
|
294
|
+
}
|
|
295
|
+
const money = formatMoney(cost)
|
|
296
|
+
if (cost.complete) return `cost: ${money} (estimate; all models priced)`
|
|
297
|
+
return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Spend for one subtask: measured when priced, explicit when not. */
|
|
301
|
+
function subtaskCostText(subtask) {
|
|
302
|
+
if (!subtask?.usage || !subtask.usage.modelCalls) return ''
|
|
303
|
+
const cost = subtask.cost
|
|
304
|
+
if (!cost || Object.keys(cost.byModel ?? {}).length === 0) {
|
|
305
|
+
const named = cost?.unpriced?.length ? ` (${cost.unpriced.join(', ')})` : ''
|
|
306
|
+
return `, cost unpriced${named}`
|
|
307
|
+
}
|
|
308
|
+
return `, ${formatMoney(cost)}${cost.complete ? '' : '+'}`
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Render one run as text for a tool result. */
|
|
312
|
+
function formatRun(run, { includeReport = true } = {}) {
|
|
313
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
314
|
+
const lines = [
|
|
315
|
+
`run ${run.id} — ${run.status}`,
|
|
316
|
+
`goal: ${run.goal}`,
|
|
317
|
+
`plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
|
|
318
|
+
+ `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
|
|
319
|
+
`elapsed: ${elapsed(run)}`,
|
|
320
|
+
usageLine(run.usage, run.status),
|
|
321
|
+
]
|
|
322
|
+
if (run.queue?.waiting) {
|
|
323
|
+
lines.push(
|
|
324
|
+
`queue: waiting for a free slot — position ${run.queue.position} of ${run.queue.of}; `
|
|
325
|
+
+ 'it starts automatically when an active run finishes, does not count against maxActiveRuns while it waits, '
|
|
326
|
+
+ `and fails if no slot frees by ${run.queue.timeoutAt}`,
|
|
327
|
+
)
|
|
328
|
+
} else if (run.queue?.expired) {
|
|
329
|
+
lines.push(`queue: timed out after waiting ${run.queue.of > 0 ? `behind ${run.queue.of} run(s)` : 'for a slot'}; it never started`)
|
|
330
|
+
} else if (run.queue?.cancelled) {
|
|
331
|
+
lines.push('queue: cancelled while waiting for a slot; it never started')
|
|
332
|
+
}
|
|
333
|
+
const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
|
|
334
|
+
if (unreadable > 0) {
|
|
335
|
+
lines.push(
|
|
336
|
+
`usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
|
|
337
|
+
+ 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
|
|
338
|
+
)
|
|
339
|
+
}
|
|
340
|
+
const cost = costLine(run)
|
|
341
|
+
if (cost) lines.push(cost)
|
|
342
|
+
if (run.memory?.digest) {
|
|
343
|
+
lines.push(
|
|
344
|
+
`memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
|
|
345
|
+
+ `(${run.memory.digestChars} chars)`,
|
|
346
|
+
)
|
|
347
|
+
}
|
|
348
|
+
if (run.attention?.issue) {
|
|
349
|
+
lines.push(`attention: ${run.attention.issue}`)
|
|
350
|
+
}
|
|
351
|
+
if (run.attention?.items?.length > 0) {
|
|
352
|
+
const items = run.attention.items
|
|
353
|
+
const idOf = item => item.id ?? `q${items.indexOf(item) + 1}`
|
|
354
|
+
const open = items.filter(item => !item.answer)
|
|
355
|
+
const first = open[0] ?? items[0]
|
|
356
|
+
if (open.length > 0) {
|
|
357
|
+
lines.push(`needs your decision: ${first.question}${first.source ? ` (from ${first.source})` : ''}`)
|
|
358
|
+
if (first.options?.length) lines.push(`options: ${first.options.join(' | ')}`)
|
|
359
|
+
if (first.reason) lines.push(`why: ${first.reason}`)
|
|
360
|
+
lines.push(`attention id: ${idOf(first)}`)
|
|
361
|
+
} else {
|
|
362
|
+
// Answering does not hide the question: the record shows what was decided.
|
|
363
|
+
lines.push(`answered [${idOf(first)}]: ${first.question} — ${first.answer}`)
|
|
364
|
+
}
|
|
365
|
+
if (open.length > 1) {
|
|
366
|
+
lines.push(`and ${open.length - 1} more open question(s): ${open.slice(1).map(idOf).join(', ')}`)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (Array.isArray(run.followups) && run.followups.length > 0) {
|
|
370
|
+
const pending = run.followups.filter(entry => !entry.appliedAt)
|
|
371
|
+
const missed = pending.filter(entry => entry.missedAt)
|
|
372
|
+
const applied = run.followups.length - pending.length
|
|
373
|
+
if (applied > 0) {
|
|
374
|
+
const stages = [...new Set(run.followups.filter(entry => entry.appliedAt).map(entry => entry.appliedAtStage))]
|
|
375
|
+
lines.push(`instructions: ${applied} added during the run, applied at ${stages.join(' / ')}`)
|
|
376
|
+
}
|
|
377
|
+
if (pending.length > missed.length) {
|
|
378
|
+
lines.push(
|
|
379
|
+
`instructions: ${pending.length - missed.length} waiting; they take effect at ${followupEffect(run).detail}`,
|
|
380
|
+
)
|
|
381
|
+
}
|
|
382
|
+
if (missed.length > 0) {
|
|
383
|
+
lines.push(
|
|
384
|
+
`instructions: ${missed.length} never took effect — ${missed[0].missedReason ?? 'the run settled first'}`,
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
if (Array.isArray(run.milestones) && run.milestones.length > 0) {
|
|
389
|
+
// Times are UTC because the record is ISO; a status line is not a place to
|
|
390
|
+
// start guessing the reader's timezone.
|
|
391
|
+
lines.push(`milestones: ${run.milestones
|
|
392
|
+
.map(milestone => `${milestone.name}@${String(milestone.at ?? '').slice(11, 19)}`)
|
|
393
|
+
.join(' → ')}`)
|
|
394
|
+
}
|
|
395
|
+
lines.push(...describeWorkspace(run.workspace))
|
|
396
|
+
const reportArtifact = (run.artifacts ?? []).find(artifact => artifact?.kind === 'report')
|
|
397
|
+
if (reportArtifact?.path) lines.push(`report file: ${reportArtifact.path} (${reportArtifact.bytes} bytes)`)
|
|
398
|
+
else if (run.artifactError) lines.push(`report file: not written — ${run.artifactError}`)
|
|
399
|
+
if (run.deduped) {
|
|
400
|
+
lines.push(
|
|
401
|
+
'deduped: true — an active run with the same goal already exists, so this call joined it instead of starting '
|
|
402
|
+
+ 'a second one (pass allow_duplicate: true to start another)',
|
|
403
|
+
)
|
|
404
|
+
}
|
|
405
|
+
if (run.selfHeal?.retried) {
|
|
406
|
+
lines.push(
|
|
407
|
+
`self-heal: retried ${run.selfHeal.retried} failed subtask(s) in ${run.selfHeal.rounds} extra round(s); `
|
|
408
|
+
+ `${run.selfHeal.recovered} recovered` + (run.selfHeal.model ? ` (on ${run.selfHeal.model})` : ''),
|
|
409
|
+
)
|
|
410
|
+
}
|
|
411
|
+
if (run.memoryWrite?.written > 0) {
|
|
412
|
+
lines.push(`memory: wrote ${run.memoryWrite.written} note(s) for the next run`)
|
|
413
|
+
} else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
|
|
414
|
+
lines.push(`memory note not written: ${run.memoryWrite.reason}`)
|
|
415
|
+
}
|
|
416
|
+
if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
|
|
417
|
+
if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
|
|
418
|
+
if (run.status === 'interrupted' && run.error) {
|
|
419
|
+
// Not a failure: the host went away and the run is waiting to be resumed.
|
|
420
|
+
lines.push(`note: ${run.error}`)
|
|
421
|
+
} else if (run.status !== 'cancelled' && run.error) {
|
|
422
|
+
lines.push(`error: ${summarizeError(run.error)}`)
|
|
423
|
+
if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
|
|
424
|
+
}
|
|
425
|
+
if (notifyFailed(run)) {
|
|
426
|
+
lines.push(`notify: not delivered — ${run.notify.reason}`)
|
|
427
|
+
}
|
|
428
|
+
if (run.cancelPending) {
|
|
429
|
+
lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
|
|
430
|
+
}
|
|
431
|
+
for (const subtask of run.subtasks) {
|
|
432
|
+
const tokens = subtask.usage
|
|
433
|
+
? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out${subtaskCostText(subtask)}`
|
|
434
|
+
: ''
|
|
435
|
+
// A subtask waiting on a dependency is not running and not failed; saying
|
|
436
|
+
// which tasks it waits for is the difference between "stuck" and "queued".
|
|
437
|
+
const waiting = subtask.status === 'waiting' && subtask.waitingOn?.length > 0
|
|
438
|
+
? ` — waiting on ${subtask.waitingOn.join(', ')}`
|
|
439
|
+
: ''
|
|
440
|
+
const skipped = subtask.status === 'skipped' && subtask.skippedReason
|
|
441
|
+
? ` — skipped: ${subtask.skippedReason}`
|
|
442
|
+
: ''
|
|
443
|
+
const detail = skipped || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
|
|
444
|
+
// A cancelled run never judged its unfinished subtasks, so calling them
|
|
445
|
+
// "pending" or "failed (attempts 0)" would misreport what happened.
|
|
446
|
+
const status = run.status === 'cancelled' && subtask.status !== 'completed'
|
|
447
|
+
? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
|
|
448
|
+
: subtask.status
|
|
449
|
+
lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${waiting}${detail}`)
|
|
450
|
+
}
|
|
451
|
+
const failed = run.subtasks.find(subtask => subtask.error)
|
|
452
|
+
if (failed) {
|
|
453
|
+
const hint = classifyError(failed.error).hint
|
|
454
|
+
if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
|
|
455
|
+
}
|
|
456
|
+
if (includeReport && run.report) {
|
|
457
|
+
lines.push('', 'report:', '', preview(run.report))
|
|
458
|
+
}
|
|
459
|
+
const openQuestion = (run.attention?.items ?? []).find(item => !item.answer)
|
|
460
|
+
if (openQuestion) {
|
|
461
|
+
// The user can act on this line directly; the id is what makes the answer
|
|
462
|
+
// land on the question it belongs to.
|
|
463
|
+
lines.push('', `next: superagent_answer run_id="${run.id}" attention_id="${openQuestion.id ?? 'q1'}" answer="..."`)
|
|
464
|
+
}
|
|
465
|
+
if (!TERMINAL_STATUSES.has(run.status)) {
|
|
466
|
+
lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
|
|
467
|
+
} else if (run.status === 'interrupted') {
|
|
468
|
+
lines.push('', `next: superagent_resume run_id="${run.id}"`)
|
|
469
|
+
}
|
|
470
|
+
return lines.join('\n')
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function formatBytes(bytes) {
|
|
474
|
+
if (bytes < 1024) return `${bytes} B`
|
|
475
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
|
476
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** True when a run finished but its owner was never told, and that is a problem. */
|
|
480
|
+
function notifyFailed(run) {
|
|
481
|
+
if (!run.notify || run.notify.delivered) return false
|
|
482
|
+
return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** What a failed run already tried, so the message is not just "it broke". */
|
|
486
|
+
function triedLine(run) {
|
|
487
|
+
const attempts = run.limits?.attempts ?? 1
|
|
488
|
+
const parts = [`tried: ${attempts} attempt(s) per subtask`]
|
|
489
|
+
if (run.selfHeal?.rounds > 0) {
|
|
490
|
+
parts.push(`${run.selfHeal.rounds} self-heal round(s), ${run.selfHeal.recovered ?? 0} recovered`)
|
|
491
|
+
}
|
|
492
|
+
if (run.selfHeal?.model) parts.push(`switched to ${run.selfHeal.model} for the retry`)
|
|
493
|
+
return `${parts.join('; ')}.`
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function formatList(runs, limit, stats = null) {
|
|
497
|
+
if (runs.length === 0) return 'no superagent runs recorded'
|
|
498
|
+
const rows = runs.slice(0, limit).map(run => {
|
|
499
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
500
|
+
return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
|
|
501
|
+
+ `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
|
|
502
|
+
})
|
|
503
|
+
const lines = [`${runs.length} run(s):`, ...rows]
|
|
504
|
+
if (stats) {
|
|
505
|
+
lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
|
|
506
|
+
+ (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
|
|
507
|
+
if (stats.memory) {
|
|
508
|
+
lines.push(`memory: ${stats.memory.entries} note(s), ${formatBytes(stats.memory.bytes)} in ${path.dirname(stats.memory.path)}`)
|
|
509
|
+
}
|
|
510
|
+
if (stats.pendingNotifications > 0) {
|
|
511
|
+
lines.push(`notifications: ${stats.pendingNotifications} run(s) held back by the hourly limit; `
|
|
512
|
+
+ 'they are folded into the next message')
|
|
513
|
+
}
|
|
514
|
+
if (stats.ledger) {
|
|
515
|
+
const ledger = stats.ledger
|
|
516
|
+
if (ledger.runs === 0) {
|
|
517
|
+
lines.push(`ledger: no spend recorded in the last ${stats.ledgerDays} days`)
|
|
518
|
+
} else if (ledger.priced === 0) {
|
|
519
|
+
lines.push(`ledger: ${ledger.runs} run(s) in the last ${stats.ledgerDays} days are unpriced — `
|
|
520
|
+
+ 'no configured price matches their models, so no total is claimed')
|
|
521
|
+
} else {
|
|
522
|
+
const total = ledger.mixedCurrency
|
|
523
|
+
? `${formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })}`
|
|
524
|
+
: formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency })
|
|
525
|
+
lines.push(`ledger: ${total} across ${ledger.priced} priced run(s) in the last ${stats.ledgerDays} days`
|
|
526
|
+
+ (ledger.unpricedRuns > 0 ? ` (${ledger.unpricedRuns} run(s) partially unpriced)` : '')
|
|
527
|
+
+ (ledger.mixedCurrency ? ' (mixed currencies; figure uses the first)' : ''))
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return lines.join('\n')
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function toolText(text) {
|
|
535
|
+
return [{ type: 'text', text }]
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function defineTool(spec) {
|
|
539
|
+
return {
|
|
540
|
+
name: spec.name,
|
|
541
|
+
description: spec.description,
|
|
542
|
+
parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
|
|
543
|
+
output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
|
|
544
|
+
execute: spec.execute,
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Mount the plugin.
|
|
550
|
+
* @param {object} ctx - Cordis context.
|
|
551
|
+
* @param {object} [config] - row config from `cordis.patch.yml`.
|
|
552
|
+
*/
|
|
553
|
+
export function apply(ctx, config) {
|
|
554
|
+
const log = message => console.error(`[dsh-superagent] ${message}`)
|
|
555
|
+
const configuredPort = config?.controlPort
|
|
556
|
+
const cfg = resolveConfig(config)
|
|
557
|
+
if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
|
|
558
|
+
log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
|
|
559
|
+
}
|
|
560
|
+
if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
|
|
561
|
+
console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
|
|
566
|
+
const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
|
|
567
|
+
const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
|
|
568
|
+
// The ledger is an append-only history of priced runs. Writing it here, from
|
|
569
|
+
// the read paths, keeps it out of the scheduling loop: a status or list call
|
|
570
|
+
// is already a snapshot of finished work, and a run is recorded exactly once.
|
|
571
|
+
const ledger = createLedger(store.root, { warn: log })
|
|
572
|
+
const LEDGER_WINDOW_DAYS = 30
|
|
573
|
+
|
|
574
|
+
/** Append finished runs to the spend ledger; a ledger fault never blocks a tool. */
|
|
575
|
+
async function recordSpend(runs) {
|
|
576
|
+
for (const run of runs) {
|
|
577
|
+
try {
|
|
578
|
+
await ledger.record(run)
|
|
579
|
+
} catch (error) {
|
|
580
|
+
log(`ledger: cannot record run ${run?.id}: ${error?.message ?? error}`)
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// A state directory inside the installed package would put the notebook in a
|
|
586
|
+
// directory that is meant to be shipped byte-for-byte from git. Refuse rather
|
|
587
|
+
// than rely on the `.gitignore` the notebook writes for itself.
|
|
588
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
589
|
+
const memoryBlocked = isInside(store.root, packageRoot)
|
|
590
|
+
const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
|
|
591
|
+
if (cfg.memory && memoryBlocked) {
|
|
592
|
+
log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
|
|
593
|
+
}
|
|
594
|
+
// Built-ins need no storage; only custom templates touch the state directory,
|
|
595
|
+
// and a state directory inside the package must not receive new files.
|
|
596
|
+
const templates = createTemplateStore(store.root, { warn: log })
|
|
597
|
+
const notifyPolicy = createNotifyPolicy({
|
|
598
|
+
stateFile: path.join(store.root, 'notifications.json'),
|
|
599
|
+
maxPerHour: cfg.maxNotificationsPerHour,
|
|
600
|
+
warn: log,
|
|
601
|
+
})
|
|
602
|
+
// One wake-up per run, delivered in order per session. A busy session loop
|
|
603
|
+
// can reject a followup, so the same message is retried with backoff instead
|
|
604
|
+
// of being reported as lost on the first refusal.
|
|
605
|
+
const outbox = createOutbox({ retries: cfg.notifyRetries, delayMs: cfg.notifyRetryDelayMs })
|
|
606
|
+
|
|
607
|
+
/** Child sessions spawned by this process; a run may not be started from one. */
|
|
608
|
+
const childIds = new Set()
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The subagent service is optional, so it is read from the service store at
|
|
612
|
+
* call time rather than declared as an injection: a profile without it must
|
|
613
|
+
* still mount the eight tools (they then explain what is missing), and reading
|
|
614
|
+
* it lazily also sees a service that registers after this plugin.
|
|
615
|
+
*/
|
|
616
|
+
function getSubagents() {
|
|
617
|
+
if (typeof ctx.get === 'function') {
|
|
618
|
+
const service = ctx.get('subagents')
|
|
619
|
+
if (service) return service
|
|
620
|
+
}
|
|
621
|
+
// The direct property is topology-sensitive on a real host; it is only a
|
|
622
|
+
// fallback for test contexts that provide the service without a registry.
|
|
623
|
+
try {
|
|
624
|
+
return ctx.subagents
|
|
625
|
+
} catch {
|
|
626
|
+
return undefined
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Remember a child id for the recursion guard without growing forever. */
|
|
631
|
+
function rememberChild(childId) {
|
|
632
|
+
if (!childId) return
|
|
633
|
+
childIds.add(childId)
|
|
634
|
+
if (childIds.size > 512) childIds.delete(childIds.values().next().value)
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Map a run outcome to one message for the owning session.
|
|
639
|
+
*
|
|
640
|
+
* The notification policy decides first: a cancelled run is never announced,
|
|
641
|
+
* and a burst above the hourly cap is buffered instead of waking the session
|
|
642
|
+
* once per run. The followup is awaited: an unhandled rejection from it would
|
|
643
|
+
* otherwise escape as a host-level error while the run already claims it was
|
|
644
|
+
* delivered.
|
|
645
|
+
*/
|
|
646
|
+
async function notifyParent(run) {
|
|
647
|
+
if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
|
|
648
|
+
if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
|
|
649
|
+
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
650
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
|
|
651
|
+
if (!agent || typeof agent.followup !== 'function') {
|
|
652
|
+
log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
|
|
653
|
+
return {
|
|
654
|
+
delivered: false,
|
|
655
|
+
reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
// Reserve only once the session is known to exist: a missing session is not
|
|
659
|
+
// an interruption and must not consume the hourly budget.
|
|
660
|
+
const verdict = await notifyPolicy.reserve(run)
|
|
661
|
+
if (!verdict.allowed) return { delivered: false, reason: verdict.reason }
|
|
662
|
+
|
|
663
|
+
const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
|
|
664
|
+
const decision = (run.attention?.items ?? []).find(item => !item.answer) ?? null
|
|
665
|
+
const questionId = decision?.id ?? (decision ? 'q1' : null)
|
|
666
|
+
const lines = decision
|
|
667
|
+
? [`[superagent] needs your decision on run ${run.id} (question ${questionId}): ${decision.question}`]
|
|
668
|
+
: [`[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`]
|
|
669
|
+
if (decision) {
|
|
670
|
+
if (decision.options?.length) lines.push(`Options: ${decision.options.join(' / ')}.`)
|
|
671
|
+
lines.push(`The run itself ended as ${run.status} (${completed}/${run.subtasks.length} subtasks).`)
|
|
672
|
+
lines.push(`Answer with superagent_answer attention_id="${questionId}".`)
|
|
673
|
+
} else if (run.attention?.issue) {
|
|
674
|
+
// A malformed block asked for a decision too; keeping it quiet would look
|
|
675
|
+
// like an ordinary finished run.
|
|
676
|
+
lines.push(`Attention: ${run.attention.issue}.`)
|
|
677
|
+
}
|
|
678
|
+
if (!decision && run.status !== 'completed') lines.push(triedLine(run))
|
|
679
|
+
if (run.workspace?.conflicts > 0) {
|
|
680
|
+
// A conflict is the one outcome the user must act on even when the run
|
|
681
|
+
// "completed": saying only "finished: completed" would bury it.
|
|
682
|
+
lines.push(
|
|
683
|
+
`${run.workspace.conflicts} worker branch(es) could not be merged into ${run.workspace.base}; `
|
|
684
|
+
+ 'both sides were kept, so nothing was lost — superagent_status lists the conflicting files and the branch '
|
|
685
|
+
+ 'to merge by hand.',
|
|
686
|
+
)
|
|
687
|
+
} else if (run.workspace?.mode === 'unavailable') {
|
|
688
|
+
lines.push(`Workspace isolation was unavailable (${run.workspace.reason}), so the workers shared one directory.`)
|
|
689
|
+
}
|
|
690
|
+
if (verdict.batch.length > 0) {
|
|
691
|
+
lines.push(
|
|
692
|
+
'Also finished since the last update: '
|
|
693
|
+
+ `${verdict.batch.map(item => `${item.id} ${item.status}`).join('; ')}.`,
|
|
694
|
+
)
|
|
695
|
+
}
|
|
696
|
+
lines.push(`Call superagent_status with run_id="${run.id}" to read the report.`)
|
|
697
|
+
try {
|
|
698
|
+
await outbox.enqueue(run.parentSessionId, () => agent.followup({
|
|
699
|
+
id: randomUUID(),
|
|
700
|
+
role: 'user',
|
|
701
|
+
content: [{ type: 'text', text: lines.join(' ') }],
|
|
702
|
+
source: { kind: 'user' },
|
|
703
|
+
}))
|
|
704
|
+
run.notified = true
|
|
705
|
+
return { delivered: true }
|
|
706
|
+
} catch (error) {
|
|
707
|
+
log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
|
|
708
|
+
// The folded runs were reserved but never delivered. Put them back so the
|
|
709
|
+
// next allowed message still carries them, up to the policy's retry cap.
|
|
710
|
+
await notifyPolicy.restore(verdict.batch).catch(restoreError => {
|
|
711
|
+
log(`cannot restore ${verdict.batch.length} batched notification(s): ${restoreError?.message ?? restoreError}`)
|
|
712
|
+
})
|
|
713
|
+
return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const orchestrator = createOrchestrator({
|
|
718
|
+
store,
|
|
719
|
+
config: cfg,
|
|
720
|
+
log,
|
|
721
|
+
readUsage,
|
|
722
|
+
memory,
|
|
723
|
+
notify: notifyParent,
|
|
724
|
+
async spawnChild({ label, prompt, parent, signal, model }) {
|
|
725
|
+
const subagents = getSubagents()
|
|
726
|
+
if (!subagents || typeof subagents.startActivation !== 'function') {
|
|
727
|
+
const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
|
|
728
|
+
// The service can also disappear in the middle of a run, when the host
|
|
729
|
+
// is shutting down. The orchestrator turns this code into `interrupted`
|
|
730
|
+
// instead of a failed subtask, so the run stays resumable.
|
|
731
|
+
error.code = 'subagent-unavailable'
|
|
732
|
+
throw error
|
|
733
|
+
}
|
|
734
|
+
const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
|
|
735
|
+
const capabilities = provider?.capabilities ?? null
|
|
736
|
+
const agentOptions = {}
|
|
737
|
+
// Only the self-heal round passes a model override; everything else keeps
|
|
738
|
+
// the configured route.
|
|
739
|
+
const childModel = model ?? cfg.childModel
|
|
740
|
+
if (cfg.childProvider) agentOptions.provider = cfg.childProvider
|
|
741
|
+
if (childModel) agentOptions.model = childModel
|
|
742
|
+
const request = {
|
|
743
|
+
parent,
|
|
744
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
745
|
+
...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
|
|
746
|
+
}
|
|
747
|
+
// A preset is the host's only way to give a child a narrower tool set:
|
|
748
|
+
// the start request has no tool filter in dsh 0.2.2-rc.1.
|
|
749
|
+
if (cfg.childPreset) {
|
|
750
|
+
if (capabilities && !capabilities.agentPreset) {
|
|
751
|
+
throw new Error(
|
|
752
|
+
`childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
|
|
753
|
+
+ 'independent agent presets, so this child would run with this session\'s tools',
|
|
754
|
+
)
|
|
755
|
+
}
|
|
756
|
+
request.agentPreset = cfg.childPreset
|
|
757
|
+
}
|
|
758
|
+
// Recursion is bounded unless the operator explicitly left it to the
|
|
759
|
+
// backend. Silently dropping the cap would hand 8 parallel workers the
|
|
760
|
+
// right to spawn their own armies.
|
|
761
|
+
if (cfg.maxSubagentDepth !== 'provider-managed') {
|
|
762
|
+
if (capabilities && !capabilities.depthLimit) {
|
|
763
|
+
throw new Error(
|
|
764
|
+
`subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
|
|
765
|
+
+ 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
|
|
766
|
+
+ 'the backend\'s own cap',
|
|
767
|
+
)
|
|
768
|
+
}
|
|
769
|
+
request.maxDepth = cfg.maxSubagentDepth
|
|
770
|
+
}
|
|
771
|
+
const activation = await subagents.startActivation({
|
|
772
|
+
provider: cfg.provider,
|
|
773
|
+
label,
|
|
774
|
+
request,
|
|
775
|
+
signal,
|
|
776
|
+
delivery: 'caller',
|
|
777
|
+
})
|
|
778
|
+
rememberChild(activation.childId)
|
|
779
|
+
return {
|
|
780
|
+
childId: activation.childId,
|
|
781
|
+
result: activation.result,
|
|
782
|
+
dispose: async () => {
|
|
783
|
+
try {
|
|
784
|
+
await activation.dispose()
|
|
785
|
+
} catch (error) {
|
|
786
|
+
log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
|
|
787
|
+
}
|
|
788
|
+
},
|
|
789
|
+
}
|
|
790
|
+
},
|
|
791
|
+
})
|
|
792
|
+
|
|
793
|
+
// Recovery runs once at mount; tools wait for it so a run left active by a
|
|
794
|
+
// dead host reads as interrupted before the first tool call sees it. A
|
|
795
|
+
// failure to initialize the state directory is kept and reported by every
|
|
796
|
+
// tool: hiding it behind "no runs recorded" is how a broken stateDir looks
|
|
797
|
+
// like an empty one.
|
|
798
|
+
let stateError = null
|
|
799
|
+
const ready = (async () => {
|
|
800
|
+
try {
|
|
801
|
+
await orchestrator.recover()
|
|
802
|
+
} catch (error) {
|
|
803
|
+
stateError = error instanceof Error ? error : new Error(String(error))
|
|
804
|
+
log(`state directory is not usable: ${stateError.message}`)
|
|
805
|
+
return
|
|
806
|
+
}
|
|
807
|
+
// Backfill runs that settled while no tool was watching, so the ledger is
|
|
808
|
+
// complete after a restart. Recording is idempotent: a normal mount adds
|
|
809
|
+
// nothing for runs already written.
|
|
810
|
+
try {
|
|
811
|
+
await recordSpend(await orchestrator.list())
|
|
812
|
+
} catch (error) {
|
|
813
|
+
log(`ledger: cannot backfill from runs: ${error?.message ?? error}`)
|
|
814
|
+
}
|
|
815
|
+
// Templates are optional: a failure here must not make every run tool
|
|
816
|
+
// answer with a state error, and the built-ins still work without a file.
|
|
817
|
+
if (!memoryBlocked) {
|
|
818
|
+
try {
|
|
819
|
+
await templates.init()
|
|
820
|
+
} catch (error) {
|
|
821
|
+
log(`cannot create the template directory ${templates.dir}: ${error?.message ?? error}`)
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
|
|
825
|
+
try {
|
|
826
|
+
const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
|
|
827
|
+
if (removed.length > 0) {
|
|
828
|
+
log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
|
|
829
|
+
}
|
|
830
|
+
} catch (error) {
|
|
831
|
+
log(`cannot prune old runs: ${error?.message ?? error}`)
|
|
832
|
+
}
|
|
833
|
+
})()
|
|
834
|
+
|
|
835
|
+
/** True when the host actually provides a subagent service. */
|
|
836
|
+
function hasSubagents() {
|
|
837
|
+
const subagents = getSubagents()
|
|
838
|
+
return Boolean(subagents && typeof subagents.startActivation === 'function')
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function requireAgent(exec) {
|
|
842
|
+
const agent = exec?.agent
|
|
843
|
+
if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
|
|
844
|
+
if (childIds.has(agent.id)) {
|
|
845
|
+
return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
|
|
846
|
+
}
|
|
847
|
+
return { agent }
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Resolve the session named by an HTTP caller. An embedded start is a normal
|
|
852
|
+
* run: it needs a live agent to own the children, and the same recursion
|
|
853
|
+
* guard as a tool call. A synthetic parent would spawn children no session
|
|
854
|
+
* owns, so a missing session is an error, never a fallback.
|
|
855
|
+
* @param {unknown} sessionId - `session_id` from the request body.
|
|
856
|
+
* @returns {object} live agent.
|
|
857
|
+
*/
|
|
858
|
+
function resolveSession(sessionId) {
|
|
859
|
+
const id = typeof sessionId === 'string' ? sessionId.trim() : ''
|
|
860
|
+
if (!id) {
|
|
861
|
+
throw new Error(
|
|
862
|
+
'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
|
|
863
|
+
)
|
|
864
|
+
}
|
|
865
|
+
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
866
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
|
|
867
|
+
if (!agent || typeof agent !== 'object' || !agent.id) {
|
|
868
|
+
throw new Error(
|
|
869
|
+
`no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
|
|
870
|
+
+ 'tool call inside it',
|
|
871
|
+
)
|
|
872
|
+
}
|
|
873
|
+
if (childIds.has(agent.id)) {
|
|
874
|
+
throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
|
|
875
|
+
}
|
|
876
|
+
return agent
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
ctx.tools.register(defineTool({
|
|
880
|
+
name: 'superagent_start',
|
|
881
|
+
description:
|
|
882
|
+
'Start a long-horizon autonomous run: a planner decomposes the goal into subtasks, '
|
|
883
|
+
+ 'independent subtasks run in parallel child agents while ones with a declared dependency wait for it, '
|
|
884
|
+
+ 'and their reports are merged into one final report. '
|
|
885
|
+
+ 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
|
|
886
|
+
+ 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
|
|
887
|
+
+ 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
|
|
888
|
+
+ 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
|
|
889
|
+
+ 'so they survive a host restart and can be resumed or cancelled.',
|
|
890
|
+
properties: {
|
|
891
|
+
goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
|
|
892
|
+
mode: {
|
|
893
|
+
type: 'string',
|
|
894
|
+
enum: ['planned', 'direct'],
|
|
895
|
+
description: 'planned (default): planner, parallel workers, merged report. direct: one worker runs the whole '
|
|
896
|
+
+ 'goal, with no planning or aggregation, and its reply is returned unchanged. Choose direct only when the '
|
|
897
|
+
+ 'task is one self-contained pass that gains nothing from splitting.',
|
|
898
|
+
},
|
|
899
|
+
queue: {
|
|
900
|
+
type: 'boolean',
|
|
901
|
+
description: 'When maxActiveRuns is already in use, wait for a free slot instead of failing. The run returns '
|
|
902
|
+
+ `status "queued" with its position, starts automatically when another run finishes, and gives up after `
|
|
903
|
+
+ `queueTimeoutMinutes (default ${DEFAULTS.queueTimeoutMinutes}). Off by default; at most maxQueuedRuns `
|
|
904
|
+
+ `(default ${DEFAULTS.maxQueuedRuns}) may wait.`,
|
|
905
|
+
},
|
|
906
|
+
max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
|
|
907
|
+
max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
|
|
908
|
+
deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
|
|
909
|
+
allow_duplicate: {
|
|
910
|
+
type: 'boolean',
|
|
911
|
+
description: 'Start a second run for the same goal even when an active run already has it. '
|
|
912
|
+
+ 'By default the active run id is returned instead, so a retry cannot double the spend.',
|
|
913
|
+
},
|
|
914
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
|
|
915
|
+
},
|
|
916
|
+
required: ['goal'],
|
|
917
|
+
async execute(args = {}, exec) {
|
|
918
|
+
const check = requireAgent(exec)
|
|
919
|
+
if (check.error) return check.error
|
|
920
|
+
try {
|
|
921
|
+
await ready
|
|
922
|
+
if (stateError) return describeError(stateError)
|
|
923
|
+
if (!hasSubagents()) {
|
|
924
|
+
return describeError(
|
|
925
|
+
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
926
|
+
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
927
|
+
)
|
|
928
|
+
}
|
|
929
|
+
const run = await orchestrator.start({
|
|
930
|
+
goal: args.goal,
|
|
931
|
+
parentSessionId: check.agent.id,
|
|
932
|
+
parent: check.agent,
|
|
933
|
+
clientTimeZone: exec.clientTimeZone,
|
|
934
|
+
allowDuplicate: args.allow_duplicate === true,
|
|
935
|
+
mode: args.mode,
|
|
936
|
+
queue: args.queue === true,
|
|
937
|
+
overrides: {
|
|
938
|
+
maxSubtasks: args.max_subtasks,
|
|
939
|
+
maxParallel: args.max_parallel,
|
|
940
|
+
deadlineMinutes: args.deadline_minutes,
|
|
941
|
+
},
|
|
942
|
+
})
|
|
943
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
944
|
+
if (waitSeconds > 0) {
|
|
945
|
+
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
946
|
+
await recordSpend([finished])
|
|
947
|
+
// `status` reads the stored run, which never has the transient join
|
|
948
|
+
// marker; carry it over so the caller can still see it joined.
|
|
949
|
+
return formatRun(run.deduped ? { ...finished, deduped: true } : finished)
|
|
950
|
+
}
|
|
951
|
+
if (run.queue?.waiting) {
|
|
952
|
+
return `${formatRun(run, { includeReport: false })}\n\nQueued, not started: the run begins automatically when `
|
|
953
|
+
+ 'an active run finishes. Poll with superagent_status or cancel it with superagent_cancel.'
|
|
954
|
+
}
|
|
955
|
+
return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
|
|
956
|
+
+ 'the run keeps going after this tool call returns.'
|
|
957
|
+
} catch (error) {
|
|
958
|
+
return describeError(error)
|
|
959
|
+
}
|
|
960
|
+
},
|
|
961
|
+
}))
|
|
962
|
+
|
|
963
|
+
ctx.tools.register(defineTool({
|
|
964
|
+
name: 'superagent_status',
|
|
965
|
+
description:
|
|
966
|
+
'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
|
|
967
|
+
+ 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
|
|
968
|
+
properties: {
|
|
969
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
970
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
971
|
+
},
|
|
972
|
+
required: ['run_id'],
|
|
973
|
+
async execute(args = {}) {
|
|
974
|
+
try {
|
|
975
|
+
await ready
|
|
976
|
+
if (stateError) return describeError(stateError)
|
|
977
|
+
const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
|
|
978
|
+
await recordSpend([run])
|
|
979
|
+
return formatRun(run)
|
|
980
|
+
} catch (error) {
|
|
981
|
+
return describeError(error)
|
|
982
|
+
}
|
|
983
|
+
},
|
|
984
|
+
}))
|
|
985
|
+
|
|
986
|
+
ctx.tools.register(defineTool({
|
|
987
|
+
name: 'superagent_list',
|
|
988
|
+
description: 'List recorded superagent runs, newest first, with status and progress.',
|
|
989
|
+
properties: {
|
|
990
|
+
limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
|
|
991
|
+
},
|
|
992
|
+
async execute(args = {}) {
|
|
993
|
+
try {
|
|
994
|
+
await ready
|
|
995
|
+
if (stateError) return describeError(stateError)
|
|
996
|
+
const runs = await orchestrator.list()
|
|
997
|
+
await recordSpend(runs)
|
|
998
|
+
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
999
|
+
const memoryStats = memory
|
|
1000
|
+
? await memory.stats({ scope: cfg.memoryScope, maxAgeDays: cfg.memoryMaxAgeDays }).catch(() => null)
|
|
1001
|
+
: null
|
|
1002
|
+
const notifyState = await notifyPolicy.summary().catch(() => null)
|
|
1003
|
+
const ledgerStats = await ledger
|
|
1004
|
+
.summarize({ since: Date.now() - LEDGER_WINDOW_DAYS * 86400000 })
|
|
1005
|
+
.catch(() => null)
|
|
1006
|
+
const extra = stats
|
|
1007
|
+
? {
|
|
1008
|
+
...stats,
|
|
1009
|
+
root: store.root,
|
|
1010
|
+
memory: memoryStats,
|
|
1011
|
+
pendingNotifications: notifyState?.pending?.length ?? 0,
|
|
1012
|
+
ledger: ledgerStats,
|
|
1013
|
+
ledgerDays: LEDGER_WINDOW_DAYS,
|
|
1014
|
+
}
|
|
1015
|
+
: null
|
|
1016
|
+
return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
return describeError(error)
|
|
1019
|
+
}
|
|
1020
|
+
},
|
|
1021
|
+
}))
|
|
1022
|
+
|
|
1023
|
+
ctx.tools.register(defineTool({
|
|
1024
|
+
name: 'superagent_cancel',
|
|
1025
|
+
description:
|
|
1026
|
+
'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
|
|
1027
|
+
+ 'so the partial work stays inspectable.',
|
|
1028
|
+
properties: {
|
|
1029
|
+
run_id: { type: 'string', description: 'Run id to cancel.' },
|
|
1030
|
+
},
|
|
1031
|
+
required: ['run_id'],
|
|
1032
|
+
async execute(args = {}, exec) {
|
|
1033
|
+
const check = requireAgent(exec)
|
|
1034
|
+
if (check.error) return check.error
|
|
1035
|
+
try {
|
|
1036
|
+
await ready
|
|
1037
|
+
if (stateError) return describeError(stateError)
|
|
1038
|
+
const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
|
|
1039
|
+
await recordSpend([run])
|
|
1040
|
+
const head = run.status === 'cancelled'
|
|
1041
|
+
? `cancelled ${run.id}`
|
|
1042
|
+
: run.cancelPending
|
|
1043
|
+
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1044
|
+
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1045
|
+
return `${head}\n\n${formatRun(run, { includeReport: false })}`
|
|
1046
|
+
} catch (error) {
|
|
1047
|
+
return describeError(error)
|
|
1048
|
+
}
|
|
1049
|
+
},
|
|
1050
|
+
}))
|
|
1051
|
+
|
|
1052
|
+
ctx.tools.register(defineTool({
|
|
1053
|
+
name: 'superagent_resume',
|
|
1054
|
+
description:
|
|
1055
|
+
'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
|
|
1056
|
+
+ 'Completed subtasks are kept; pending and failed ones run again. A completed run is reopened only when it '
|
|
1057
|
+
+ 'holds an answer that never reached a prompt, so its aggregation can apply the decision.',
|
|
1058
|
+
properties: {
|
|
1059
|
+
run_id: { type: 'string', description: 'Run id to resume.' },
|
|
1060
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
|
|
1061
|
+
force: {
|
|
1062
|
+
type: 'boolean',
|
|
1063
|
+
description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
|
|
1064
|
+
},
|
|
1065
|
+
},
|
|
1066
|
+
required: ['run_id'],
|
|
1067
|
+
async execute(args = {}, exec) {
|
|
1068
|
+
const check = requireAgent(exec)
|
|
1069
|
+
if (check.error) return check.error
|
|
1070
|
+
try {
|
|
1071
|
+
await ready
|
|
1072
|
+
if (stateError) return describeError(stateError)
|
|
1073
|
+
if (!hasSubagents()) {
|
|
1074
|
+
return describeError(
|
|
1075
|
+
'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
|
|
1076
|
+
)
|
|
1077
|
+
}
|
|
1078
|
+
const run = await orchestrator.resume(
|
|
1079
|
+
String(args.run_id ?? '').trim(),
|
|
1080
|
+
check.agent,
|
|
1081
|
+
exec.clientTimeZone,
|
|
1082
|
+
{ force: args.force === true },
|
|
1083
|
+
)
|
|
1084
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1085
|
+
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1086
|
+
await recordSpend([current])
|
|
1087
|
+
return formatRun(current)
|
|
1088
|
+
} catch (error) {
|
|
1089
|
+
return describeError(error)
|
|
1090
|
+
}
|
|
1091
|
+
},
|
|
1092
|
+
}))
|
|
1093
|
+
|
|
1094
|
+
ctx.tools.register(defineTool({
|
|
1095
|
+
name: 'superagent_followup',
|
|
1096
|
+
description:
|
|
1097
|
+
'Add an instruction to a run that is already executing, instead of starting a second run. This is not a live '
|
|
1098
|
+
+ 'channel to the running children: the host has no way to append a message to a child activation, so the '
|
|
1099
|
+
+ 'instruction is queued on the run and carried by the next prompt built for it — the next worker spawn or the '
|
|
1100
|
+
+ 'aggregation, whichever comes first. Subtasks that are already running or finished keep their results. The '
|
|
1101
|
+
+ 'reply states exactly which boundary it will reach.',
|
|
1102
|
+
properties: {
|
|
1103
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1104
|
+
message: { type: 'string', description: 'The instruction or constraint to add.' },
|
|
1105
|
+
},
|
|
1106
|
+
required: ['run_id', 'message'],
|
|
1107
|
+
async execute(args = {}, exec) {
|
|
1108
|
+
const check = requireAgent(exec)
|
|
1109
|
+
if (check.error) return check.error
|
|
1110
|
+
try {
|
|
1111
|
+
await ready
|
|
1112
|
+
if (stateError) return describeError(stateError)
|
|
1113
|
+
const result = await orchestrator.followup(
|
|
1114
|
+
String(args.run_id ?? '').trim(),
|
|
1115
|
+
args.message,
|
|
1116
|
+
check.agent,
|
|
1117
|
+
)
|
|
1118
|
+
return [
|
|
1119
|
+
`instruction ${result.followup.id} added to run ${result.run.id} — ${result.run.status}`,
|
|
1120
|
+
`when it takes effect: ${result.effect.detail} (boundary: ${result.effect.boundary}).`,
|
|
1121
|
+
'A child that is already running is not interrupted and does not see it.',
|
|
1122
|
+
'',
|
|
1123
|
+
formatRun(result.run, { includeReport: false }),
|
|
1124
|
+
].join('\n')
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
return describeError(error)
|
|
1127
|
+
}
|
|
1128
|
+
},
|
|
1129
|
+
}))
|
|
1130
|
+
|
|
1131
|
+
ctx.tools.register(defineTool({
|
|
1132
|
+
name: 'superagent_answer',
|
|
1133
|
+
description:
|
|
1134
|
+
'Answer a question a run asked — the "needs your decision" item with a qN id — so that run continues with the '
|
|
1135
|
+
+ 'decision instead of a new run being started. An active run applies it at its next boundary; a finished run '
|
|
1136
|
+
+ 'is reopened and only its aggregation runs again, now with the answer. The answer is matched to one specific '
|
|
1137
|
+
+ 'question: an unknown, already answered, or expired question is refused instead of being attached to whatever '
|
|
1138
|
+
+ 'is open.',
|
|
1139
|
+
properties: {
|
|
1140
|
+
run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
|
|
1141
|
+
attention_id: {
|
|
1142
|
+
type: 'string',
|
|
1143
|
+
description: 'Question id from superagent_status, e.g. q1. Required when the run has more than one open question.',
|
|
1144
|
+
},
|
|
1145
|
+
answer: { type: 'string', description: 'The decision itself; one of the listed options is enough, free text is allowed.' },
|
|
1146
|
+
wait_seconds: { type: 'number', description: 'Block up to this many seconds for the run to settle again (default 0).' },
|
|
1147
|
+
},
|
|
1148
|
+
required: ['run_id', 'answer'],
|
|
1149
|
+
async execute(args = {}, exec) {
|
|
1150
|
+
const check = requireAgent(exec)
|
|
1151
|
+
if (check.error) return check.error
|
|
1152
|
+
try {
|
|
1153
|
+
await ready
|
|
1154
|
+
if (stateError) return describeError(stateError)
|
|
1155
|
+
const result = await orchestrator.answer(
|
|
1156
|
+
String(args.run_id ?? '').trim(),
|
|
1157
|
+
args.attention_id,
|
|
1158
|
+
args.answer,
|
|
1159
|
+
check.agent,
|
|
1160
|
+
exec.clientTimeZone,
|
|
1161
|
+
)
|
|
1162
|
+
let head
|
|
1163
|
+
if (result.resumed) {
|
|
1164
|
+
head = `answered ${result.attentionId} on run ${result.run.id}; the run was reopened and is ${result.run.status} `
|
|
1165
|
+
+ `again — it applies the answer at ${result.effect.detail}`
|
|
1166
|
+
} else if (result.reason) {
|
|
1167
|
+
head = `answered ${result.attentionId} on run ${result.run.id}, but the run was not restarted: ${result.reason}. `
|
|
1168
|
+
+ 'The answer is saved; call superagent_resume when you want it applied.'
|
|
1169
|
+
} else {
|
|
1170
|
+
head = `answered ${result.attentionId} on run ${result.run.id}; it takes effect at ${result.effect.detail}`
|
|
1171
|
+
}
|
|
1172
|
+
const waitSeconds = Number(args.wait_seconds) || 0
|
|
1173
|
+
const current = result.resumed && waitSeconds > 0
|
|
1174
|
+
? await orchestrator.status(result.run.id, waitSeconds)
|
|
1175
|
+
: result.run
|
|
1176
|
+
return `${head}.\n\n${formatRun(current)}`
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
return describeError(error)
|
|
1179
|
+
}
|
|
1180
|
+
},
|
|
1181
|
+
}))
|
|
1182
|
+
|
|
1183
|
+
ctx.tools.register(defineTool({
|
|
1184
|
+
name: 'superagent_memory',
|
|
1185
|
+
description:
|
|
1186
|
+
'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
|
|
1187
|
+
+ 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
|
|
1188
|
+
properties: {
|
|
1189
|
+
action: {
|
|
1190
|
+
type: 'string',
|
|
1191
|
+
enum: ['list', 'search', 'set', 'forget'],
|
|
1192
|
+
description: 'List notes, search them by keyword or tag, set (add or correct) one, or forget one.',
|
|
1193
|
+
},
|
|
1194
|
+
key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
|
|
1195
|
+
kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
|
|
1196
|
+
text: { type: 'string', description: 'The durable fact to record (set only).' },
|
|
1197
|
+
query: {
|
|
1198
|
+
type: 'string',
|
|
1199
|
+
description: 'Keywords to rank notes by (search only). The goal of the current task works well.',
|
|
1200
|
+
},
|
|
1201
|
+
tags: {
|
|
1202
|
+
type: 'array',
|
|
1203
|
+
items: { type: 'string' },
|
|
1204
|
+
description: 'Topic labels to match exactly (search) or to attach to a note (set).',
|
|
1205
|
+
},
|
|
1206
|
+
scope: {
|
|
1207
|
+
type: 'string',
|
|
1208
|
+
description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
|
|
1209
|
+
+ 'or the run scope (default) that earlier runs write to.',
|
|
1210
|
+
},
|
|
1211
|
+
limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
|
|
1212
|
+
},
|
|
1213
|
+
required: ['action'],
|
|
1214
|
+
async execute(args = {}, exec) {
|
|
1215
|
+
const check = requireAgent(exec)
|
|
1216
|
+
if (check.error) return check.error
|
|
1217
|
+
if (!memory) {
|
|
1218
|
+
return describeError(
|
|
1219
|
+
'cross-run memory is disabled (memory: false, or stateDir points inside the installed package)',
|
|
1220
|
+
)
|
|
1221
|
+
}
|
|
1222
|
+
try {
|
|
1223
|
+
await ready
|
|
1224
|
+
if (stateError) return describeError(stateError)
|
|
1225
|
+
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1226
|
+
// A run writes to the configured scope; `rules` and `profile` are
|
|
1227
|
+
// curated by hand and read into every run, so the tool can address
|
|
1228
|
+
// them explicitly.
|
|
1229
|
+
const scope = args.scope === undefined || args.scope === null
|
|
1230
|
+
? cfg.memoryScope
|
|
1231
|
+
: normalizeScope(args.scope)
|
|
1232
|
+
if (action === 'list') {
|
|
1233
|
+
// Capped at 30: this output goes straight into the model context, and a
|
|
1234
|
+
// 200-row dump would cost more than the notes are worth.
|
|
1235
|
+
const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
|
|
1236
|
+
const result = await memory.list({ scope, limit, maxAgeDays: cfg.memoryMaxAgeDays })
|
|
1237
|
+
if (result.total === 0) return `no notes recorded in scope "${scope}" (${result.path})`
|
|
1238
|
+
const rows = result.entries.map(entry => `- ${entry.key} [${entry.kind}] ${entry.text}`)
|
|
1239
|
+
const notes = result.bad ? `\n\n${result.bad} unreadable line(s) skipped` : ''
|
|
1240
|
+
return `${result.total} note(s) in scope "${scope}" (${result.path})\n\n${rows.join('\n')}${notes}`
|
|
1241
|
+
}
|
|
1242
|
+
if (action === 'search') {
|
|
1243
|
+
const query = String(args.query ?? '').trim()
|
|
1244
|
+
const tags = Array.isArray(args.tags) ? args.tags : []
|
|
1245
|
+
if (!query && tags.length === 0) {
|
|
1246
|
+
return describeError('search needs a query, tags, or both; call action="list" to read everything')
|
|
1247
|
+
}
|
|
1248
|
+
const limit = Math.max(1, Math.min(20, Number(args.limit) || 10))
|
|
1249
|
+
const result = await memory.recall({
|
|
1250
|
+
scope,
|
|
1251
|
+
query,
|
|
1252
|
+
tags,
|
|
1253
|
+
maxEntries: limit,
|
|
1254
|
+
maxAgeDays: cfg.memoryMaxAgeDays,
|
|
1255
|
+
})
|
|
1256
|
+
if (result.matched === 0) {
|
|
1257
|
+
return `no note in scope "${scope}" matches ${query ? `“${query}”` : 'those tags'} `
|
|
1258
|
+
+ `(${result.total} note(s) recorded; action="list" shows them all)`
|
|
1259
|
+
}
|
|
1260
|
+
// The score and its parts are printed so a ranking can be argued with
|
|
1261
|
+
// instead of taken on faith.
|
|
1262
|
+
const rows = result.entries.map(entry => {
|
|
1263
|
+
const run = entry.source.runId ?? 'manual'
|
|
1264
|
+
return `- ${entry.key} [${entry.kind}] score ${entry.score.toFixed(2)} `
|
|
1265
|
+
+ `(keyword ${entry.keyword.toFixed(2)}, tag ${entry.tag.toFixed(2)}) `
|
|
1266
|
+
+ `from run ${run}, ${String(entry.source.ts ?? '').slice(0, 10)}: ${entry.text}`
|
|
1267
|
+
})
|
|
1268
|
+
return `${result.matched} of ${result.total} note(s) in scope "${scope}" match, best first\n\n${rows.join('\n')}`
|
|
1269
|
+
}
|
|
1270
|
+
if (action === 'forget') {
|
|
1271
|
+
const key = String(args.key ?? '').trim()
|
|
1272
|
+
if (!key) return describeError('forget needs the key of the note to retract; call action="list" first')
|
|
1273
|
+
const result = await memory.forget({ scope, key })
|
|
1274
|
+
return result.forgotten
|
|
1275
|
+
? `retracted "${key}" in scope "${scope}"; later runs will not see it`
|
|
1276
|
+
: describeError(result.reason ?? 'cannot retract that note')
|
|
1277
|
+
}
|
|
1278
|
+
if (action === 'set') {
|
|
1279
|
+
const key = String(args.key ?? '').trim()
|
|
1280
|
+
const text = String(args.text ?? '').trim()
|
|
1281
|
+
if (!key || !text) return describeError('set needs both key and text')
|
|
1282
|
+
const result = await memory.set({ scope, key, kind: args.kind, text, tags: args.tags })
|
|
1283
|
+
return result.written > 0
|
|
1284
|
+
? `recorded "${key}" in scope "${scope}"; later runs will see it`
|
|
1285
|
+
: describeError(result.reason ?? 'cannot record that note')
|
|
1286
|
+
}
|
|
1287
|
+
return describeError(`unknown action "${args.action}"; use list, search, set, or forget`)
|
|
1288
|
+
} catch (error) {
|
|
1289
|
+
return describeError(error)
|
|
1290
|
+
}
|
|
1291
|
+
},
|
|
1292
|
+
}))
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* A template failure already names the concrete problem (which parameters
|
|
1296
|
+
* are missing, which field is not allowed), so it gets its own hint instead
|
|
1297
|
+
* of the generic "this came from the host" text.
|
|
1298
|
+
*/
|
|
1299
|
+
function templateProblem(error) {
|
|
1300
|
+
const hints = {
|
|
1301
|
+
'missing-parameters': 'pass every declared parameter in params={...}; a template never guesses a default, '
|
|
1302
|
+
+ 'and action="show" lists each parameter with what it should contain',
|
|
1303
|
+
'unknown-parameters': 'remove the parameters the template does not declare, or declare them in a custom '
|
|
1304
|
+
+ 'template saved with action="save"',
|
|
1305
|
+
'builtin-template': 'built-in templates are read-only; save your version under a new id',
|
|
1306
|
+
'unknown-template': 'call action="list" to see the available template ids',
|
|
1307
|
+
}
|
|
1308
|
+
const hint = hints[error.code]
|
|
1309
|
+
?? 'call action="show" on a built-in template to see the accepted fields, then save the corrected definition'
|
|
1310
|
+
return [`[error] ${error.message}`, `hint: ${hint}`].join('\n')
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
ctx.tools.register(defineTool({
|
|
1314
|
+
name: 'superagent_template',
|
|
1315
|
+
description:
|
|
1316
|
+
'List, show, expand, save, or delete a workflow template: a fixed goal skeleton with required parameters, '
|
|
1317
|
+
+ 'the situations it fits, and when it is the wrong tool. Expanding returns one normal goal string, which '
|
|
1318
|
+
+ 'superagent_start plans exactly like a goal typed by the user. A template cannot set limits, budgets, a '
|
|
1319
|
+
+ 'mode, or an override, so using one never widens what a run may do.',
|
|
1320
|
+
properties: {
|
|
1321
|
+
action: {
|
|
1322
|
+
type: 'string',
|
|
1323
|
+
enum: ['list', 'show', 'expand', 'save', 'delete'],
|
|
1324
|
+
description: 'List templates, show one in full, expand one into a goal, save a custom one, or delete a custom one.',
|
|
1325
|
+
},
|
|
1326
|
+
id: { type: 'string', description: 'Template id from action="list". Built-in ids are read-only.' },
|
|
1327
|
+
params: {
|
|
1328
|
+
type: 'object',
|
|
1329
|
+
description: 'Values for the placeholders (expand only). Every declared parameter is required; a missing or '
|
|
1330
|
+
+ 'empty value is refused with its name instead of being given a default.',
|
|
1331
|
+
additionalProperties: { type: 'string' },
|
|
1332
|
+
},
|
|
1333
|
+
template: {
|
|
1334
|
+
type: 'object',
|
|
1335
|
+
description: 'Complete definition (save only): id, title, whenToUse, whenNotToUse (list of strings), '
|
|
1336
|
+
+ 'variables (list of {name, description}), and skeleton with {{name}} placeholders. Unknown fields are '
|
|
1337
|
+
+ 'refused so a template cannot carry limits or overrides.',
|
|
1338
|
+
},
|
|
1339
|
+
limit: { type: 'number', description: 'Maximum templates to list (default 50).' },
|
|
1340
|
+
},
|
|
1341
|
+
required: ['action'],
|
|
1342
|
+
async execute(args = {}, exec) {
|
|
1343
|
+
const check = requireAgent(exec)
|
|
1344
|
+
if (check.error) return check.error
|
|
1345
|
+
try {
|
|
1346
|
+
await ready
|
|
1347
|
+
if (stateError) return describeError(stateError)
|
|
1348
|
+
const action = String(args.action ?? '').trim().toLowerCase()
|
|
1349
|
+
if (action === 'list') {
|
|
1350
|
+
const result = await templates.list()
|
|
1351
|
+
return formatTemplateList(result, Math.max(1, Math.min(100, Number(args.limit) || 50)))
|
|
1352
|
+
}
|
|
1353
|
+
if ((action === 'save' || action === 'delete') && memoryBlocked) {
|
|
1354
|
+
return describeError(
|
|
1355
|
+
`cannot ${action} a template: stateDir ${store.root} is inside the installed package, so writing there `
|
|
1356
|
+
+ 'would modify the shipped files; point stateDir elsewhere',
|
|
1357
|
+
)
|
|
1358
|
+
}
|
|
1359
|
+
if (action === 'show' || action === 'expand') {
|
|
1360
|
+
const id = String(args.id ?? '').trim()
|
|
1361
|
+
if (!id) return describeError(`${action} needs the id of a template; call action="list" first`)
|
|
1362
|
+
const template = await templates.get(id)
|
|
1363
|
+
if (!template) {
|
|
1364
|
+
return describeError(`no workflow template with id "${id}"; call action="list" to see the ids`)
|
|
1365
|
+
}
|
|
1366
|
+
if (action === 'show') return formatTemplateDetail(template)
|
|
1367
|
+
const expanded = expandTemplate(template, args.params)
|
|
1368
|
+
return [
|
|
1369
|
+
`expanded template "${expanded.templateId}" into one goal of ${expanded.goal.length} characters. `
|
|
1370
|
+
+ 'Start it with superagent_start goal=<the text below>; the planner sees the same goal it would '
|
|
1371
|
+
+ 'have seen if you had typed it.',
|
|
1372
|
+
'',
|
|
1373
|
+
expanded.goal,
|
|
1374
|
+
].join('\n')
|
|
1375
|
+
}
|
|
1376
|
+
if (action === 'save') {
|
|
1377
|
+
if (!args.template || typeof args.template !== 'object') {
|
|
1378
|
+
return describeError(
|
|
1379
|
+
'save needs template: the full definition (id, title, whenToUse, whenNotToUse, variables, skeleton)',
|
|
1380
|
+
)
|
|
1381
|
+
}
|
|
1382
|
+
const saved = await templates.save(args.template)
|
|
1383
|
+
return `saved template "${saved.id}"${saved.replaced ? ' (replaced the earlier version)' : ''} at ${saved.path}`
|
|
1384
|
+
}
|
|
1385
|
+
if (action === 'delete') {
|
|
1386
|
+
const id = String(args.id ?? '').trim()
|
|
1387
|
+
if (!id) return describeError('delete needs the id of a custom template; call action="list" first')
|
|
1388
|
+
const result = await templates.remove(id)
|
|
1389
|
+
return result.removed
|
|
1390
|
+
? `deleted custom template "${result.id}"; built-in templates are unaffected`
|
|
1391
|
+
: describeError(`no custom template with id "${result.id}" to delete; built-in templates cannot be deleted`)
|
|
1392
|
+
}
|
|
1393
|
+
return describeError(`unknown action "${args.action}"; use list, show, expand, save, or delete`)
|
|
1394
|
+
} catch (error) {
|
|
1395
|
+
if (error instanceof TemplateError) return templateProblem(error)
|
|
1396
|
+
return describeError(error)
|
|
1397
|
+
}
|
|
1398
|
+
},
|
|
1399
|
+
}))
|
|
1400
|
+
|
|
1401
|
+
// The embedding surface is opt-in: mounting the plugin must not open a port
|
|
1402
|
+
// unasked. When it is on, every request goes through the same orchestrator as
|
|
1403
|
+
// the tools, so quota, budgets, ownership, and cancel behave identically.
|
|
1404
|
+
if (cfg.controlPort !== null) {
|
|
1405
|
+
const clampControlWait = value => {
|
|
1406
|
+
const seconds = Number(value)
|
|
1407
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return 0
|
|
1408
|
+
return Math.min(300, Math.trunc(seconds))
|
|
1409
|
+
}
|
|
1410
|
+
const control = createControlPlane({
|
|
1411
|
+
port: cfg.controlPort,
|
|
1412
|
+
stateRoot: store.root,
|
|
1413
|
+
version: pkg.version,
|
|
1414
|
+
log,
|
|
1415
|
+
actions: {
|
|
1416
|
+
// Liveness only: a probe must not sweep or reclaim runs, so this
|
|
1417
|
+
// deliberately does no state-directory work. Use GET /runs to ask what
|
|
1418
|
+
// is running.
|
|
1419
|
+
async health() {
|
|
1420
|
+
return { runs: 'GET /runs' }
|
|
1421
|
+
},
|
|
1422
|
+
async list({ limit } = {}) {
|
|
1423
|
+
await ready
|
|
1424
|
+
if (stateError) throw stateError
|
|
1425
|
+
const runs = await orchestrator.list()
|
|
1426
|
+
const stats = typeof store.stats === 'function' ? await store.stats() : null
|
|
1427
|
+
const rows = Math.max(1, Math.min(100, Number(limit) || 20))
|
|
1428
|
+
const visible = runs.slice(0, rows)
|
|
1429
|
+
return {
|
|
1430
|
+
data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
|
|
1431
|
+
text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
async status(runId, waitSeconds) {
|
|
1435
|
+
await ready
|
|
1436
|
+
if (stateError) throw stateError
|
|
1437
|
+
const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
|
|
1438
|
+
return { data: { run }, text: formatRun(run) }
|
|
1439
|
+
},
|
|
1440
|
+
async start(body = {}) {
|
|
1441
|
+
await ready
|
|
1442
|
+
if (stateError) throw stateError
|
|
1443
|
+
if (!hasSubagents()) {
|
|
1444
|
+
throw new Error(
|
|
1445
|
+
'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
|
|
1446
|
+
+ 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
|
|
1447
|
+
)
|
|
1448
|
+
}
|
|
1449
|
+
const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
|
|
1450
|
+
if (!goal) {
|
|
1451
|
+
// Report the caller's mistake as written in the docs: a missing goal
|
|
1452
|
+
// is 400, not "you also did not name a session".
|
|
1453
|
+
throw new Error('goal is required; pass a concrete goal string')
|
|
1454
|
+
}
|
|
1455
|
+
const agent = resolveSession(body.session_id)
|
|
1456
|
+
const run = await orchestrator.start({
|
|
1457
|
+
goal,
|
|
1458
|
+
parentSessionId: agent.id,
|
|
1459
|
+
parent: agent,
|
|
1460
|
+
clientTimeZone: body.time_zone,
|
|
1461
|
+
allowDuplicate: body.allow_duplicate === true,
|
|
1462
|
+
mode: body.mode,
|
|
1463
|
+
queue: body.queue === true,
|
|
1464
|
+
overrides: {
|
|
1465
|
+
maxSubtasks: body.max_subtasks,
|
|
1466
|
+
maxParallel: body.max_parallel,
|
|
1467
|
+
deadlineMinutes: body.deadline_minutes,
|
|
1468
|
+
},
|
|
1469
|
+
})
|
|
1470
|
+
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1471
|
+
if (waitSeconds > 0) {
|
|
1472
|
+
const finished = await orchestrator.status(run.id, waitSeconds)
|
|
1473
|
+
const current = run.deduped ? { ...finished, deduped: true } : finished
|
|
1474
|
+
return { data: { run: current }, text: formatRun(current) }
|
|
1475
|
+
}
|
|
1476
|
+
if (run.queue?.waiting) {
|
|
1477
|
+
return {
|
|
1478
|
+
data: { run },
|
|
1479
|
+
text: `${formatRun(run, { includeReport: false })}\n\nQueued, not started: it begins automatically when `
|
|
1480
|
+
+ `an active run finishes. Poll GET /runs/${run.id} or cancel it.`,
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
return {
|
|
1484
|
+
data: { run },
|
|
1485
|
+
text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
|
|
1486
|
+
+ `GET /runs/${run.id} or call superagent_status.`,
|
|
1487
|
+
}
|
|
1488
|
+
},
|
|
1489
|
+
async cancel(runId) {
|
|
1490
|
+
await ready
|
|
1491
|
+
if (stateError) throw stateError
|
|
1492
|
+
const run = await orchestrator.cancel(String(runId ?? '').trim())
|
|
1493
|
+
const head = run.status === 'cancelled'
|
|
1494
|
+
? `cancelled ${run.id}`
|
|
1495
|
+
: run.cancelPending
|
|
1496
|
+
? `cancel requested for ${run.id}, not confirmed by the owning process yet`
|
|
1497
|
+
: `${run.id} is ${run.status}; nothing to cancel`
|
|
1498
|
+
return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
|
|
1499
|
+
},
|
|
1500
|
+
async resume(runId, body = {}) {
|
|
1501
|
+
await ready
|
|
1502
|
+
if (stateError) throw stateError
|
|
1503
|
+
if (!hasSubagents()) {
|
|
1504
|
+
throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
|
|
1505
|
+
}
|
|
1506
|
+
const agent = resolveSession(body.session_id)
|
|
1507
|
+
const run = await orchestrator.resume(
|
|
1508
|
+
String(runId ?? '').trim(),
|
|
1509
|
+
agent,
|
|
1510
|
+
body.time_zone,
|
|
1511
|
+
{ force: body.force === true || body.override_quota === true },
|
|
1512
|
+
)
|
|
1513
|
+
const waitSeconds = clampControlWait(body.wait_seconds)
|
|
1514
|
+
const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
|
|
1515
|
+
return { data: { run: current }, text: formatRun(current) }
|
|
1516
|
+
},
|
|
1517
|
+
},
|
|
1518
|
+
})
|
|
1519
|
+
let disposed = false
|
|
1520
|
+
const stopControl = () => {
|
|
1521
|
+
disposed = true
|
|
1522
|
+
return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
|
|
1523
|
+
}
|
|
1524
|
+
if (typeof ctx.effect === 'function') {
|
|
1525
|
+
ctx.effect(() => stopControl, 'dsh-superagent control plane')
|
|
1526
|
+
} else if (typeof ctx.on === 'function') {
|
|
1527
|
+
ctx.on('dispose', stopControl)
|
|
1528
|
+
}
|
|
1529
|
+
// The state directory is created by `orchestrator.recover()`, which `ready`
|
|
1530
|
+
// awaits. Starting before it exists makes the discovery write fail with
|
|
1531
|
+
// ENOENT and would leave the plane off for the whole host lifetime.
|
|
1532
|
+
ready
|
|
1533
|
+
.then(() => {
|
|
1534
|
+
if (disposed || stateError) return null
|
|
1535
|
+
return control.start()
|
|
1536
|
+
})
|
|
1537
|
+
.catch(error => {
|
|
1538
|
+
log(
|
|
1539
|
+
`control plane is not listening: ${error?.message ?? error}; `
|
|
1540
|
+
+ 'check that controlPort is free and the state directory is writable, '
|
|
1541
|
+
+ 'or remove controlPort to keep the socket closed',
|
|
1542
|
+
)
|
|
1543
|
+
})
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
log(`registered 9 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
|
|
1547
|
+
}
|