@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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/README.md +132 -194
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/cordis.patch.yml +4 -4
- package/package.json +40 -40
- package/src/assets.js +405 -348
- package/src/catalog.js +999 -605
- package/src/client.js +883 -4
- package/src/config.js +88 -88
- package/src/conversation-readers.js +198 -0
- package/src/conversation-store.js +583 -0
- package/src/export.js +273 -12
- package/src/index.js +282 -136
- package/src/native-transcript.js +217 -0
- package/src/project-archive.js +145 -145
- package/src/projects.js +1837 -980
- package/src/session-import.js +138 -93
- package/src/session-trace.js +121 -0
- package/src/skill-handoff.js +1327 -0
- package/src/skill-package.js +417 -0
- package/src/skill-provider.js +249 -0
- package/src/watch.js +319 -309
- package/web/Geist-OFL.txt +93 -93
- package/web/agent-icons/NOTICE.md +19 -19
- package/web/agent-icons/antigravity.svg +76 -76
- package/web/agent-icons/claude.svg +3 -3
- package/web/agent-icons/dsh.svg +58 -58
- package/web/agent-icons/licenses/copilot.txt +21 -21
- package/web/agent-icons/licenses/dsh.txt +21 -21
- package/web/agent-icons/licenses/gemini.txt +201 -201
- package/web/agent-icons/licenses/opencode.txt +21 -21
- package/web/agent-icons/licenses/qoder-notice.txt +18 -18
- package/web/agent-icons/licenses/qoder.txt +22 -22
- package/web/agent-icons/licenses/qwen.txt +202 -202
- package/web/agent-icons/qoder.svg +4 -4
- package/web/agent-icons/qwen.svg +5 -5
- package/web/agent-icons/workbuddy.svg +29 -29
- package/web/inline-process.css +22 -0
- package/web/markdown.js +225 -0
- package/web/panel.css +168 -151
- package/web/panel.html +82 -43
- package/web/panel.js +1316 -93
- package/web/project-context.js +25 -25
- package/web/reader.css +259 -0
- package/web/vendor/markdown-it-LICENSE.txt +156 -0
- package/web/vendor/markdown-it.mjs +3064 -0
package/src/projects.js
CHANGED
|
@@ -1,980 +1,1837 @@
|
|
|
1
|
-
import { createReadStream } from 'node:fs';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
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
|
-
const
|
|
73
|
-
return { text:
|
|
74
|
-
|
|
75
|
-
await handle.
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
db.
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
const
|
|
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
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
return undefined;
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
if (
|
|
314
|
-
const
|
|
315
|
-
if (
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
const
|
|
338
|
-
const
|
|
339
|
-
const
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
?? rows
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
return dataDirectories(root,
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
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
|
-
const
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
if (
|
|
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
|
-
if (
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
const
|
|
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
|
-
if (
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
if (
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
const
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
}
|
|
804
|
-
if (
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
function
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
const
|
|
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
|
-
for (const
|
|
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
|
-
if (!
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
const
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
if (
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { open, readdir, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import zlib from 'node:zlib';
|
|
7
|
+
import { sourceJson, sourceJsonl, sourceValueLimit } from './conversation-readers.js';
|
|
8
|
+
|
|
9
|
+
const maxMessages = 36;
|
|
10
|
+
const maxMessageLength = 4_000;
|
|
11
|
+
const maxTranscriptBytes = 12 * 1024 * 1024;
|
|
12
|
+
const maxTranscriptRowBytes = 256 * 1024;
|
|
13
|
+
const tailBufferBytes = maxTranscriptBytes + 1;
|
|
14
|
+
const transcriptHeaderBytes = 96 * 1024;
|
|
15
|
+
const codexLocations = ['sessions', 'archived_sessions'];
|
|
16
|
+
const jsonlFile = /\.jsonl$/i;
|
|
17
|
+
const compressedCodexFile = /\.jsonl\.zst$/i;
|
|
18
|
+
const hasZstd = typeof zlib.createZstdDecompress === 'function';
|
|
19
|
+
const conversationLimits = { messages: 600, characters: 160_000, messageLength: 24_000 };
|
|
20
|
+
const traceItemLimit = 600;
|
|
21
|
+
const traceTextLimit = 8_000;
|
|
22
|
+
|
|
23
|
+
const agentLabels = {
|
|
24
|
+
codex: 'Codex', claude: 'Claude Code', opencode: 'OpenCode', workbuddy: 'WorkBuddy',
|
|
25
|
+
qoder: 'Qoder', trae: 'TRAE', antigravity: 'Antigravity', gemini: 'Gemini CLI',
|
|
26
|
+
copilot: 'GitHub Copilot', qwen: 'Qwen Code',
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function configuredRoots(config, agent) {
|
|
30
|
+
const aliases = {
|
|
31
|
+
antigravity: ['antigravity-cli'], claude: ['claude-code'], codex: ['codex-cli'],
|
|
32
|
+
copilot: ['vscode', 'vscode-copilot', 'vscode-insiders', 'vscodium', 'code-oss'],
|
|
33
|
+
gemini: ['gemini-cli'], opencode: ['open-code'], qoder: ['qoder-cn'],
|
|
34
|
+
qwen: ['qwen-code'], trae: ['trae-cn', 'trae-solo'],
|
|
35
|
+
};
|
|
36
|
+
const roots = config.agentRoots ?? {};
|
|
37
|
+
const keys = [agent, ...(aliases[agent] ?? [])];
|
|
38
|
+
if (keys.some(key => Object.hasOwn(roots, key))) return keys.flatMap(key => roots[key] ?? []);
|
|
39
|
+
if (!config.home) return [];
|
|
40
|
+
const defaults = {
|
|
41
|
+
codex: ['.codex'], claude: ['.claude'], opencode: ['.local/share/opencode'],
|
|
42
|
+
qoder: ['.qoder-cn', '.qoder'], workbuddy: ['.workbuddy'],
|
|
43
|
+
trae: ['.trae-cn'],
|
|
44
|
+
antigravity: ['.gemini/antigravity', '.gemini/antigravity-cli'], gemini: ['.gemini'],
|
|
45
|
+
qwen: ['.qwen'],
|
|
46
|
+
};
|
|
47
|
+
return (defaults[agent] ?? []).map(root => path.join(config.home, root));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function pathKey(file) {
|
|
51
|
+
const normalized = path.normalize(file).replace(/^\\\\\?\\/, '');
|
|
52
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function physicalPath(file) {
|
|
56
|
+
return realpath(file).catch(() => undefined);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function inside(root, file) {
|
|
60
|
+
const relative = path.relative(pathKey(root), pathKey(file));
|
|
61
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function scopedFile(file, root) {
|
|
65
|
+
const [actual, base] = await Promise.all([physicalPath(file), physicalPath(root)]);
|
|
66
|
+
return actual && base && inside(base, actual) ? actual : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function prefix(file, bytes) {
|
|
70
|
+
const handle = await open(file, 'r');
|
|
71
|
+
try {
|
|
72
|
+
const info = await handle.stat();
|
|
73
|
+
if (!info.isFile()) return { text: '', truncated: false };
|
|
74
|
+
const buffer = Buffer.alloc(Math.min(info.size, bytes));
|
|
75
|
+
const result = await handle.read(buffer, 0, buffer.length, 0);
|
|
76
|
+
return { text: buffer.toString('utf8', 0, result.bytesRead), truncated: info.size > result.bytesRead, modified: info.mtimeMs };
|
|
77
|
+
} finally {
|
|
78
|
+
await handle.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function json(text) {
|
|
83
|
+
try { return JSON.parse(text); } catch { return undefined; }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function rowsFrom(text, truncated) {
|
|
87
|
+
const value = text.replace(/^\uFEFF/, '');
|
|
88
|
+
const end = truncated ? value.lastIndexOf('\n') + 1 : value.length;
|
|
89
|
+
return value.slice(0, end).split(/\r?\n/).map(json).filter(Boolean);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function directories(root) {
|
|
93
|
+
return readdir(root, { withFileTypes: true });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function missingStore() {
|
|
97
|
+
return Object.assign(new Error('未发现可读取的本地数据目录'), { code: 'ENOENT' });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function dataDirectories(root, relatives) {
|
|
101
|
+
const candidates = await Promise.all(relatives.map(relative => scopedFile(path.join(root, relative), root)));
|
|
102
|
+
const found = await Promise.all(candidates.filter(Boolean).map(async candidate => (await stat(candidate)).isDirectory() ? candidate : undefined));
|
|
103
|
+
return [...new Set(found.filter(Boolean))];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function yamlScalar(value) {
|
|
107
|
+
const text = value.trim();
|
|
108
|
+
if (text.startsWith('"')) return json(text) ?? '';
|
|
109
|
+
if (text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replaceAll("''", "'");
|
|
110
|
+
return text.replace(/\s+#.*$/, '');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// WorkspaceHub emits a fixed, flat schema for project metadata and its root list.
|
|
114
|
+
function projectRecord(text) {
|
|
115
|
+
const record = { roots: [], agentIDs: [] };
|
|
116
|
+
let section;
|
|
117
|
+
for (const line of text.replace(/^\uFEFF/, '').split(/\r?\n/)) {
|
|
118
|
+
const top = /^([A-Za-z][\w]*):\s*(.*)$/.exec(line);
|
|
119
|
+
if (top) {
|
|
120
|
+
section = top[1];
|
|
121
|
+
if (['id', 'name', 'canonicalPath', 'entryKind'].includes(section)) record[section] = yamlScalar(top[2]);
|
|
122
|
+
if (section === 'agentIDs' && top[2].startsWith('[') && top[2].endsWith(']')) {
|
|
123
|
+
record.agentIDs = top[2].slice(1, -1).split(',').map(yamlScalar).filter(Boolean);
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (section === 'agentIDs') {
|
|
128
|
+
const entry = /^\s*-\s+(.+)$/.exec(line);
|
|
129
|
+
if (entry) record.agentIDs.push(yamlScalar(entry[1]));
|
|
130
|
+
}
|
|
131
|
+
if (section === 'roots') {
|
|
132
|
+
const entry = /^\s*-\s+id:\s*(.*)$/.exec(line);
|
|
133
|
+
if (entry) record.roots.push({ id: yamlScalar(entry[1]) });
|
|
134
|
+
const field = /^\s+(role|path):\s*(.*)$/.exec(line);
|
|
135
|
+
if (field && record.roots.length) record.roots.at(-1)[field[1]] = yamlScalar(field[2]);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return record;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function workspaceProjects(root) {
|
|
142
|
+
const result = [];
|
|
143
|
+
const records = path.basename(root) === '项目档案' ? root : path.join(root, '项目档案');
|
|
144
|
+
for (const entry of await directories(records)) {
|
|
145
|
+
if (!entry.isDirectory() || !/^P\d{3,}$/.test(entry.name)) continue;
|
|
146
|
+
const file = await scopedFile(path.join(records, entry.name, 'project.yaml'), records);
|
|
147
|
+
if (!file) continue;
|
|
148
|
+
const { text, truncated } = await prefix(file, 256 * 1024);
|
|
149
|
+
if (truncated) continue;
|
|
150
|
+
const record = projectRecord(text);
|
|
151
|
+
if (record.id !== entry.name || typeof record.canonicalPath !== 'string' || !path.isAbsolute(record.canonicalPath)) continue;
|
|
152
|
+
const locations = [record.canonicalPath, ...record.roots.filter(item => item.role === 'auxiliary').map(item => item.path)];
|
|
153
|
+
for (const location of locations) {
|
|
154
|
+
if (!location || !path.isAbsolute(location)) continue;
|
|
155
|
+
// A file project opens its containing directory, the nearest valid DSH cwd.
|
|
156
|
+
const info = await stat(location).catch(() => undefined);
|
|
157
|
+
const cwd = info?.isFile() ? path.dirname(location) : location;
|
|
158
|
+
for (const agent of record.agentIDs.length ? record.agentIDs : ['workspacehub']) {
|
|
159
|
+
result.push({ cwd, agent, name: record.name, projectId: record.id, projectRoot: root });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function withDatabase(file, callback) {
|
|
167
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
168
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
169
|
+
try {
|
|
170
|
+
db.exec('PRAGMA trusted_schema = OFF');
|
|
171
|
+
return callback(db);
|
|
172
|
+
} finally {
|
|
173
|
+
db.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function columns(db, table) {
|
|
178
|
+
return new Set(db.prepare('SELECT name FROM pragma_table_info(?)').all(table).map(row => row.name));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function archivedProjects(file) {
|
|
182
|
+
return withDatabase(file, db => {
|
|
183
|
+
const fields = columns(db, 'sessions');
|
|
184
|
+
if (!['id', 'cwd', 'agent'].every(field => fields.has(field))) throw new Error('未识别 AgentsView 会话表');
|
|
185
|
+
const sort = fields.has('ended_at') ? 'ended_at' : 'id';
|
|
186
|
+
const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
|
|
187
|
+
const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
|
|
188
|
+
const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
|
|
189
|
+
const rows = db.prepare(`SELECT id, cwd, agent, ${sort} AS date, ${title} AS title FROM sessions WHERE cwd <> ''${deleted}${machine} ORDER BY ${sort} DESC`)
|
|
190
|
+
.iterate();
|
|
191
|
+
return Array.from(rows, ({ id, cwd, agent, date, title }) => ({ cwd, agent, archive: { kind: 'agentsview', agent, file, id, date, title } }));
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function codexProjects(root) {
|
|
196
|
+
const entries = await directories(root);
|
|
197
|
+
const states = entries.filter(entry => entry.isFile() && /^state_\d+\.sqlite$/.test(entry.name));
|
|
198
|
+
states.sort((a, b) => Number(b.name.match(/\d+/)[0]) - Number(a.name.match(/\d+/)[0]));
|
|
199
|
+
let indexed;
|
|
200
|
+
let indexError;
|
|
201
|
+
for (const entry of states) {
|
|
202
|
+
const file = await scopedFile(path.join(root, entry.name), root);
|
|
203
|
+
if (!file) continue;
|
|
204
|
+
try {
|
|
205
|
+
indexed = await withDatabase(file, db => {
|
|
206
|
+
const fields = columns(db, 'threads');
|
|
207
|
+
if (!['cwd', 'rollout_path', 'id'].every(field => fields.has(field))) return undefined;
|
|
208
|
+
const sort = fields.has('updated_at') ? 'updated_at' : 'id';
|
|
209
|
+
const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
|
|
210
|
+
return db.prepare(`SELECT id, cwd, rollout_path, ${sort} AS date, ${title} AS title FROM threads WHERE cwd <> '' ORDER BY ${sort} DESC`).all();
|
|
211
|
+
});
|
|
212
|
+
if (indexed) break;
|
|
213
|
+
} catch (error) {
|
|
214
|
+
indexError = error;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const bases = await transcriptDirectories(root, codexLocations);
|
|
218
|
+
if (!bases.length) throw indexError ?? missingStore();
|
|
219
|
+
const byFile = new Map();
|
|
220
|
+
for (let offset = 0; offset < (indexed?.length ?? 0); offset += 32) {
|
|
221
|
+
const batch = await Promise.all(indexed.slice(offset, offset + 32).map(async ({ id, cwd, rollout_path, date, title }) => {
|
|
222
|
+
const file = await resolveCodexTranscript(rollout_path, bases);
|
|
223
|
+
return file ? { cwd, agent: 'codex', archive: { kind: 'codex', file, root, id, date, title } } : undefined;
|
|
224
|
+
}));
|
|
225
|
+
for (const project of batch.filter(Boolean)) {
|
|
226
|
+
const key = pathKey(project.archive.file);
|
|
227
|
+
if (!byFile.has(key)) byFile.set(key, project);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
// SQLite can lag an active or archived transcript. Keep its titles for
|
|
231
|
+
// resolved files and discover any additional plain or compressed transcripts.
|
|
232
|
+
const byId = new Set([...byFile.values()].map(project => project.archive.id).filter(Boolean));
|
|
233
|
+
const include = file => !byFile.has(pathKey(file))
|
|
234
|
+
&& (jsonlFile.test(file) || (hasZstd && compressedCodexFile.test(file)));
|
|
235
|
+
const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include);
|
|
236
|
+
for (const project of fallback) {
|
|
237
|
+
const { file, id } = project.archive;
|
|
238
|
+
if (id && byId.has(id)) continue;
|
|
239
|
+
if (id) byId.add(id);
|
|
240
|
+
byFile.set(pathKey(file), project);
|
|
241
|
+
}
|
|
242
|
+
return [...byFile.values()];
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function resolveCodexTranscript(file, bases) {
|
|
246
|
+
if (typeof file !== 'string' || !path.isAbsolute(file)) return undefined;
|
|
247
|
+
const candidates = compressedCodexFile.test(file) ? [file, file.slice(0, -4)]
|
|
248
|
+
: jsonlFile.test(file) ? [file, file + '.zst'] : [];
|
|
249
|
+
for (const candidate of candidates) {
|
|
250
|
+
const actual = await physicalPath(candidate);
|
|
251
|
+
if (!actual || !bases.some(base => inside(base, actual))
|
|
252
|
+
|| !(jsonlFile.test(actual) || hasZstd && compressedCodexFile.test(actual))) continue;
|
|
253
|
+
if ((await stat(actual).catch(() => undefined))?.isFile()) return actual;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function opencodeTables(db) {
|
|
258
|
+
return ['session_v2', 'session'].filter(table => {
|
|
259
|
+
const fields = columns(db, table);
|
|
260
|
+
return ['id', 'directory', 'time_updated'].every(field => fields.has(field));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function opencodeProjects(root) {
|
|
265
|
+
const file = await opencodeDatabase(root);
|
|
266
|
+
if (!file) throw missingStore();
|
|
267
|
+
return withDatabase(file, db => {
|
|
268
|
+
const tables = opencodeTables(db);
|
|
269
|
+
if (!tables.length) throw new Error('未识别 OpenCode 会话表');
|
|
270
|
+
const projects = tables.flatMap(table => {
|
|
271
|
+
const title = columns(db, table).has('title') ? 'substr(title, 1, 200)' : 'NULL';
|
|
272
|
+
const rows = db.prepare(`SELECT id, directory AS cwd, time_updated AS date, ${title} AS title FROM ${table} WHERE directory <> '' ORDER BY time_updated DESC`).iterate();
|
|
273
|
+
return Array.from(rows, ({ id, cwd, date, title }) => ({ cwd, agent: 'opencode', archive: { kind: 'opencode', file, id, table, date, title } }));
|
|
274
|
+
});
|
|
275
|
+
const fields = columns(db, 'project');
|
|
276
|
+
if (fields.has('worktree')) {
|
|
277
|
+
const name = fields.has('name') ? 'name' : 'NULL';
|
|
278
|
+
for (const row of db.prepare(`SELECT worktree AS cwd, ${name} AS name FROM project WHERE worktree <> ''`).iterate()) {
|
|
279
|
+
projects.push({ ...row, agent: 'opencode' });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return projects;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function opencodeDatabase(root) {
|
|
287
|
+
const info = await stat(root).catch(() => undefined);
|
|
288
|
+
if (info?.isFile()) return physicalPath(root);
|
|
289
|
+
if (!info?.isDirectory()) return undefined;
|
|
290
|
+
for (const relative of ['opencode.db', 'opencode/opencode.db']) {
|
|
291
|
+
const candidate = await scopedFile(path.join(root, relative), root);
|
|
292
|
+
if (candidate && (await stat(candidate)).isFile()) return candidate;
|
|
293
|
+
}
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function* transcriptFiles(root, depth, predicate) {
|
|
298
|
+
const stack = [{ root, depth }];
|
|
299
|
+
while (stack.length) {
|
|
300
|
+
const current = stack.pop();
|
|
301
|
+
const entries = await directories(current.root).catch(() => []);
|
|
302
|
+
for (const entry of entries) {
|
|
303
|
+
const file = path.join(current.root, entry.name);
|
|
304
|
+
if (entry.isFile() && predicate(entry.name, file)) yield file;
|
|
305
|
+
if (entry.isDirectory() && current.depth > 0 && entry.name !== 'subagents') {
|
|
306
|
+
stack.push({ root: file, depth: current.depth - 1 });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function nativeCwd(file, agent, rows) {
|
|
313
|
+
if (agent === 'codex') return rows.find(row => row.type === 'session_meta')?.payload?.cwd;
|
|
314
|
+
const cwd = rows.find(row => typeof row.cwd === 'string' && path.isAbsolute(row.cwd))?.cwd;
|
|
315
|
+
if (cwd || agent !== 'qoder') return cwd;
|
|
316
|
+
const sidecar = await scopedFile(file.replace(/\.jsonl$/i, '-session.json'), path.dirname(file));
|
|
317
|
+
if (!sidecar) return undefined;
|
|
318
|
+
const { text, truncated } = await prefix(sidecar, 128 * 1024);
|
|
319
|
+
const metadata = truncated ? undefined : json(text);
|
|
320
|
+
return metadata?.working_dir ?? metadata?.workingDir ?? metadata?.cwd;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function jsonlProjects(root, agent, children = ['projects'], depth = 1) {
|
|
324
|
+
const roots = await transcriptDirectories(root, children);
|
|
325
|
+
if (!roots.length) throw missingStore();
|
|
326
|
+
return scanJsonlProjects(root, agent, roots, depth, file => jsonlFile.test(file));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function scanJsonlProjects(root, agent, roots, depth, include) {
|
|
330
|
+
const result = [];
|
|
331
|
+
const batch = [];
|
|
332
|
+
async function flush() {
|
|
333
|
+
const rows = await Promise.all(batch.splice(0).map(async file => {
|
|
334
|
+
try {
|
|
335
|
+
const compressed = agent === 'codex' && compressedCodexFile.test(file);
|
|
336
|
+
const { text, truncated, modified } = compressed ? await compressedPrefix(file) : await prefix(file, transcriptHeaderBytes);
|
|
337
|
+
const rows = rowsFrom(text, truncated);
|
|
338
|
+
const cwd = await nativeCwd(file, agent, rows);
|
|
339
|
+
const id = agent === 'codex' ? rows.find(row => row.type === 'session_meta')?.payload?.id : undefined;
|
|
340
|
+
const title = rows.findLast(row => row.type === 'custom-title' && typeof row.customTitle === 'string')?.customTitle
|
|
341
|
+
?? rows.findLast(row => row.type === 'summary' && typeof row.summary === 'string')?.summary
|
|
342
|
+
?? firstQuestion(rows, agent);
|
|
343
|
+
return cwd ? { cwd, agent, archive: { kind: agent, file, root, id, date: modified, title: title?.slice(0, 200) } } : undefined;
|
|
344
|
+
} catch { return undefined; }
|
|
345
|
+
}));
|
|
346
|
+
result.push(...rows.filter(Boolean));
|
|
347
|
+
}
|
|
348
|
+
for (const target of roots) {
|
|
349
|
+
for await (const file of transcriptFiles(target, depth, (_name, candidate) => include(candidate))) {
|
|
350
|
+
batch.push(file);
|
|
351
|
+
if (batch.length === 32) await flush();
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (batch.length) await flush();
|
|
355
|
+
return result;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function transcriptDirectories(root, children) {
|
|
359
|
+
return dataDirectories(root, children.includes(path.basename(root).toLowerCase()) ? [''] : children);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function editorStores(root) {
|
|
363
|
+
const relatives = path.basename(root).toLowerCase() === 'workspacestorage'
|
|
364
|
+
? [''] : ['workspaceStorage', 'User/workspaceStorage'];
|
|
365
|
+
return dataDirectories(root, relatives);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function copilotDatabase(root) {
|
|
369
|
+
const actual = await physicalPath(root);
|
|
370
|
+
if (!actual) return undefined;
|
|
371
|
+
if (path.basename(actual).toLowerCase() === 'session-store.db' && (await stat(actual)).isFile()) return actual;
|
|
372
|
+
for (const prefix of ['', 'User']) {
|
|
373
|
+
const file = await scopedFile(path.join(actual, prefix, 'globalStorage', 'github.copilot-chat', 'session-store.db'), actual);
|
|
374
|
+
if (file && (await stat(file)).isFile()) return file;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function copilotTables(db) {
|
|
379
|
+
const sessions = columns(db, 'sessions');
|
|
380
|
+
const turns = columns(db, 'turns');
|
|
381
|
+
return ['id', 'cwd'].every(field => sessions.has(field))
|
|
382
|
+
&& ['id', 'session_id', 'turn_index', 'user_message', 'assistant_response', 'timestamp'].every(field => turns.has(field));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function copilotHostFilter(fields) {
|
|
386
|
+
return fields.has('host_type') ? " AND host_type = 'vscode'" : '';
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function copilotDbProjects(file, root) {
|
|
390
|
+
return withDatabase(file, db => {
|
|
391
|
+
if (!copilotTables(db)) throw new Error('Unrecognized Copilot session store');
|
|
392
|
+
const fields = columns(db, 'sessions');
|
|
393
|
+
const title = fields.has('summary') ? 'substr(summary, 1, 200)' : 'NULL';
|
|
394
|
+
const date = fields.has('updated_at') ? 'updated_at' : 'NULL';
|
|
395
|
+
const rows = db.prepare(`SELECT id, cwd, ${title} AS title, ${date} AS date FROM sessions WHERE cwd <> ''${copilotHostFilter(fields)} ORDER BY date DESC, id`)
|
|
396
|
+
.iterate();
|
|
397
|
+
return Array.from(rows, row => ({
|
|
398
|
+
cwd: localDirectory(row.cwd), agent: 'copilot',
|
|
399
|
+
archive: { kind: 'copilot', storage: 'sqlite', file, root, id: row.id, title: row.title, date: row.date },
|
|
400
|
+
}));
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async function editorProjects(root, agent) {
|
|
405
|
+
const stores = await editorStores(root);
|
|
406
|
+
const database = agent === 'copilot' ? await copilotDatabase(root) : undefined;
|
|
407
|
+
if (!stores.length && !database) throw missingStore();
|
|
408
|
+
const result = [];
|
|
409
|
+
for (const store of stores) {
|
|
410
|
+
for await (const file of transcriptFiles(store, 1, name => name === 'workspace.json')) {
|
|
411
|
+
try {
|
|
412
|
+
const { text } = await prefix(file, 32 * 1024);
|
|
413
|
+
const value = json(text);
|
|
414
|
+
const cwd = localDirectory(value?.folder);
|
|
415
|
+
if (!cwd) continue;
|
|
416
|
+
result.push({ cwd, agent });
|
|
417
|
+
if (agent !== 'copilot') continue;
|
|
418
|
+
for await (const session of transcriptFiles(path.join(path.dirname(file), 'chatSessions'), 0, name => /\.jsonl?$/i.test(name))) {
|
|
419
|
+
const info = await stat(session).catch(() => undefined);
|
|
420
|
+
if (info) result.push({ cwd, agent, archive: { kind: 'copilot', file: session, root, date: info.mtimeMs } });
|
|
421
|
+
}
|
|
422
|
+
} catch { continue; }
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (database) {
|
|
426
|
+
try { for (const project of await copilotDbProjects(database, root)) result.push(project); }
|
|
427
|
+
catch (error) { if (!result.length) throw error; }
|
|
428
|
+
}
|
|
429
|
+
return result;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function geminiProjects(root) {
|
|
433
|
+
const [base] = await transcriptDirectories(root, ['tmp']);
|
|
434
|
+
if (!base) throw missingStore();
|
|
435
|
+
const result = [];
|
|
436
|
+
for await (const file of transcriptFiles(base, 1, name => name === '.project_root')) {
|
|
437
|
+
const { text } = await prefix(file, 32 * 1024);
|
|
438
|
+
const cwd = text.trim();
|
|
439
|
+
result.push({ cwd, agent: 'gemini' });
|
|
440
|
+
for await (const session of transcriptFiles(path.join(path.dirname(file), 'chats'), 0, name => /^session-.+\.jsonl?$/i.test(name))) {
|
|
441
|
+
const info = await stat(session).catch(() => undefined);
|
|
442
|
+
if (info) result.push({ cwd, agent: 'gemini', archive: { kind: 'gemini', file: session, root, date: info.mtimeMs } });
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return result;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function localDirectory(value) {
|
|
449
|
+
if (typeof value !== 'string') return undefined;
|
|
450
|
+
if (path.isAbsolute(value)) return value;
|
|
451
|
+
if (!value.startsWith('file:')) return undefined;
|
|
452
|
+
try { return fileURLToPath(value); } catch { return undefined; }
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function antigravityProjects(root) {
|
|
456
|
+
await directories(root);
|
|
457
|
+
const projects = [];
|
|
458
|
+
const database = await scopedFile(path.join(root, 'conversation_summaries.db'), root);
|
|
459
|
+
const file = await scopedFile(path.join(root, 'history.jsonl'), root);
|
|
460
|
+
if (!database && !file) throw missingStore();
|
|
461
|
+
if (database) {
|
|
462
|
+
const rows = await withDatabase(database, db => {
|
|
463
|
+
const fields = columns(db, 'conversation_summaries');
|
|
464
|
+
if (!fields.has('workspace_uris')) return [];
|
|
465
|
+
return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]')").all();
|
|
466
|
+
});
|
|
467
|
+
for (const row of rows) {
|
|
468
|
+
const uris = json(row.workspace_uris);
|
|
469
|
+
if (!Array.isArray(uris)) continue;
|
|
470
|
+
for (const uri of uris) {
|
|
471
|
+
const cwd = localDirectory(uri);
|
|
472
|
+
if (cwd) projects.push({ cwd, agent: 'antigravity' });
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (file) {
|
|
477
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
478
|
+
for (const row of rowsFrom(text, truncated)) {
|
|
479
|
+
const cwd = localDirectory(row.workspace);
|
|
480
|
+
if (cwd && typeof row.conversationId === 'string') {
|
|
481
|
+
projects.push({ cwd, agent: 'antigravity', archive: { kind: 'antigravity', file, root, id: row.conversationId, date: row.timestamp } });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return projects;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export async function scanProjects(config) {
|
|
489
|
+
const projects = [];
|
|
490
|
+
const sources = [];
|
|
491
|
+
const discovered = new Map();
|
|
492
|
+
async function scan(id, label, paths, load, partial) {
|
|
493
|
+
let errors = 0;
|
|
494
|
+
const checks = await Promise.all(paths.map(async value => {
|
|
495
|
+
try { return await realpath(value); } catch (error) {
|
|
496
|
+
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') errors++;
|
|
497
|
+
return undefined;
|
|
498
|
+
}
|
|
499
|
+
}));
|
|
500
|
+
const candidates = [...new Set(checks.filter(Boolean))];
|
|
501
|
+
let succeeded = 0;
|
|
502
|
+
let found = 0;
|
|
503
|
+
for (const file of candidates) {
|
|
504
|
+
try {
|
|
505
|
+
const rows = await load(file);
|
|
506
|
+
for (const row of rows) projects.push(row);
|
|
507
|
+
found += rows.length;
|
|
508
|
+
succeeded++;
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (error.code !== 'ENOENT') errors++;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const status = succeeded ? (errors || partial ? 'partial' : 'ready') : errors ? 'error' : candidates.length ? 'partial' : 'unavailable';
|
|
514
|
+
const detail = succeeded ? `${found} 条项目来源记录${partial ? ` · ${partial}` : ''}${errors ? ' · 部分来源读取失败' : ''}`
|
|
515
|
+
: errors ? '本地来源无法读取或格式无法识别' : candidates.length ? '已找到数据目录,尚无可读取的项目来源' : undefined;
|
|
516
|
+
sources.push({ id, label, status, detail });
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
await Promise.all([
|
|
520
|
+
scan('workspacehub', 'Agent Workspace Manager', config.workspaceHubRoots ?? [], workspaceProjects),
|
|
521
|
+
scan('agentsview', 'AgentsView 会话归档', config.archiveFiles ?? [], archivedProjects),
|
|
522
|
+
...Object.entries({
|
|
523
|
+
codex: codexProjects, claude: root => jsonlProjects(root, 'claude'),
|
|
524
|
+
opencode: opencodeProjects, workbuddy: root => jsonlProjects(root, 'workbuddy'),
|
|
525
|
+
qoder: root => jsonlProjects(root, 'qoder'), qwen: root => jsonlProjects(root, 'qwen', ['projects'], 2),
|
|
526
|
+
trae: root => editorProjects(root, 'trae'), copilot: root => editorProjects(root, 'copilot'),
|
|
527
|
+
gemini: geminiProjects,
|
|
528
|
+
antigravity: antigravityProjects,
|
|
529
|
+
}).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
|
|
530
|
+
trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
|
|
531
|
+
copilot: '支持 VS Code 工作区会话及本机会话库;其他版本可从 AgentsView 读取已归档部分',
|
|
532
|
+
antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
|
|
533
|
+
}[agent])),
|
|
534
|
+
]);
|
|
535
|
+
|
|
536
|
+
for (const cwd of config.projectRoots ?? []) projects.push({ cwd, agent: 'manual' });
|
|
537
|
+
const canonical = new Map();
|
|
538
|
+
for (const project of projects) {
|
|
539
|
+
if (typeof project.cwd !== 'string' || !path.isAbsolute(project.cwd) || project.cwd === path.parse(project.cwd).root) continue;
|
|
540
|
+
const key = pathKey(project.cwd);
|
|
541
|
+
if (!canonical.has(key)) canonical.set(key, await physicalPath(project.cwd) ?? path.normalize(project.cwd));
|
|
542
|
+
project.cwd = canonical.get(key);
|
|
543
|
+
const timestamp = dateMillis(project.archive?.date);
|
|
544
|
+
if (timestamp > 0 && timestamp < 8_640_000_000_000_000) project.updatedAt = new Date(timestamp).toISOString();
|
|
545
|
+
const identity = JSON.stringify([pathKey(project.cwd), project.agent, project.projectId, project.archive?.kind, project.archive?.file, project.archive?.id]);
|
|
546
|
+
const previous = discovered.get(identity);
|
|
547
|
+
if (!previous || compareDate(project.archive?.date, previous.archive?.date) > 0) discovered.set(identity, project);
|
|
548
|
+
}
|
|
549
|
+
return { projects: [...discovered.values()], sources: sources.sort((a, b) => a.id.localeCompare(b.id)) };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
export function dateMillis(value) {
|
|
553
|
+
if (typeof value === 'string') return Date.parse(value) || 0;
|
|
554
|
+
if (!Number.isFinite(value) || value <= 0 || value > 8_640_000_000_000_000) return 0;
|
|
555
|
+
return Math.trunc(value < 10_000_000_000 ? value * 1_000 : value);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function compareDate(a, b) {
|
|
559
|
+
return dateMillis(a) - dateMillis(b);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function sameDirectory(cwd, expected) {
|
|
563
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
|
|
564
|
+
const actual = await physicalPath(cwd);
|
|
565
|
+
return pathKey(actual ?? cwd) === pathKey(expected);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function stripRuntimeWrapper(text) {
|
|
569
|
+
let value = text.trimStart();
|
|
570
|
+
let stripped = false;
|
|
571
|
+
while (value.startsWith('<') || value.startsWith('#')) {
|
|
572
|
+
const wrapper = /^<(environment_context|permissions instructions|collaboration_mode|system-reminder|developer_instructions|user_instructions|app-context|subagent_notification)(?=[>\s])[^>]*(?:>|$)/i.exec(value);
|
|
573
|
+
const instructions = wrapper ? undefined : /^# AGENTS\.md instructions for [\s\S]*?\n<INSTRUCTIONS>/i.exec(value);
|
|
574
|
+
if (!wrapper && !instructions) break;
|
|
575
|
+
const closing = `</${wrapper?.[1].toLowerCase() ?? 'instructions'}>`;
|
|
576
|
+
const end = value.toLowerCase().indexOf(closing, (wrapper ?? instructions)[0].length);
|
|
577
|
+
if (end === -1) return '';
|
|
578
|
+
value = value.slice(end + closing.length).trimStart();
|
|
579
|
+
stripped = true;
|
|
580
|
+
}
|
|
581
|
+
return stripped ? value : text;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function messageText(text) {
|
|
585
|
+
return typeof text === 'string' ? stripRuntimeWrapper(text).trim() : '';
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function markSourcePartial(result, reason = 'source-compacted') {
|
|
589
|
+
result.events?.push({ kind: 'gap', reason });
|
|
590
|
+
result.sourcePartial = true;
|
|
591
|
+
result.truncated = true;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function appendMessage(result, role, text, timestamp, { estimatedTime = false } = {}) {
|
|
595
|
+
if (role !== 'user' && role !== 'assistant') return false;
|
|
596
|
+
const value = messageText(text);
|
|
597
|
+
if (!value) return false;
|
|
598
|
+
for (const match of value.matchAll(/<skill>\s*<name>([^<]+)<\/name>/gi)) addSkill(result, match[1]);
|
|
599
|
+
if (value.startsWith('<skill>')) return false;
|
|
600
|
+
if (result.events) {
|
|
601
|
+
if (role === 'user') result.turn++;
|
|
602
|
+
const time = dateMillis(timestamp);
|
|
603
|
+
result.events.push({
|
|
604
|
+
kind: 'message', role, text: stripRuntimeWrapper(text), turn: result.turn,
|
|
605
|
+
...(time > 0 && !estimatedTime ? { time } : {}),
|
|
606
|
+
...(result.sourceId ? { sourceId: result.sourceId } : {}),
|
|
607
|
+
...(result.parentId ? { parentId: result.parentId } : {}),
|
|
608
|
+
});
|
|
609
|
+
return true;
|
|
610
|
+
}
|
|
611
|
+
const { limits } = result;
|
|
612
|
+
if (limits) {
|
|
613
|
+
const bounded = value.slice(0, limits.messageLength).replace(/[\uD800-\uDBFF]$/, '');
|
|
614
|
+
const time = dateMillis(timestamp);
|
|
615
|
+
const stats = result.readStats;
|
|
616
|
+
if (role === 'user') stats.userMessages++;
|
|
617
|
+
else stats.assistantMessages++;
|
|
618
|
+
if (time > 0 && !estimatedTime) {
|
|
619
|
+
stats.timedMessages++;
|
|
620
|
+
stats.firstAt = Math.min(stats.firstAt ?? time, time);
|
|
621
|
+
stats.lastAt = Math.max(stats.lastAt ?? time, time);
|
|
622
|
+
}
|
|
623
|
+
const entry = { role, text: bounded, agent: result.agent, time };
|
|
624
|
+
if (result.trace) {
|
|
625
|
+
const ref = ++result.messageSeq;
|
|
626
|
+
if (role === 'user') {
|
|
627
|
+
result.turn++;
|
|
628
|
+
result.turnRef = ref;
|
|
629
|
+
}
|
|
630
|
+
entry.turnRef = result.turnRef;
|
|
631
|
+
}
|
|
632
|
+
result.messages.push(entry);
|
|
633
|
+
result.characters += bounded.length;
|
|
634
|
+
if (value.length > bounded.length) result.truncated = true;
|
|
635
|
+
while (result.messages.length > limits.messages || result.characters > limits.characters) {
|
|
636
|
+
const first = result.messages.shift();
|
|
637
|
+
if (first.role === 'user') result.removedQuestion = first;
|
|
638
|
+
result.characters -= first.text.length;
|
|
639
|
+
result.truncated = true;
|
|
640
|
+
}
|
|
641
|
+
} else {
|
|
642
|
+
const entry = { role, text: value.slice(0, maxMessageLength), agent: result.agent };
|
|
643
|
+
result.messages.push(entry);
|
|
644
|
+
if (result.messages.length > maxMessages) result.messages.shift();
|
|
645
|
+
}
|
|
646
|
+
return true;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function addSkill(result, name) {
|
|
650
|
+
if (typeof name === 'string' && /^[\p{L}\p{N}_:.\/-]{1,140}$/u.test(name.trim())) result.usedSkills.add(name.trim());
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function traceValue(value) {
|
|
654
|
+
if (typeof value === 'string') return value;
|
|
655
|
+
if (value === undefined || value === null) return '';
|
|
656
|
+
try { return JSON.stringify(value); } catch { return ''; }
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function cleanTraceText(value) {
|
|
660
|
+
return traceValue(value).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' ').trim();
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function addTrace(result, item) {
|
|
664
|
+
if (result.events) {
|
|
665
|
+
const { id, text, ...details } = item;
|
|
666
|
+
result.events.push({
|
|
667
|
+
...details, text: traceValue(text).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' '),
|
|
668
|
+
...(id ? { sourceId: id } : {}),
|
|
669
|
+
...(item.kind !== 'tool_result' ? { turn: result.turn } : {}),
|
|
670
|
+
});
|
|
671
|
+
return undefined;
|
|
672
|
+
}
|
|
673
|
+
if (!result.trace) return undefined;
|
|
674
|
+
const text = cleanTraceText(item.text);
|
|
675
|
+
const bounded = text.slice(0, traceTextLimit).replace(/[\uD800-\uDBFF]$/, '');
|
|
676
|
+
const entry = {
|
|
677
|
+
id: `${item.kind}-${item.callId ?? item.id ?? result.traceOrder}`,
|
|
678
|
+
order: result.traceOrder++,
|
|
679
|
+
kind: item.kind,
|
|
680
|
+
...(item.name ? { name: item.name } : {}),
|
|
681
|
+
...(item.callId ? { callId: item.callId } : {}),
|
|
682
|
+
text: bounded,
|
|
683
|
+
status: item.status,
|
|
684
|
+
...(text.length > bounded.length ? { truncated: true } : {}),
|
|
685
|
+
...(item.time ? { time: item.time } : {}),
|
|
686
|
+
turnRef: result.turnRef,
|
|
687
|
+
turn: result.turn,
|
|
688
|
+
};
|
|
689
|
+
const key = entry.kind === 'summary'
|
|
690
|
+
? `summary\0${entry.id}`
|
|
691
|
+
: `${entry.kind}\0${entry.callId ?? entry.id}`;
|
|
692
|
+
if (result.traceKeys.has(key)) return entry;
|
|
693
|
+
result.traceKeys.add(key);
|
|
694
|
+
result.trace.push(entry);
|
|
695
|
+
while (result.trace.length > traceItemLimit) {
|
|
696
|
+
result.truncated = true;
|
|
697
|
+
const removed = result.trace.shift();
|
|
698
|
+
result.traceKeys.delete(removed.kind === 'summary'
|
|
699
|
+
? `summary\0${removed.id}` : `${removed.kind}\0${removed.callId ?? removed.id}`);
|
|
700
|
+
}
|
|
701
|
+
return entry;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function traceCallId(value) {
|
|
705
|
+
if (typeof value !== 'string' || !value) return undefined;
|
|
706
|
+
if (value.length <= 200) return value;
|
|
707
|
+
return `${value.slice(0, 120)}…${createHash('sha256').update(value).digest('hex')}`;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function addSummary(result, text, time, id) {
|
|
711
|
+
const value = result.events ? traceValue(text) : cleanTraceText(text);
|
|
712
|
+
if (!value.trim()) return;
|
|
713
|
+
addTrace(result, { kind: 'summary', text: value, status: 'ok', time: dateMillis(time), id });
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function addToolCall(result, name, callId, input, time) {
|
|
717
|
+
if (typeof name !== 'string' || !name.trim()) return;
|
|
718
|
+
addTrace(result, {
|
|
719
|
+
kind: 'tool_call', name: name.trim().slice(0, 120),
|
|
720
|
+
callId: traceCallId(callId),
|
|
721
|
+
text: result.events ? traceValue(input) : cleanTraceText(input), status: 'pending', time: dateMillis(time),
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function addToolResult(result, callId, output, failed, time) {
|
|
726
|
+
if (!result.events && (!result.trace || typeof callId !== 'string' || !callId)) return;
|
|
727
|
+
addTrace(result, {
|
|
728
|
+
kind: 'tool_result', callId: traceCallId(callId),
|
|
729
|
+
text: result.events ? traceValue(output) : cleanTraceText(output),
|
|
730
|
+
status: failed === 'incomplete' ? 'incomplete' : failed === true ? 'error' : 'ok',
|
|
731
|
+
...(time === undefined ? {} : { time: dateMillis(time) }),
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function skillPaths(result, value) {
|
|
736
|
+
if (typeof value !== 'string') return;
|
|
737
|
+
for (const match of value.replace(/[\\/]+/g, '/').matchAll(/(?:^|\/)([\p{L}\p{N}_:.-]+)\/SKILL\.md\b/giu)) addSkill(result, match[1]);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function readTool(result, name, input) {
|
|
741
|
+
const data = typeof input === 'string' ? json(input) : input;
|
|
742
|
+
if (typeof name !== 'string') return;
|
|
743
|
+
if (name === 'exec' && typeof input === 'string' && /(?:\bGet-Content\b|\breadFile\b|\bcat\s+)/i.test(input)) skillPaths(result, input);
|
|
744
|
+
if (!data) return;
|
|
745
|
+
if (/^(?:skill|activate_skill)$/i.test(name)) addSkill(result, data.skill ?? data.name ?? data.skill_name);
|
|
746
|
+
if (/^(?:read|exec_command|bash|shell)$/i.test(name)) {
|
|
747
|
+
for (const value of [data.file_path, data.filePath, data.path, data.cmd, data.command]) skillPaths(result, value);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function textBlocks(content, result) {
|
|
752
|
+
if (typeof content === 'string') return content;
|
|
753
|
+
if (!Array.isArray(content)) return '';
|
|
754
|
+
const texts = [];
|
|
755
|
+
for (const block of content) {
|
|
756
|
+
if (typeof block === 'string') texts.push(block);
|
|
757
|
+
if (['text', 'input_text', 'output_text'].includes(block?.type) && typeof block.text === 'string') texts.push(block.text);
|
|
758
|
+
if (result && block?.type === 'tool_use') {
|
|
759
|
+
readTool(result, block.name, block.input);
|
|
760
|
+
addToolCall(result, block.name, block.id, block.input);
|
|
761
|
+
}
|
|
762
|
+
if (result && block?.type === 'tool_result') {
|
|
763
|
+
const value = result.events ? sourceToolOutput(result, block.content, block.tool_use_id)
|
|
764
|
+
: (Array.isArray(block.content)
|
|
765
|
+
? block.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n')
|
|
766
|
+
: block.content);
|
|
767
|
+
addToolResult(result, block.tool_use_id, value, block.is_error === true);
|
|
768
|
+
}
|
|
769
|
+
if (result && block?.type === 'tool') {
|
|
770
|
+
const input = block.state?.input ?? block.input ?? block.args;
|
|
771
|
+
readTool(result, block.tool ?? block.name, input);
|
|
772
|
+
const callId = block.callID ?? block.callId ?? block.id;
|
|
773
|
+
addToolCall(result, block.tool ?? block.name, callId, input, block.time?.created);
|
|
774
|
+
const state = block.state ?? {};
|
|
775
|
+
if (state.status === 'completed' || state.status === 'error') {
|
|
776
|
+
const output = state.output ?? state.result ?? state.content ?? state.error?.message ?? state.error;
|
|
777
|
+
const time = result.events ? block.time?.completed : undefined;
|
|
778
|
+
addToolResult(result, callId, result.events ? sourceToolOutput(result, output, callId) : output, state.status === 'error', time);
|
|
779
|
+
if (result.events && state.metadata?.truncated === true) markSourcePartial(result, 'source-tool-output-truncated');
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
// A Codex user message can contain several independent input_text blocks.
|
|
784
|
+
// Filter each one so an internal block never hides a neighboring prompt.
|
|
785
|
+
return texts.map(stripRuntimeWrapper).filter(value => value.trim()).join('\n');
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function sourceAttachment(block) {
|
|
789
|
+
const type = block?.type;
|
|
790
|
+
if (!['input_image', 'image', 'file', 'input_file', 'document'].includes(type) && !block?.inlineData && !block?.fileData) return;
|
|
791
|
+
const source = block.source ?? block.inlineData ?? block.fileData ?? block;
|
|
792
|
+
const url = block.image_url?.url ?? block.image_url ?? block.url ?? source.fileUri ?? source.url;
|
|
793
|
+
const embedded = typeof url === 'string' ? /^data:([a-z\d.+-]+\/[a-z\d.+-]+);base64,([a-z\d+/=]+)$/i.exec(url) : undefined;
|
|
794
|
+
const encoded = embedded?.[2] ?? source.data ?? block.file_data;
|
|
795
|
+
const sourceType = embedded?.[1] ?? source.media_type ?? source.mimeType ?? source.mime ?? block.mime;
|
|
796
|
+
const mediaType = typeof sourceType === 'string' ? sourceType : undefined;
|
|
797
|
+
const originalName = block.filename ?? block.name ?? block.title;
|
|
798
|
+
const name = typeof originalName === 'string' && path.win32.basename(originalName)
|
|
799
|
+
|| ((typeof type === 'string' && type.includes('image')) || mediaType?.startsWith('image/') ? '图片' : '附件');
|
|
800
|
+
const file = localDirectory(block.path ?? url);
|
|
801
|
+
if (typeof encoded === 'string' && /^[\da-z+/]+={0,2}$/i.test(encoded)) {
|
|
802
|
+
return { name, mediaType, data: Buffer.from(encoded, 'base64') };
|
|
803
|
+
}
|
|
804
|
+
if (file) return { name, mediaType, path: file };
|
|
805
|
+
return { name, mediaType, status: typeof url === 'string' ? 'remote-reference' : 'name-only' };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function sourceToolOutput(result, value, callId) {
|
|
809
|
+
if (!Array.isArray(value)) return value;
|
|
810
|
+
for (const attachment of value.map(sourceAttachment).filter(Boolean)) {
|
|
811
|
+
result.events.push({
|
|
812
|
+
kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId,
|
|
813
|
+
callId: traceCallId(callId), ...attachment,
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
return textBlocks(value);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function sourceBlockText(block, functionParts) {
|
|
820
|
+
if (typeof block === 'string') return block;
|
|
821
|
+
if (block?.thought || typeof block?.text !== 'string') return undefined;
|
|
822
|
+
if (['text', 'input_text', 'output_text'].includes(block.type) || (functionParts && block.type === undefined)) return block.text;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function sourceReasoning(block) {
|
|
826
|
+
if (block?.type === 'thinking') return block.thinking;
|
|
827
|
+
if (block?.type === 'reasoning' || block?.thought === true) return block.text;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function readAssistantBlocks(result, blocks, timestamp, hints) {
|
|
831
|
+
let foundText = false;
|
|
832
|
+
let text = [];
|
|
833
|
+
const flush = () => {
|
|
834
|
+
if (text.length) foundText = appendMessage(result, 'assistant', text.join('\n'), timestamp, hints) || foundText;
|
|
835
|
+
text = [];
|
|
836
|
+
};
|
|
837
|
+
for (const block of blocks) {
|
|
838
|
+
const body = sourceBlockText(block, hints.functionParts);
|
|
839
|
+
if (body !== undefined) {
|
|
840
|
+
text.push(stripRuntimeWrapper(body));
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
const thought = sourceReasoning(block);
|
|
844
|
+
const attachment = sourceAttachment(block);
|
|
845
|
+
const tool = ['tool', 'tool_use', 'tool_result'].includes(block?.type)
|
|
846
|
+
|| (hints.functionParts && (block?.functionCall || block?.functionResponse));
|
|
847
|
+
if (!thought && !tool && !attachment) continue;
|
|
848
|
+
flush();
|
|
849
|
+
if (typeof thought === 'string') addSummary(result, thought, timestamp, result.sourceId);
|
|
850
|
+
if (attachment) {
|
|
851
|
+
result.events.push({ kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId, ...attachment });
|
|
852
|
+
}
|
|
853
|
+
if (tool) {
|
|
854
|
+
textBlocks([block], result);
|
|
855
|
+
if (hints.functionParts) readFunctionParts(result, [block], timestamp);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
flush();
|
|
859
|
+
if (!foundText) appendMessage(result, 'assistant', hints.text, timestamp, hints);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
function readSourceBlocks(result, role, content, timestamp, hints = {}) {
|
|
863
|
+
const blocks = Array.isArray(content) ? content : [];
|
|
864
|
+
if (role === 'assistant' && blocks.length) {
|
|
865
|
+
readAssistantBlocks(result, blocks, timestamp, hints);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const attachments = blocks.map(sourceAttachment).filter(Boolean);
|
|
869
|
+
const added = appendMessage(result, role, hints.text ?? textBlocks(content), timestamp, hints);
|
|
870
|
+
const standalone = role === 'user' && attachments.length > 0 && !added;
|
|
871
|
+
if (standalone) result.turn++;
|
|
872
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
873
|
+
result.events.push({
|
|
874
|
+
kind: 'attachment', role, turn: result.turn, sourceId: result.sourceId, ...attachment,
|
|
875
|
+
...(standalone && index === 0 ? { standalone: true } : {}),
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
textBlocks(blocks, result);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function firstQuestion(rows, agent) {
|
|
882
|
+
for (const row of rows) {
|
|
883
|
+
if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
|
|
884
|
+
let body;
|
|
885
|
+
if (agent === 'codex') {
|
|
886
|
+
if (row.type === 'response_item' && row.payload?.type === 'message' && row.payload.role === 'user') {
|
|
887
|
+
body = textBlocks(row.payload.content);
|
|
888
|
+
}
|
|
889
|
+
} else if (agent === 'workbuddy') {
|
|
890
|
+
if (row.type === 'message' && ['user', 'human'].includes(row.role)) body = textBlocks(row.content);
|
|
891
|
+
} else if (row.type === 'user') {
|
|
892
|
+
body = agent === 'qwen' && Array.isArray(row.message?.parts)
|
|
893
|
+
? row.message.parts.filter(part => !part?.thought).map(part => part?.text ?? '').join('\n')
|
|
894
|
+
: textBlocks(row.message?.content);
|
|
895
|
+
}
|
|
896
|
+
const title = messageText(body);
|
|
897
|
+
if (title && !title.startsWith('<skill>')) return title;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
async function allowedGemini(descriptor, cwd, config) {
|
|
902
|
+
for (const root of configuredRoots(config, 'gemini')) {
|
|
903
|
+
const [base] = await transcriptDirectories(root, ['tmp']);
|
|
904
|
+
if (!base) continue;
|
|
905
|
+
const file = await scopedFile(descriptor.file, base);
|
|
906
|
+
if (!file || path.basename(path.dirname(file)) !== 'chats' || !/^session-.+\.jsonl?$/i.test(path.basename(file))) continue;
|
|
907
|
+
const marker = await scopedFile(path.resolve(path.dirname(file), '..', '.project_root'), base);
|
|
908
|
+
if (!marker || !await sameDirectory((await prefix(marker, 32 * 1024)).text.trim(), cwd)) continue;
|
|
909
|
+
return file;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async function readGeminiHistory(descriptor, cwd, config, result) {
|
|
914
|
+
const file = await allowedGemini(descriptor, cwd, config);
|
|
915
|
+
if (!file) return;
|
|
916
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
917
|
+
if (truncated) markSourcePartial(result);
|
|
918
|
+
const messages = json(text)?.messages ?? rowsFrom(text, truncated);
|
|
919
|
+
if (!Array.isArray(messages)) return;
|
|
920
|
+
for (const row of messages) {
|
|
921
|
+
const message = row.message ?? row;
|
|
922
|
+
if (!['user', 'gemini', 'assistant'].includes(message.type)) continue;
|
|
923
|
+
const content = Array.isArray(message.content) ? message.content.map(block => block?.text ?? '').join('\n') : message.content;
|
|
924
|
+
appendMessage(result, message.type === 'gemini' ? 'assistant' : message.type, content, message.timestamp);
|
|
925
|
+
for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) readTool(result, tool.name, tool.args);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
async function readAntigravityHistory(descriptor, cwd, config, result) {
|
|
930
|
+
for (const root of configuredRoots(config, 'antigravity')) {
|
|
931
|
+
const file = await scopedFile(path.join(root, 'history.jsonl'), root);
|
|
932
|
+
if (!file || pathKey(descriptor.file) !== pathKey(file)) continue;
|
|
933
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
934
|
+
for (const row of rowsFrom(text, truncated)) {
|
|
935
|
+
if (row.conversationId === descriptor.id && await sameDirectory(localDirectory(row.workspace), cwd)) {
|
|
936
|
+
appendMessage(result, 'user', row.display);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function copilotRequests(text, truncated) {
|
|
944
|
+
const snapshot = json(text);
|
|
945
|
+
if (Array.isArray(snapshot?.requests)) return snapshot.requests;
|
|
946
|
+
let state;
|
|
947
|
+
for (const op of rowsFrom(text, truncated)) {
|
|
948
|
+
if (op.kind === 0) state = op.v;
|
|
949
|
+
else applyCopilotOp(state, op);
|
|
950
|
+
}
|
|
951
|
+
return Array.isArray(state?.requests) ? state.requests : [];
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function applyCopilotOp(state, op) {
|
|
955
|
+
if (!Array.isArray(op.k) || op.k[0] !== 'requests') return true;
|
|
956
|
+
if (op.k.length > 8) return false;
|
|
957
|
+
const keys = op.k.map(String);
|
|
958
|
+
if (keys.some(key => ['__proto__', 'prototype', 'constructor'].includes(key))) return false;
|
|
959
|
+
const key = keys.pop();
|
|
960
|
+
let target = state;
|
|
961
|
+
for (const part of keys) target = target && Object.hasOwn(target, part) ? target[part] : undefined;
|
|
962
|
+
if (!target || typeof target !== 'object') return false;
|
|
963
|
+
if (Array.isArray(target) && (!/^\d+$/.test(key) || Number(key) >= target.length)) return false;
|
|
964
|
+
if (op.kind === 1) {
|
|
965
|
+
target[key] = op.v;
|
|
966
|
+
return true;
|
|
967
|
+
}
|
|
968
|
+
if (op.kind === 2 && Array.isArray(target[key]) && Array.isArray(op.v)) {
|
|
969
|
+
const current = target[key];
|
|
970
|
+
const index = Number.isInteger(op.i) ? Math.max(0, Math.min(op.i, current.length)) : current.length;
|
|
971
|
+
target[key] = current.slice(0, index).concat(op.v, current.slice(index + op.v.length));
|
|
972
|
+
return true;
|
|
973
|
+
}
|
|
974
|
+
if (op.kind === 3 && !Array.isArray(target)) {
|
|
975
|
+
delete target[key];
|
|
976
|
+
return true;
|
|
977
|
+
}
|
|
978
|
+
return false;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async function allowedEditorChat(descriptor, cwd, config) {
|
|
982
|
+
const stores = await Promise.all(configuredRoots(config, 'copilot').map(editorStores));
|
|
983
|
+
for (const base of stores.flat()) {
|
|
984
|
+
const file = await scopedFile(descriptor.file, base);
|
|
985
|
+
if (!file || path.basename(path.dirname(file)) !== 'chatSessions' || !/\.jsonl?$/i.test(file)) continue;
|
|
986
|
+
const workspace = await scopedFile(path.resolve(path.dirname(file), '..', 'workspace.json'), base);
|
|
987
|
+
if (!workspace) continue;
|
|
988
|
+
const marker = json((await prefix(workspace, 32 * 1024)).text);
|
|
989
|
+
if (!await sameDirectory(localDirectory(marker?.folder), cwd)) continue;
|
|
990
|
+
return file;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
function copilotText(item) {
|
|
995
|
+
if (item?.kind && item.kind !== 'markdownContent') return '';
|
|
996
|
+
const value = item?.value?.value ?? item?.value;
|
|
997
|
+
return typeof value === 'string' ? value : '';
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function copilotAnswer(response) {
|
|
1001
|
+
return response.map(copilotText).join('');
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
async function readCopilotHistory(descriptor, cwd, config, result) {
|
|
1005
|
+
const file = await allowedEditorChat(descriptor, cwd, config);
|
|
1006
|
+
if (!file) return;
|
|
1007
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
1008
|
+
if (truncated) markSourcePartial(result);
|
|
1009
|
+
const requests = copilotRequests(text, truncated);
|
|
1010
|
+
for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
|
|
1011
|
+
appendMessage(result, 'user', request?.message?.text, request?.timestamp);
|
|
1012
|
+
const response = Array.isArray(request?.response) ? request.response : [];
|
|
1013
|
+
// Copilot stores the request time. Use it for transcript order only.
|
|
1014
|
+
appendMessage(result, 'assistant', copilotAnswer(response), request?.timestamp, { estimatedTime: true });
|
|
1015
|
+
for (const item of response) {
|
|
1016
|
+
if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
async function* zstdChunks(file) {
|
|
1022
|
+
const decoder = zlib.createZstdDecompress();
|
|
1023
|
+
const input = createReadStream(file);
|
|
1024
|
+
input.on('error', error => decoder.destroy(error));
|
|
1025
|
+
try {
|
|
1026
|
+
yield* input.pipe(decoder);
|
|
1027
|
+
} finally {
|
|
1028
|
+
// Discovery stops after the header. Close both ends without reading the rest.
|
|
1029
|
+
input.destroy();
|
|
1030
|
+
decoder.destroy();
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
async function compressedPrefix(file) {
|
|
1035
|
+
const { mtimeMs: modified } = await stat(file);
|
|
1036
|
+
const chunks = [];
|
|
1037
|
+
let bytes = 0;
|
|
1038
|
+
for await (const chunk of zstdChunks(file)) {
|
|
1039
|
+
const part = chunk.subarray(0, transcriptHeaderBytes - bytes);
|
|
1040
|
+
if (part.length) chunks.push(part);
|
|
1041
|
+
bytes += part.length;
|
|
1042
|
+
if (part.length < chunk.length) {
|
|
1043
|
+
return { text: Buffer.concat(chunks, bytes).toString('utf8'), truncated: true, modified };
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
return { text: Buffer.concat(chunks, bytes).toString('utf8'), truncated: false, modified };
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
async function* compressedRows(file) {
|
|
1050
|
+
// Keep at most one bounded JSONL record. Large tool outputs commonly sit
|
|
1051
|
+
// between the last question and answer and must not compete with them.
|
|
1052
|
+
let parts = [];
|
|
1053
|
+
let bytes = 0;
|
|
1054
|
+
for await (const chunk of zstdChunks(file)) {
|
|
1055
|
+
let offset = 0;
|
|
1056
|
+
while (offset < chunk.length) {
|
|
1057
|
+
const newline = chunk.indexOf(10, offset);
|
|
1058
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
1059
|
+
const length = end - offset;
|
|
1060
|
+
if (bytes <= maxTranscriptRowBytes && length) {
|
|
1061
|
+
bytes += length;
|
|
1062
|
+
if (bytes <= maxTranscriptRowBytes) parts.push(chunk.subarray(offset, end));
|
|
1063
|
+
else parts = [];
|
|
1064
|
+
}
|
|
1065
|
+
if (newline === -1) break;
|
|
1066
|
+
if (bytes > maxTranscriptRowBytes) yield null;
|
|
1067
|
+
else if (bytes) {
|
|
1068
|
+
const row = json(Buffer.concat(parts, bytes).toString('utf8').replace(/^\uFEFF/, ''));
|
|
1069
|
+
if (row) yield row;
|
|
1070
|
+
}
|
|
1071
|
+
offset = newline + 1;
|
|
1072
|
+
bytes = 0;
|
|
1073
|
+
parts = [];
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
if (bytes > maxTranscriptRowBytes) yield null;
|
|
1077
|
+
else if (bytes) {
|
|
1078
|
+
const row = json(Buffer.concat(parts, bytes).toString('utf8').replace(/^\uFEFF/, ''));
|
|
1079
|
+
if (row) yield row;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
function readCodexRow(result, row) {
|
|
1084
|
+
if (row === null || row.type === 'compacted' || row.isCompactSummary) {
|
|
1085
|
+
if (result.limits || result.events) markSourcePartial(result);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (row.isSidechain) {
|
|
1089
|
+
if (result.events) markSourcePartial(result, 'unresolved-branch');
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
if (row.isMeta) return;
|
|
1093
|
+
const payload = row.payload;
|
|
1094
|
+
if (row.type === 'event_msg' && result.events) {
|
|
1095
|
+
if (payload?.type === 'task_started') result.sourceTurn = payload.turn_id;
|
|
1096
|
+
if (['turn_aborted', 'task_complete'].includes(payload?.type)) {
|
|
1097
|
+
const turn = payload.turn_id ? result.sourceTurns.get(payload.turn_id) : result.turn;
|
|
1098
|
+
if (turn) result.events.push({
|
|
1099
|
+
kind: 'turn_end', turn, status: payload.type === 'turn_aborted' ? 'interrupted' : 'completed',
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
if (row.type === 'event_msg' && payload?.type === 'token_count' && result.readStats) {
|
|
1104
|
+
// Codex repeats cumulative snapshots. The latest recorded total already
|
|
1105
|
+
// includes earlier turns, and may be available even when only a tail was read.
|
|
1106
|
+
const usage = payload.info?.total_token_usage;
|
|
1107
|
+
if (Number.isSafeInteger(usage?.total_tokens) && usage.total_tokens >= 0) {
|
|
1108
|
+
const tokens = { total: usage.total_tokens };
|
|
1109
|
+
for (const name of ['input', 'output']) {
|
|
1110
|
+
const value = usage[`${name}_tokens`];
|
|
1111
|
+
if (Number.isSafeInteger(value) && value >= 0 && value <= tokens.total) tokens[name] = value;
|
|
1112
|
+
}
|
|
1113
|
+
result.readStats.tokens = tokens;
|
|
1114
|
+
}
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
if (row.type !== 'response_item') return;
|
|
1118
|
+
if (payload?.type === 'message') {
|
|
1119
|
+
if (result.events && ['user', 'assistant'].includes(payload.role)) {
|
|
1120
|
+
const previousTurn = result.turn;
|
|
1121
|
+
readSourceBlocks(result, payload.role, payload.content, row.timestamp);
|
|
1122
|
+
if (result.turn !== previousTurn && typeof result.sourceTurn === 'string') {
|
|
1123
|
+
result.sourceTurns.set(result.sourceTurn, result.turn);
|
|
1124
|
+
}
|
|
1125
|
+
} else {
|
|
1126
|
+
appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
|
|
1127
|
+
}
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (payload?.type === 'reasoning') {
|
|
1131
|
+
// Only the visible summary is retained; encrypted reasoning has no text.
|
|
1132
|
+
const summary = Array.isArray(payload.summary) ? payload.summary : [];
|
|
1133
|
+
const text = summary.filter(item => item?.type === 'summary_text' && typeof item.text === 'string')
|
|
1134
|
+
.map(item => item.text).join('\n\n');
|
|
1135
|
+
if (text) addSummary(result, text, row.timestamp, payload.id);
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
if (payload?.type === 'function_call' || payload?.type === 'custom_tool_call') {
|
|
1139
|
+
readTool(result, payload.name, payload.arguments ?? payload.input);
|
|
1140
|
+
addToolCall(result, payload.name, payload.call_id ?? payload.id, payload.arguments ?? payload.input, row.timestamp);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
if (payload?.type === 'function_call_output' || payload?.type === 'custom_tool_call_output') {
|
|
1144
|
+
const output = payload.output ?? payload.content;
|
|
1145
|
+
const text = result.events ? traceValue(sourceToolOutput(result, output, payload.call_id))
|
|
1146
|
+
: (Array.isArray(output)
|
|
1147
|
+
? output.filter(item => item?.type === 'input_text' && typeof item.text === 'string').map(item => item.text).join('\n')
|
|
1148
|
+
: output);
|
|
1149
|
+
const value = typeof text === 'string' ? text : '';
|
|
1150
|
+
addToolResult(result, payload.call_id, value, payload.status === 'failed'
|
|
1151
|
+
|| /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value), ...(result.events ? [row.timestamp] : []));
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
async function readCompressedCodex(file, cwd, result) {
|
|
1156
|
+
// Use a separate accumulator so a damaged file never contributes an
|
|
1157
|
+
// incomplete history or discards previously read project context.
|
|
1158
|
+
const local = { messages: [], usedSkills: new Set(), limits: result.limits,
|
|
1159
|
+
characters: 0, truncated: false, agent: result.agent,
|
|
1160
|
+
trace: result.trace ? [] : undefined, traceKeys: result.trace ? new Set() : undefined,
|
|
1161
|
+
traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
|
|
1162
|
+
readStats: result.readStats && { userMessages: 0, assistantMessages: 0, timedMessages: 0 } };
|
|
1163
|
+
let validated = false;
|
|
1164
|
+
for await (const row of compressedRows(file)) {
|
|
1165
|
+
if (!validated) {
|
|
1166
|
+
if (row?.type !== 'session_meta') return;
|
|
1167
|
+
if (!await sameDirectory(row.payload?.cwd, cwd)) return;
|
|
1168
|
+
validated = true;
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
readCodexRow(local, row);
|
|
1172
|
+
}
|
|
1173
|
+
if (result.limits) {
|
|
1174
|
+
const trace = result.trace ? [...result.trace, ...local.trace] : undefined;
|
|
1175
|
+
Object.assign(result, local);
|
|
1176
|
+
if (result.trace) result.trace = trace;
|
|
1177
|
+
} else {
|
|
1178
|
+
result.messages.push(...local.messages);
|
|
1179
|
+
if (result.messages.length > maxMessages) result.messages.splice(0, result.messages.length - maxMessages);
|
|
1180
|
+
for (const skill of local.usedSkills) result.usedSkills.add(skill);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
async function transcriptTail(file) {
|
|
1185
|
+
const handle = await open(file, 'r');
|
|
1186
|
+
try {
|
|
1187
|
+
const { size } = await handle.stat();
|
|
1188
|
+
const buffer = Buffer.alloc(Math.min(size, tailBufferBytes));
|
|
1189
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, size - buffer.length);
|
|
1190
|
+
return parseTail(buffer.subarray(0, bytesRead));
|
|
1191
|
+
} finally {
|
|
1192
|
+
await handle.close();
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function parseTail(buffer) {
|
|
1197
|
+
const truncated = buffer.length > maxTranscriptBytes;
|
|
1198
|
+
// Inspect one byte before the window so a complete first line isn't dropped.
|
|
1199
|
+
const newline = truncated ? buffer.indexOf(10, buffer.length - tailBufferBytes) : -1;
|
|
1200
|
+
return {
|
|
1201
|
+
history: truncated && newline === -1 ? [] : rowsFrom(buffer.toString('utf8', newline + 1), false),
|
|
1202
|
+
truncated,
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
async function allowedJsonl(descriptor, config) {
|
|
1207
|
+
const codex = descriptor.kind === 'codex';
|
|
1208
|
+
const locations = codex ? codexLocations : ['projects'];
|
|
1209
|
+
const bases = (await Promise.all(configuredRoots(config, descriptor.kind)
|
|
1210
|
+
.map(root => transcriptDirectories(root, locations)))).flat();
|
|
1211
|
+
let file;
|
|
1212
|
+
if (codex) file = await resolveCodexTranscript(descriptor.file, bases);
|
|
1213
|
+
else {
|
|
1214
|
+
for (const base of bases) {
|
|
1215
|
+
file = await scopedFile(descriptor.file, base);
|
|
1216
|
+
if (file) break;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
return file;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
async function readJsonlHistory(descriptor, cwd, config, result) {
|
|
1223
|
+
const codex = descriptor.kind === 'codex';
|
|
1224
|
+
const file = await allowedJsonl(descriptor, config);
|
|
1225
|
+
if (!file) return;
|
|
1226
|
+
if (codex && compressedCodexFile.test(file)) return readCompressedCodex(file, cwd, result);
|
|
1227
|
+
if (!jsonlFile.test(file)) return;
|
|
1228
|
+
// Validate the embedded working directory before returning messages from this source.
|
|
1229
|
+
const { text, truncated } = await prefix(file, transcriptHeaderBytes);
|
|
1230
|
+
if (!await sameDirectory(await nativeCwd(file, descriptor.kind, rowsFrom(text, truncated)), cwd)) return;
|
|
1231
|
+
const transcript = await transcriptTail(file);
|
|
1232
|
+
|
|
1233
|
+
// Active transcripts may have a torn last row. Large transcripts keep the latest bounded tail.
|
|
1234
|
+
const { history } = transcript;
|
|
1235
|
+
if (transcript.truncated) markSourcePartial(result);
|
|
1236
|
+
for (const row of history) {
|
|
1237
|
+
if (result.limits && row.isCompactSummary) markSourcePartial(result);
|
|
1238
|
+
if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
|
|
1239
|
+
if (descriptor.kind === 'codex') {
|
|
1240
|
+
readCodexRow(result, row);
|
|
1241
|
+
} else if (descriptor.kind === 'workbuddy') {
|
|
1242
|
+
if (row.type === 'message') appendMessage(result, row.role === 'human' ? 'user' : row.role, textBlocks(row.content, result), row.timestamp);
|
|
1243
|
+
if (row.type === 'function_call') readTool(result, row.name, row.arguments);
|
|
1244
|
+
} else if (descriptor.kind === 'qwen' && (row.type === 'user' || row.type === 'assistant')) {
|
|
1245
|
+
const parts = Array.isArray(row.message?.parts) ? row.message.parts : [];
|
|
1246
|
+
appendMessage(result, row.type, parts.filter(part => !part?.thought && typeof part?.text === 'string').map(part => part.text).join('\n'), row.timestamp);
|
|
1247
|
+
for (const part of parts) readTool(result, part?.functionCall?.name, part?.functionCall?.args);
|
|
1248
|
+
} else if (row.type === 'user' || row.type === 'assistant') {
|
|
1249
|
+
appendMessage(result, row.type, textBlocks(row.message?.content, result), row.timestamp);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
async function allowedArchive(descriptor, config) {
|
|
1255
|
+
const candidates = descriptor.kind === 'agentsview' ? config.archiveFiles ?? []
|
|
1256
|
+
: (await Promise.all(configuredRoots(config, descriptor.kind)
|
|
1257
|
+
.map(descriptor.kind === 'copilot' ? copilotDatabase : opencodeDatabase))).filter(Boolean);
|
|
1258
|
+
const actual = await physicalPath(descriptor.file);
|
|
1259
|
+
if (!actual) return undefined;
|
|
1260
|
+
for (const candidate of candidates) {
|
|
1261
|
+
const allowed = await physicalPath(candidate);
|
|
1262
|
+
if (allowed && pathKey(allowed) === pathKey(actual)) return actual;
|
|
1263
|
+
}
|
|
1264
|
+
return undefined;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
async function readDatabaseHistory(descriptor, cwd, config, result) {
|
|
1268
|
+
const file = await allowedArchive(descriptor, config);
|
|
1269
|
+
if (!file) return;
|
|
1270
|
+
const snapshot = await withDatabase(file, db => {
|
|
1271
|
+
if (descriptor.kind === 'agentsview') {
|
|
1272
|
+
const sessionFields = columns(db, 'sessions');
|
|
1273
|
+
const deleted = sessionFields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
|
|
1274
|
+
const machine = sessionFields.has('machine') ? " AND machine IN ('', 'local')" : '';
|
|
1275
|
+
const project = db.prepare('SELECT cwd, agent FROM sessions WHERE id = ?' + deleted + machine).get(descriptor.id);
|
|
1276
|
+
const fields = columns(db, 'messages');
|
|
1277
|
+
const content = fields.has('dialogue_text') ? "COALESCE(dialogue_text, '')" : 'content';
|
|
1278
|
+
const system = fields.has('is_system') ? ' AND is_system = 0' : '';
|
|
1279
|
+
const time = fields.has('timestamp') ? 'timestamp' : 'NULL';
|
|
1280
|
+
const messages = db.prepare(`SELECT role, substr(${content}, 1, ?) AS text, ${time} AS time FROM messages WHERE session_id = ? AND role IN ('user', 'assistant')${system} ORDER BY ordinal DESC LIMIT ?`)
|
|
1281
|
+
.all(result.limits ? result.limits.messageLength + 1 : maxMessageLength, descriptor.id,
|
|
1282
|
+
result.limits ? result.limits.messages + 1 : maxMessages).reverse();
|
|
1283
|
+
const skills = columns(db, 'tool_calls').has('skill_name') ? db.prepare('SELECT DISTINCT skill_name FROM tool_calls WHERE session_id = ? AND skill_name IS NOT NULL LIMIT 200').all(descriptor.id) : [];
|
|
1284
|
+
return { cwd: project?.cwd, agent: project?.agent, messages, skills };
|
|
1285
|
+
}
|
|
1286
|
+
if (!opencodeTables(db).includes(descriptor.table)) return undefined;
|
|
1287
|
+
const project = db.prepare(`SELECT directory FROM ${descriptor.table} WHERE id = ?`).get(descriptor.id);
|
|
1288
|
+
const fields = columns(db, 'session_message');
|
|
1289
|
+
if (['type', 'session_id', 'data'].every(field => fields.has(field))) {
|
|
1290
|
+
const order = fields.has('seq') ? 'seq' : 'time_created';
|
|
1291
|
+
const time = fields.has('time_created') ? 'time_created' : 'NULL';
|
|
1292
|
+
const messages = db.prepare(`SELECT type, data, ${time} AS time FROM session_message WHERE session_id = ? AND type IN ('user','assistant','skill') ORDER BY ${order} DESC LIMIT ?`)
|
|
1293
|
+
.all(descriptor.id, result.limits ? result.limits.messages + 1 : 100).reverse();
|
|
1294
|
+
if (messages.length) return { cwd: project?.directory, projection: messages };
|
|
1295
|
+
}
|
|
1296
|
+
if (!columns(db, 'message').has('data') || !columns(db, 'part').has('data')) return { cwd: project?.directory };
|
|
1297
|
+
const messages = db.prepare('SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created DESC LIMIT ?')
|
|
1298
|
+
.all(descriptor.id, result.limits ? result.limits.messages + 1 : maxMessages).reverse();
|
|
1299
|
+
const parts = db.prepare('SELECT data FROM part WHERE session_id = ? AND message_id = ? ORDER BY time_created LIMIT 100');
|
|
1300
|
+
return { cwd: project?.directory, legacy: messages.map(row => ({ role: json(row.data)?.role, time: row.time_created, parts: parts.all(descriptor.id, row.id).map(part => json(part.data)) })) };
|
|
1301
|
+
});
|
|
1302
|
+
if (!snapshot || !await sameDirectory(snapshot.cwd, cwd)) return;
|
|
1303
|
+
if (snapshot.agent) result.agent = snapshot.agent;
|
|
1304
|
+
for (const row of snapshot.messages ?? []) appendMessage(result, row.role, row.text, row.time);
|
|
1305
|
+
for (const row of snapshot.skills ?? []) addSkill(result, row.skill_name);
|
|
1306
|
+
for (const row of snapshot.projection ?? []) {
|
|
1307
|
+
const data = json(row.data);
|
|
1308
|
+
if (row.type === 'skill') addSkill(result, data?.name ?? data?.skill);
|
|
1309
|
+
else appendMessage(result, row.type, data?.text ?? textBlocks(data?.content, result), row.time);
|
|
1310
|
+
}
|
|
1311
|
+
for (const row of snapshot.legacy ?? []) appendMessage(result, row.role, textBlocks(row.parts, result), row.time);
|
|
1312
|
+
if (result.limits && (snapshot.messages ?? snapshot.projection ?? snapshot.legacy ?? []).length > result.limits.messages) {
|
|
1313
|
+
markSourcePartial(result);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
async function readHistory(archive, cwd, config, result) {
|
|
1318
|
+
result.agent = archive.agent ?? archive.kind;
|
|
1319
|
+
if (archive.kind === 'agentsview' || archive.kind === 'opencode') await readDatabaseHistory(archive, cwd, config, result);
|
|
1320
|
+
if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive.kind)) await readJsonlHistory(archive, cwd, config, result);
|
|
1321
|
+
if (archive.kind === 'gemini') await readGeminiHistory(archive, cwd, config, result);
|
|
1322
|
+
if (archive.kind === 'antigravity') await readAntigravityHistory(archive, cwd, config, result);
|
|
1323
|
+
if (archive.kind === 'copilot' && archive.storage === 'sqlite') {
|
|
1324
|
+
for await (const event of readSourceEvents(archive, { config, sourceCwd: cwd })) {
|
|
1325
|
+
if (event.kind === 'message') appendMessage(result, event.role, event.text, event.time);
|
|
1326
|
+
if (event.kind === 'gap' && result.limits) markSourcePartial(result, event.reason);
|
|
1327
|
+
}
|
|
1328
|
+
} else if (archive.kind === 'copilot') await readCopilotHistory(archive, cwd, config, result);
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
function readSourceMessageRow(result, kind, row) {
|
|
1332
|
+
if (kind === 'codex') {
|
|
1333
|
+
readCodexRow(result, row);
|
|
1334
|
+
} else if (row.isCompactSummary || (row.type === 'system' && row.subtype === 'compact_boundary')) {
|
|
1335
|
+
markSourcePartial(result);
|
|
1336
|
+
} else if (row.isSidechain) {
|
|
1337
|
+
markSourcePartial(result, 'unresolved-branch');
|
|
1338
|
+
} else if (!row.isMeta) {
|
|
1339
|
+
if (kind === 'workbuddy') {
|
|
1340
|
+
if (row.type === 'message') readSourceBlocks(result, row.role === 'human' ? 'user' : row.role, row.content, row.timestamp);
|
|
1341
|
+
if (row.type === 'reasoning') {
|
|
1342
|
+
const text = blocks => Array.isArray(blocks) ? blocks
|
|
1343
|
+
.filter(block => block?.type === 'reasoning_text' && typeof block.text === 'string')
|
|
1344
|
+
.map(block => block.text).join('\n\n') : '';
|
|
1345
|
+
addSummary(result, text(row.content) || text(row.rawContent), row.timestamp, result.sourceId);
|
|
1346
|
+
}
|
|
1347
|
+
if (row.type === 'function_call') {
|
|
1348
|
+
readTool(result, row.name, row.arguments);
|
|
1349
|
+
addToolCall(result, row.name, row.callId ?? row.call_id ?? row.id, row.arguments, row.timestamp);
|
|
1350
|
+
}
|
|
1351
|
+
if (['function_call_output', 'function_call_result'].includes(row.type)) {
|
|
1352
|
+
const blocks = Array.isArray(row.output) ? row.output : [row.output];
|
|
1353
|
+
const output = blocks.length && blocks.every(block => block?.type === 'text' && typeof block.text === 'string')
|
|
1354
|
+
? blocks.map(block => block.text).join('\n') : row.output;
|
|
1355
|
+
const status = row.status === 'incomplete' ? 'incomplete' : ['error', 'failed'].includes(row.status);
|
|
1356
|
+
addToolResult(result, row.callId ?? row.call_id, output, status, row.timestamp);
|
|
1357
|
+
}
|
|
1358
|
+
} else if (kind === 'qwen' && Array.isArray(row.message?.parts)) {
|
|
1359
|
+
const parts = row.message.parts;
|
|
1360
|
+
if (row.type === 'user' || row.type === 'assistant') {
|
|
1361
|
+
readSourceBlocks(result, row.type, parts, row.timestamp, {
|
|
1362
|
+
functionParts: true,
|
|
1363
|
+
text: parts.map(part => sourceBlockText(part, true)).filter(Boolean).join('\n'),
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
if (['user', 'tool_result'].includes(row.type)) readFunctionParts(result, parts, row.timestamp);
|
|
1367
|
+
} else if (row.type === 'user' || row.type === 'assistant') {
|
|
1368
|
+
readSourceBlocks(result, row.type, row.message?.content, row.timestamp);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
function readFunctionParts(result, parts, time) {
|
|
1374
|
+
for (const part of parts) {
|
|
1375
|
+
if (part?.functionCall) {
|
|
1376
|
+
const { name, id, args } = part.functionCall;
|
|
1377
|
+
readTool(result, name, args);
|
|
1378
|
+
addToolCall(result, name, id, args, time);
|
|
1379
|
+
}
|
|
1380
|
+
if (part?.functionResponse) {
|
|
1381
|
+
const { id, response } = part.functionResponse;
|
|
1382
|
+
const error = Boolean(response?.error);
|
|
1383
|
+
const output = response && typeof response === 'object' && Object.keys(response).length === 1
|
|
1384
|
+
? response.error ?? response.output ?? response : response;
|
|
1385
|
+
addToolResult(result, id, output, error, time);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
function sourceIdentity(result, row, ordinal) {
|
|
1391
|
+
result.sourceId = row.uuid ?? row.message?.id ?? row.payload?.id ?? row.id ?? `row:${ordinal}`;
|
|
1392
|
+
result.parentId = row.parentUuid ?? row.message?.parentId;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
async function* jsonlSourceEvents(archive, options, result) {
|
|
1396
|
+
const { config, sourceCwd, signal } = options;
|
|
1397
|
+
const file = await allowedJsonl(archive, config);
|
|
1398
|
+
if (!file) {
|
|
1399
|
+
yield { kind: 'gap', reason: compressedCodexFile.test(archive.file) && !hasZstd ? 'unsupported-compression' : 'source-unavailable' };
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
let validated = false;
|
|
1403
|
+
let ordinal = 0;
|
|
1404
|
+
let pendingBytes = 0;
|
|
1405
|
+
let pending = [];
|
|
1406
|
+
for await (const { row, bytes, gap } of sourceJsonl(file, { compressed: compressedCodexFile.test(file), signal })) {
|
|
1407
|
+
if (gap) {
|
|
1408
|
+
yield { kind: 'gap', reason: gap };
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
ordinal++;
|
|
1412
|
+
if (!validated) {
|
|
1413
|
+
// Codex authenticates the session before any content can leave the reader.
|
|
1414
|
+
const cwd = await nativeCwd(file, archive.kind, [row]);
|
|
1415
|
+
if (!cwd) {
|
|
1416
|
+
pendingBytes += bytes;
|
|
1417
|
+
if (archive.kind === 'codex' || pendingBytes > sourceValueLimit || pending.length >= 65_536) {
|
|
1418
|
+
yield { kind: 'gap', reason: 'source-metadata-missing' };
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
pending.push([row, ordinal]);
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
if (!await sameDirectory(cwd, sourceCwd)
|
|
1425
|
+
|| (archive.kind === 'codex' && archive.id && row.payload?.id && row.payload.id !== archive.id)) {
|
|
1426
|
+
yield { kind: 'gap', reason: 'source-mismatch' };
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
validated = true;
|
|
1430
|
+
for (const [earlier, sequence] of pending) {
|
|
1431
|
+
sourceIdentity(result, earlier, sequence);
|
|
1432
|
+
readSourceMessageRow(result, archive.kind, earlier);
|
|
1433
|
+
yield* result.events.splice(0);
|
|
1434
|
+
}
|
|
1435
|
+
pending = [];
|
|
1436
|
+
}
|
|
1437
|
+
sourceIdentity(result, row, ordinal);
|
|
1438
|
+
readSourceMessageRow(result, archive.kind, row);
|
|
1439
|
+
yield* result.events.splice(0);
|
|
1440
|
+
}
|
|
1441
|
+
if (!validated && ordinal) yield { kind: 'gap', reason: 'source-metadata-missing' };
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
function* agentsViewEvents(db, id, result) {
|
|
1445
|
+
const fields = columns(db, 'messages');
|
|
1446
|
+
if (!['ordinal', 'role', 'session_id'].every(field => fields.has(field))
|
|
1447
|
+
|| (!fields.has('dialogue_text') && !fields.has('content'))) {
|
|
1448
|
+
markSourcePartial(result, 'unsupported-source-schema');
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
const content = fields.has('dialogue_text') ? 'dialogue_text' : 'content';
|
|
1452
|
+
const system = fields.has('is_system') ? ' AND is_system = 0' : '';
|
|
1453
|
+
const time = fields.has('timestamp') ? 'timestamp' : 'NULL';
|
|
1454
|
+
for (const row of db.prepare(`SELECT ordinal, role, ${content} AS text, ${time} AS time FROM messages
|
|
1455
|
+
WHERE session_id = ? AND role IN ('user','assistant')${system} ORDER BY ordinal`).iterate(id)) {
|
|
1456
|
+
result.sourceId = `message:${row.ordinal}`;
|
|
1457
|
+
appendMessage(result, row.role, row.text, row.time);
|
|
1458
|
+
yield* result.events.splice(0);
|
|
1459
|
+
}
|
|
1460
|
+
const toolFields = columns(db, 'tool_calls');
|
|
1461
|
+
if (!toolFields.has('session_id')) return;
|
|
1462
|
+
if (toolFields.has('skill_name')) {
|
|
1463
|
+
for (const row of db.prepare('SELECT DISTINCT skill_name FROM tool_calls WHERE session_id = ?').iterate(id)) {
|
|
1464
|
+
addSkill(result, row.skill_name);
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
if (db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? LIMIT 1').get(id)) {
|
|
1468
|
+
markSourcePartial(result, 'archive-tool-details-unavailable');
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function mergeOpenCodeParts(content, rows, result) {
|
|
1473
|
+
for (const row of rows) {
|
|
1474
|
+
const data = json(row.data);
|
|
1475
|
+
if (!data) {
|
|
1476
|
+
markSourcePartial(result, 'malformed-record');
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
const part = { ...data, type: row.type, ...(row.call_id ? { callID: row.call_id } : {}) };
|
|
1480
|
+
const current = content[row.ordinal];
|
|
1481
|
+
if (!current || current.type !== part.type) {
|
|
1482
|
+
content.push(part);
|
|
1483
|
+
continue;
|
|
1484
|
+
}
|
|
1485
|
+
const sameText = part.text === undefined || current.text === undefined || part.text === current.text;
|
|
1486
|
+
const sameCall = !part.callID || !current.callID || current.callID === part.callID;
|
|
1487
|
+
if (!sameText || !sameCall) {
|
|
1488
|
+
markSourcePartial(result, 'unresolved-source-projection');
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
content[row.ordinal] = { ...current, ...part, ...(part.state ? { state: { ...current.state, ...part.state } } : {}) };
|
|
1492
|
+
}
|
|
1493
|
+
return content;
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
function* openCodeEvents(db, id, result) {
|
|
1497
|
+
const projection = columns(db, 'session_message');
|
|
1498
|
+
const messages = columns(db, 'message');
|
|
1499
|
+
const parts = columns(db, 'part');
|
|
1500
|
+
// The normalized part table carries text and tool statuses directly. If
|
|
1501
|
+
// both layouts exist and contain this session, never replay the projection
|
|
1502
|
+
// as a second copy.
|
|
1503
|
+
if (['id', 'session_id', 'data', 'time_created'].every(field => messages.has(field))
|
|
1504
|
+
&& ['session_id', 'message_id', 'data', 'time_created'].every(field => parts.has(field))
|
|
1505
|
+
&& db.prepare('SELECT 1 FROM message WHERE session_id = ? LIMIT 1').get(id)) {
|
|
1506
|
+
const order = parts.has('id') ? 'time_created, id' : 'time_created';
|
|
1507
|
+
const readParts = db.prepare(`SELECT data FROM part WHERE session_id = ? AND message_id = ? ORDER BY ${order}`);
|
|
1508
|
+
for (const row of db.prepare('SELECT id, data, time_created AS time FROM message WHERE session_id = ? ORDER BY time, id').iterate(id)) {
|
|
1509
|
+
const data = json(row.data);
|
|
1510
|
+
result.sourceId = row.id;
|
|
1511
|
+
result.parentId = data?.parentID;
|
|
1512
|
+
const content = [];
|
|
1513
|
+
for (const part of readParts.iterate(id, row.id)) {
|
|
1514
|
+
const block = json(part.data);
|
|
1515
|
+
if (block) content.push(block);
|
|
1516
|
+
else markSourcePartial(result, 'malformed-record');
|
|
1517
|
+
}
|
|
1518
|
+
if (['user', 'assistant'].includes(data?.role)) readSourceBlocks(result, data.role, content, row.time);
|
|
1519
|
+
else if (!data) markSourcePartial(result, 'malformed-record');
|
|
1520
|
+
yield* result.events.splice(0);
|
|
1521
|
+
}
|
|
1522
|
+
if (['type', 'session_id'].every(field => projection.has(field))) {
|
|
1523
|
+
const messageCount = db.prepare('SELECT count(*) AS count FROM message WHERE session_id = ?').get(id).count;
|
|
1524
|
+
const projectionCount = db.prepare("SELECT count(*) AS count FROM session_message WHERE session_id = ? AND type IN ('user','assistant')").get(id).count;
|
|
1525
|
+
if (projectionCount > messageCount) markSourcePartial(result, 'unresolved-source-projection');
|
|
1526
|
+
}
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
if (['type', 'session_id', 'data'].every(field => projection.has(field))) {
|
|
1530
|
+
const seq = projection.has('seq') ? 'seq' : projection.has('time_created') ? 'time_created' : 'rowid';
|
|
1531
|
+
const time = projection.has('time_created') ? 'time_created' : 'NULL';
|
|
1532
|
+
const messageId = projection.has('id') ? 'id' : 'NULL';
|
|
1533
|
+
const projectedParts = columns(db, 'session_part');
|
|
1534
|
+
const readParts = projection.has('id') && ['session_id', 'message_id', 'ordinal', 'type', 'data'].every(field => projectedParts.has(field))
|
|
1535
|
+
? db.prepare(`SELECT ordinal, type, data, ${projectedParts.has('call_id') ? 'call_id' : 'NULL'} AS call_id FROM session_part
|
|
1536
|
+
WHERE session_id = ? AND message_id = ? ORDER BY ordinal`) : undefined;
|
|
1537
|
+
for (const row of db.prepare(`SELECT ${messageId} AS id, type, data, ${seq} AS seq, ${time} AS time FROM session_message
|
|
1538
|
+
WHERE session_id = ? AND type IN ('user','assistant','skill','idle') ORDER BY seq, id`).iterate(id)) {
|
|
1539
|
+
const data = json(row.data);
|
|
1540
|
+
if (!data) markSourcePartial(result, 'malformed-record');
|
|
1541
|
+
else if (row.type === 'skill') addSkill(result, data.name ?? data.skill);
|
|
1542
|
+
else if (row.type === 'idle') {
|
|
1543
|
+
const status = data.outcome === 'succeeded' ? 'completed'
|
|
1544
|
+
: ['aborted', 'cancelled', 'failed', 'interrupted'].includes(data.outcome) ? 'interrupted' : undefined;
|
|
1545
|
+
if (status && result.turn) result.events.push({ kind: 'turn_end', status, turn: result.turn });
|
|
1546
|
+
}
|
|
1547
|
+
else {
|
|
1548
|
+
result.sourceId = row.id ?? data.id ?? `message:${row.seq}`;
|
|
1549
|
+
const content = Array.isArray(data.content) ? [...data.content] : [];
|
|
1550
|
+
if (readParts) mergeOpenCodeParts(content, readParts.iterate(id, row.id), result);
|
|
1551
|
+
if (Array.isArray(data.files)) {
|
|
1552
|
+
content.push(...data.files.filter(file => file && typeof file === 'object').map(file => ({ type: 'file', ...file })));
|
|
1553
|
+
}
|
|
1554
|
+
readSourceBlocks(result, row.type, content, row.time, {
|
|
1555
|
+
text: data.text ?? (typeof data.content === 'string' ? data.content : undefined),
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
yield* result.events.splice(0);
|
|
1559
|
+
}
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
if (!messages.size || !parts.size) markSourcePartial(result, 'unsupported-source-schema');
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
function* copilotSqliteEvents(db, id, result) {
|
|
1566
|
+
for (const row of db.prepare('SELECT id, user_message, assistant_response, timestamp FROM turns WHERE session_id = ? ORDER BY turn_index, id').iterate(id)) {
|
|
1567
|
+
result.sourceId = `request:${row.id}`;
|
|
1568
|
+
appendMessage(result, 'user', row.user_message, row.timestamp);
|
|
1569
|
+
result.sourceId = `response:${row.id}`;
|
|
1570
|
+
appendMessage(result, 'assistant', row.assistant_response, row.timestamp, { estimatedTime: true });
|
|
1571
|
+
yield* result.events.splice(0);
|
|
1572
|
+
}
|
|
1573
|
+
markSourcePartial(result, 'source-dialogue-only');
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
async function* databaseSourceEvents(archive, options, result) {
|
|
1577
|
+
const { sourceCwd, config, signal } = options;
|
|
1578
|
+
const file = await allowedArchive(archive, config);
|
|
1579
|
+
if (!file) {
|
|
1580
|
+
yield { kind: 'gap', reason: 'source-unavailable' };
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
1584
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
1585
|
+
try {
|
|
1586
|
+
db.exec('PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 1000; BEGIN');
|
|
1587
|
+
let cwd;
|
|
1588
|
+
let events;
|
|
1589
|
+
if (archive.kind === 'agentsview') {
|
|
1590
|
+
const fields = columns(db, 'sessions');
|
|
1591
|
+
const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
|
|
1592
|
+
const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
|
|
1593
|
+
cwd = db.prepare('SELECT cwd FROM sessions WHERE id = ?' + deleted + machine).get(archive.id)?.cwd;
|
|
1594
|
+
events = agentsViewEvents;
|
|
1595
|
+
} else if (archive.kind === 'copilot' && copilotTables(db)) {
|
|
1596
|
+
const host = copilotHostFilter(columns(db, 'sessions'));
|
|
1597
|
+
cwd = localDirectory(db.prepare('SELECT cwd FROM sessions WHERE id = ?' + host).get(archive.id)?.cwd);
|
|
1598
|
+
events = copilotSqliteEvents;
|
|
1599
|
+
} else if (archive.kind === 'opencode' && opencodeTables(db).includes(archive.table)) {
|
|
1600
|
+
cwd = db.prepare(`SELECT directory FROM ${archive.table} WHERE id = ?`).get(archive.id)?.directory;
|
|
1601
|
+
events = openCodeEvents;
|
|
1602
|
+
}
|
|
1603
|
+
if (!events) {
|
|
1604
|
+
yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1605
|
+
} else if (!await sameDirectory(cwd, sourceCwd)) {
|
|
1606
|
+
yield { kind: 'gap', reason: 'source-mismatch' };
|
|
1607
|
+
} else {
|
|
1608
|
+
for (const event of events(db, archive.id, result)) {
|
|
1609
|
+
signal?.throwIfAborted();
|
|
1610
|
+
yield event;
|
|
1611
|
+
}
|
|
1612
|
+
yield* result.events.splice(0);
|
|
1613
|
+
}
|
|
1614
|
+
} finally {
|
|
1615
|
+
db.close();
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
function geminiEvent(result, row, index) {
|
|
1620
|
+
const message = row?.message ?? row;
|
|
1621
|
+
if (!['user', 'gemini', 'assistant'].includes(message?.type)) return;
|
|
1622
|
+
sourceIdentity(result, row, index);
|
|
1623
|
+
const role = message.type === 'gemini' ? 'assistant' : message.type;
|
|
1624
|
+
const blocks = Array.isArray(message.content) ? message.content : [];
|
|
1625
|
+
readSourceBlocks(result, role, message.content, message.timestamp ?? row.timestamp, {
|
|
1626
|
+
functionParts: true,
|
|
1627
|
+
text: blocks.length ? blocks.map(block => sourceBlockText(block, true)).filter(Boolean).join('\n') : undefined,
|
|
1628
|
+
});
|
|
1629
|
+
if (role === 'user') readFunctionParts(result, blocks, message.timestamp);
|
|
1630
|
+
for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) {
|
|
1631
|
+
readTool(result, tool.name, tool.args);
|
|
1632
|
+
addToolCall(result, tool.name, tool.id, tool.args, tool.timestamp ?? message.timestamp);
|
|
1633
|
+
if (tool.result !== undefined || tool.error !== undefined) {
|
|
1634
|
+
addToolResult(result, tool.id, tool.result ?? tool.error, tool.status === 'error' || Boolean(tool.error), tool.timestamp);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
function* copilotEvent(result, requests) {
|
|
1640
|
+
let index = 0;
|
|
1641
|
+
for (const request of requests) {
|
|
1642
|
+
index++;
|
|
1643
|
+
result.sourceId = request?.requestId ?? request?.id ?? `request:${index}`;
|
|
1644
|
+
const requestId = result.sourceId;
|
|
1645
|
+
appendMessage(result, 'user', request?.message?.text, request?.timestamp);
|
|
1646
|
+
const response = Array.isArray(request?.response) ? request.response : [];
|
|
1647
|
+
result.sourceId = `${requestId}:response`;
|
|
1648
|
+
let text = '';
|
|
1649
|
+
const flush = () => {
|
|
1650
|
+
appendMessage(result, 'assistant', text, request?.timestamp, { estimatedTime: true });
|
|
1651
|
+
text = '';
|
|
1652
|
+
};
|
|
1653
|
+
for (const item of response) {
|
|
1654
|
+
if (item?.kind === 'thinking') {
|
|
1655
|
+
const value = item.value?.value ?? item.value;
|
|
1656
|
+
if (typeof value === 'string' && value.trim()) {
|
|
1657
|
+
flush();
|
|
1658
|
+
addSummary(result, value, undefined);
|
|
1659
|
+
}
|
|
1660
|
+
continue;
|
|
1661
|
+
}
|
|
1662
|
+
if (item?.kind !== 'toolInvocationSerialized') {
|
|
1663
|
+
text += copilotText(item);
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
flush();
|
|
1667
|
+
const callId = item.toolCallId ?? item.invocationId;
|
|
1668
|
+
readTool(result, item.toolId, item.parameters);
|
|
1669
|
+
addToolCall(result, item.toolId ?? item.name, callId, item.parameters, request.timestamp);
|
|
1670
|
+
if (item.resultDetails !== undefined || item.result !== undefined || item.error !== undefined) {
|
|
1671
|
+
addToolResult(result, callId, item.resultDetails ?? item.result ?? item.error, Boolean(item.error));
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
flush();
|
|
1675
|
+
yield* result.events.splice(0);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
async function* editorSourceEvents(archive, { sourceCwd, config, signal }, result) {
|
|
1680
|
+
const copilot = archive.kind === 'copilot';
|
|
1681
|
+
const file = await (copilot ? allowedEditorChat : allowedGemini)(archive, sourceCwd, config);
|
|
1682
|
+
if (!file) {
|
|
1683
|
+
yield { kind: 'gap', reason: 'source-unavailable' };
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
const jsonl = /\.jsonl$/i.test(file);
|
|
1687
|
+
if (!jsonl) {
|
|
1688
|
+
const { row, gap } = await sourceJson(file, signal);
|
|
1689
|
+
if (gap) {
|
|
1690
|
+
yield { kind: 'gap', reason: gap };
|
|
1691
|
+
} else if (copilot && Array.isArray(row?.requests)) {
|
|
1692
|
+
yield* copilotEvent(result, row.requests);
|
|
1693
|
+
} else if (Array.isArray(row?.messages)) {
|
|
1694
|
+
for (const [index, message] of row.messages.entries()) {
|
|
1695
|
+
signal?.throwIfAborted();
|
|
1696
|
+
geminiEvent(result, message, index + 1);
|
|
1697
|
+
yield* result.events.splice(0);
|
|
1698
|
+
}
|
|
1699
|
+
} else {
|
|
1700
|
+
yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1701
|
+
}
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
let state;
|
|
1705
|
+
let index = 0;
|
|
1706
|
+
let uncertain = false;
|
|
1707
|
+
for await (const { row, gap } of sourceJsonl(file, { signal })) {
|
|
1708
|
+
if (gap) {
|
|
1709
|
+
yield { kind: 'gap', reason: gap };
|
|
1710
|
+
} else if (copilot) {
|
|
1711
|
+
if (row.kind === 0) state = row.v;
|
|
1712
|
+
else if (!applyCopilotOp(state, row)) uncertain = true;
|
|
1713
|
+
} else {
|
|
1714
|
+
geminiEvent(result, row, ++index);
|
|
1715
|
+
yield* result.events.splice(0);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
if (copilot) {
|
|
1719
|
+
if (uncertain) yield { kind: 'gap', reason: 'unsupported-incremental-edit' };
|
|
1720
|
+
if (Array.isArray(state?.requests)) yield* copilotEvent(result, state.requests);
|
|
1721
|
+
else yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
export async function* readSourceEvents(archive, options) {
|
|
1726
|
+
const { signal } = options;
|
|
1727
|
+
const result = { events: [], usedSkills: new Set(), readStats: {}, turn: 0, sourceTurns: new Map() };
|
|
1728
|
+
try {
|
|
1729
|
+
signal?.throwIfAborted();
|
|
1730
|
+
if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive?.kind)) {
|
|
1731
|
+
yield* jsonlSourceEvents(archive, options, result);
|
|
1732
|
+
} else if (['opencode', 'agentsview'].includes(archive?.kind) || archive?.kind === 'copilot' && archive.storage === 'sqlite') {
|
|
1733
|
+
yield* databaseSourceEvents(archive, options, result);
|
|
1734
|
+
} else if (['copilot', 'gemini'].includes(archive?.kind)) {
|
|
1735
|
+
yield* editorSourceEvents(archive, options, result);
|
|
1736
|
+
} else {
|
|
1737
|
+
yield { kind: 'gap', reason: 'unsupported-source' };
|
|
1738
|
+
}
|
|
1739
|
+
} catch (error) {
|
|
1740
|
+
signal?.throwIfAborted();
|
|
1741
|
+
yield { kind: 'gap', reason: error.sourceReason ?? 'source-unreadable' };
|
|
1742
|
+
}
|
|
1743
|
+
const { tokens } = result.readStats;
|
|
1744
|
+
if (result.usedSkills.size || tokens) {
|
|
1745
|
+
yield { kind: 'metadata', usedSkills: [...result.usedSkills].sort(), ...(tokens ? { sourceStats: { tokens } } : {}) };
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
export async function probeConversation(archive, options) {
|
|
1750
|
+
let reason;
|
|
1751
|
+
for await (const event of readSourceEvents(archive, options)) {
|
|
1752
|
+
if (event.role === 'user' && ['message', 'attachment'].includes(event.kind)) return { state: 'ready' };
|
|
1753
|
+
if (event.kind === 'gap') reason ??= event.reason;
|
|
1754
|
+
}
|
|
1755
|
+
return reason ? { state: 'unknown', reason } : { state: 'empty' };
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
export async function readConversationHistory(archive, cwd, config) {
|
|
1759
|
+
const result = {
|
|
1760
|
+
messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false,
|
|
1761
|
+
trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
|
|
1762
|
+
readStats: { userMessages: 0, assistantMessages: 0, timedMessages: 0 },
|
|
1763
|
+
};
|
|
1764
|
+
await readHistory(archive, cwd, config, result);
|
|
1765
|
+
const calls = new Map();
|
|
1766
|
+
for (const item of result.trace) {
|
|
1767
|
+
if (item.kind !== 'tool_call') continue;
|
|
1768
|
+
item.status = 'missing';
|
|
1769
|
+
if (item.callId) calls.set(item.callId, item);
|
|
1770
|
+
}
|
|
1771
|
+
for (const item of result.trace) {
|
|
1772
|
+
if (item.kind !== 'tool_result') continue;
|
|
1773
|
+
const call = calls.get(item.callId);
|
|
1774
|
+
item.turnRef = call?.turnRef;
|
|
1775
|
+
if (!call) {
|
|
1776
|
+
result.truncated = true;
|
|
1777
|
+
continue;
|
|
1778
|
+
}
|
|
1779
|
+
call.status = item.status;
|
|
1780
|
+
item.name = call.name;
|
|
1781
|
+
item.turn = call.turn;
|
|
1782
|
+
}
|
|
1783
|
+
if (result.messages[0]?.role === 'assistant' && result.removedQuestion) {
|
|
1784
|
+
// The latest retained replies may belong to a long turn whose question
|
|
1785
|
+
// fell out of the sliding budget. Keep that real question with its replies.
|
|
1786
|
+
const question = result.removedQuestion;
|
|
1787
|
+
while (result.messages.length >= result.limits.messages || result.characters + question.text.length > result.limits.characters) {
|
|
1788
|
+
result.characters -= result.messages.shift().text.length;
|
|
1789
|
+
}
|
|
1790
|
+
result.messages.unshift(question);
|
|
1791
|
+
}
|
|
1792
|
+
const start = result.messages.findIndex(message => message.role === 'user');
|
|
1793
|
+
const retained = start < 0 ? [] : result.messages.slice(start);
|
|
1794
|
+
// The last displayed reply in each source turn is its disclosure anchor.
|
|
1795
|
+
// A turn without a reply is anchored to its own user message.
|
|
1796
|
+
const indexOf = new Map(retained.map((message, index) => [message.turnRef, index]));
|
|
1797
|
+
const trace = result.trace
|
|
1798
|
+
.filter(item => item.turnRef !== undefined && indexOf.has(item.turnRef))
|
|
1799
|
+
.map(({ turnRef, ...item }) => ({ ...item, messageIndex: indexOf.get(turnRef) }))
|
|
1800
|
+
.sort((a, b) => a.turn - b.turn || a.order - b.order);
|
|
1801
|
+
const byMessage = new Map()
|
|
1802
|
+
for (const item of trace) {
|
|
1803
|
+
if (!Number.isInteger(item.messageIndex)) continue;
|
|
1804
|
+
byMessage.set(item.messageIndex, [...(byMessage.get(item.messageIndex) ?? []), item.id]);
|
|
1805
|
+
}
|
|
1806
|
+
const { userMessages, assistantMessages, timedMessages, firstAt, lastAt, tokens } = result.readStats;
|
|
1807
|
+
const sourceStats = {
|
|
1808
|
+
userMessages, assistantMessages, importedMessages: retained.length, partial: result.sourcePartial === true,
|
|
1809
|
+
...(timedMessages >= 2 && timedMessages === userMessages + assistantMessages ? { elapsedMs: lastAt - firstAt } : {}),
|
|
1810
|
+
...(tokens ? { tokens } : {}),
|
|
1811
|
+
};
|
|
1812
|
+
return {
|
|
1813
|
+
messages: retained.map(({ turnRef, ...message }, index) => ({ ...message, ...(byMessage.has(index) ? { traceIds: byMessage.get(index) } : {}) })),
|
|
1814
|
+
trace,
|
|
1815
|
+
sourceStats,
|
|
1816
|
+
usedSkills: [...result.usedSkills].sort(),
|
|
1817
|
+
truncated: result.truncated || start > 0,
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
export async function readProjectHistory(project, config) {
|
|
1822
|
+
const result = { messages: [], usedSkills: new Set() };
|
|
1823
|
+
const archives = project.archives ?? (project.archive ? [project.archive] : []);
|
|
1824
|
+
const ordered = [...archives].filter(item => typeof item?.file === 'string').sort((a, b) => compareDate(b.date, a.date));
|
|
1825
|
+
for (const archive of ordered.slice(0, 12).reverse()) {
|
|
1826
|
+
try { await readHistory(archive, project.cwd, config, result); }
|
|
1827
|
+
catch { continue; }
|
|
1828
|
+
}
|
|
1829
|
+
const seen = new Set();
|
|
1830
|
+
const messages = result.messages.filter(({ role, text, agent }) => {
|
|
1831
|
+
const key = `${agent}\0${role}\0${text}`;
|
|
1832
|
+
if (seen.has(key)) return false;
|
|
1833
|
+
seen.add(key);
|
|
1834
|
+
return true;
|
|
1835
|
+
});
|
|
1836
|
+
return { messages, usedSkills: [...result.usedSkills].sort() };
|
|
1837
|
+
}
|