forked from kenn-io/agentsview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualstudio_copilot.go
More file actions
1782 lines (1679 loc) · 53.7 KB
/
Copy pathvisualstudio_copilot.go
File metadata and controls
1782 lines (1679 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package parser
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"time"
)
// VisualStudioCopilotVirtualPath pairs a trace file with one conversation ID.
// A single physical trace file can hold spans for multiple conversations, so
// each conversation is tracked as its own work item under this virtual path.
func VisualStudioCopilotVirtualPath(tracePath, conversationID string) string {
conversationID = canonicalVisualStudioCopilotConversationID(conversationID)
return VirtualSourcePath(tracePath, conversationID)
}
func canonicalVisualStudioCopilotConversationID(id string) string {
if isVisualStudioCopilotVS2026SessionID(id) {
return strings.ToLower(id)
}
return id
}
func sameVisualStudioCopilotConversationID(a, b string) bool {
return canonicalVisualStudioCopilotConversationID(a) ==
canonicalVisualStudioCopilotConversationID(b)
}
// SplitVisualStudioCopilotVirtualPath splits a <traceFile>#<conversationID>
// virtual source path into its physical trace file and conversation ID. It
// builds on the provider-neutral ParseVirtualSourcePath splitter and adds the
// Visual Studio Copilot validation that the container names a trace file and
// the source ID is a valid conversation ID. It returns ok=false for a plain
// trace-file path. Callers outside the parser package use it to detect and
// resolve the virtual paths Visual Studio Copilot stores for its sessions.
func SplitVisualStudioCopilotVirtualPath(
sourcePath string,
) (tracePath, conversationID string, ok bool) {
return splitVisualStudioCopilotVirtualPath(sourcePath)
}
// IsVisualStudioCopilotTraceFile reports whether path names a Visual Studio
// Copilot OpenTelemetry trace file. Callers outside the parser use it to detect
// a physical trace path whose synced sessions are stored under
// <traceFile>#<conversationID> virtual paths.
func IsVisualStudioCopilotTraceFile(path string) bool {
base := filepath.Base(path)
return strings.HasSuffix(base, ".jsonl") &&
strings.Contains(base, "_VSGitHubCopilot_traces")
}
func isVisualStudioCopilotConversationPath(path string) bool {
return IsVisualStudioCopilotTraceFile(path) ||
isVisualStudioCopilotVS2026SessionPath(path)
}
// IsVisualStudioCopilotVS2026SessionPath reports whether path names a Visual
// Studio 2026 Copilot one-file conversation source.
func IsVisualStudioCopilotVS2026SessionPath(path string) bool {
return isVisualStudioCopilotVS2026SessionPath(path)
}
func isVisualStudioCopilotVS2026SessionPath(path string) bool {
if !isVisualStudioCopilotVS2026SessionFileName(filepath.Base(path)) {
return false
}
parts := strings.Split(filepath.ToSlash(filepath.Dir(path)), "/")
if len(parts) < 4 {
return false
}
return strings.EqualFold(parts[len(parts)-1], "sessions") &&
strings.EqualFold(parts[len(parts)-3], "copilot-chat")
}
func isVisualStudioCopilotVS2026SessionFileName(name string) bool {
return isVisualStudioCopilotVS2026SessionID(name)
}
func isVisualStudioCopilotVS2026SessionID(id string) bool {
if len(id) != 36 {
return false
}
for i, c := range id {
switch i {
case 8, 13, 18, 23:
if c != '-' {
return false
}
default:
if !isVisualStudioCopilotVS2026Hex(c) {
return false
}
}
}
return true
}
func isVisualStudioCopilotVS2026Hex(c rune) bool {
return (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
}
// ResolveSourceFilePath maps a stored session source path to a path that can
// be opened on disk. Visual Studio Copilot stores a
// <traceFile>#<conversationID> virtual path whose conversations share one
// physical trace file, and aider stores a <historyFile>#<runIdx> virtual
// path whose runs share one physical history file, and Windsurf stores a
// <state.vscdb>#<sessionID> virtual path whose chats share one SQLite DB.
// These resolve to the physical source file. Every other agent stores a real
// path, returned unchanged.
func ResolveSourceFilePath(storedPath string) string {
if tracePath, _, ok := splitVisualStudioCopilotVirtualPath(storedPath); ok {
return tracePath
}
if historyPath, _, ok := ParseAiderVirtualPath(storedPath); ok {
return historyPath
}
if dbPath, _, ok := SplitWindsurfVirtualPath(storedPath); ok {
return dbPath
}
return storedPath
}
type vsCopilotTraceLine struct {
ResourceSpans []vsCopilotResourceSpan `json:"resourceSpans"`
}
type vsCopilotResourceSpan struct {
ScopeSpans []vsCopilotScopeSpan `json:"scopeSpans"`
}
type vsCopilotScopeSpan struct {
Spans []vsCopilotSpan `json:"spans"`
}
type vsCopilotSpan struct {
TraceID string `json:"traceId"`
SpanID string `json:"spanId"`
Name string `json:"name"`
StartTimeUnixNano string `json:"startTimeUnixNano"`
EndTimeUnixNano string `json:"endTimeUnixNano"`
Attributes []vsCopilotTraceAttr `json:"attributes"`
attrMap map[string]string `json:"-"`
start time.Time `json:"-"`
end time.Time `json:"-"`
}
type vsCopilotTraceAttr struct {
Key string `json:"key"`
Value vsCopilotTraceValue `json:"value"`
}
type vsCopilotTraceValue struct {
StringValue string `json:"stringValue"`
IntValue string `json:"intValue"`
BoolValue bool `json:"boolValue"`
}
// parseConversation parses one conversation, gathering its spans from the given
// trace file and every sibling trace file in the same directory. File metadata
// is recorded against the conversation's virtual path so that each conversation
// in a shared trace file is tracked independently.
func parseVisualStudioCopilotConversation(
tracePath, conversationID, project, machine string,
) (*ParsedSession, []ParsedMessage, error) {
conversationID = canonicalVisualStudioCopilotConversationID(conversationID)
if conversationID == "" {
return nil, nil, nil
}
if _, err := os.Stat(tracePath); err != nil {
if os.IsNotExist(err) {
return nil, nil, nil
}
return nil, nil, fmt.Errorf("stat %s: %w", tracePath, err)
}
// Fingerprint every sibling trace file before reading spans. A
// conversation's transcript is rebuilt from all siblings, so the stored
// size/mtime must span them; computing it first means a sibling appended
// during the read shows up as a change on the next sync rather than being
// hidden behind a fingerprint that already counts it.
compositeSize, compositeMtime := VisualStudioCopilotTraceFingerprint(
tracePath,
)
spans, err := visualStudioCopilotConversationSpans(tracePath, conversationID)
if err != nil {
return nil, nil, err
}
if len(spans) == 0 {
return nil, nil, nil
}
messages := visualStudioCopilotTraceMessages(spans)
if len(messages) == 0 {
return nil, nil, nil
}
userMessageCount := 0
for _, message := range messages {
if message.Role == RoleUser {
userMessageCount++
}
}
startedAt, endedAt := visualStudioCopilotTraceBounds(spans)
firstMessage := visualStudioCopilotTraceFirstMessage(
spans, conversationID,
)
sess := &ParsedSession{
ID: "visualstudio-copilot:" + conversationID,
Agent: AgentVSCopilot,
Project: project,
Machine: machine,
FirstMessage: firstMessage,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: userMessageCount,
File: FileInfo{
Path: VisualStudioCopilotVirtualPath(tracePath, conversationID),
Size: compositeSize,
Mtime: compositeMtime,
},
}
accumulateMessageTokenUsage(sess, messages)
return sess, messages, nil
}
// visualStudioCopilotConversationSpans gathers every span for one conversation
// from the given trace file plus its sibling trace files. A read error on the
// primary trace file or on any sibling is returned so the caller can surface it
// as a sync failure. Because a conversation's spans can live in any sibling and
// sessions are written with full message replacement, reconstructing from only
// the readable subset would overwrite an indexed conversation with a partial
// transcript, so a transient unreadable sibling must fail the parse instead.
func visualStudioCopilotConversationSpans(
tracePath, conversationID string,
) ([]vsCopilotSpan, error) {
own, err := readVisualStudioCopilotTraceSpans(tracePath)
if err != nil {
return nil, err
}
var spans []vsCopilotSpan
for _, span := range own {
if sameVisualStudioCopilotConversationID(
span.attrMap["gen_ai.conversation.id"], conversationID,
) {
spans = append(spans, span)
}
}
siblingSpans, err := visualStudioCopilotSiblingTraceSpans(
tracePath, conversationID,
)
if err != nil {
return nil, err
}
spans = append(spans, siblingSpans...)
return spans, nil
}
// VisualStudioCopilotFileConversationIDs returns the distinct conversation IDs
// that appear in a single trace file, in first-seen order. A read or scan error
// is returned rather than reported as an empty file, so callers do not mistake
// an unreadable file for one with no conversations.
func VisualStudioCopilotFileConversationIDs(path string) ([]string, error) {
spans, err := readVisualStudioCopilotTraceSpans(path)
if err != nil {
return nil, err
}
seen := map[string]struct{}{}
var ids []string
for _, span := range spans {
id := canonicalVisualStudioCopilotConversationID(
span.attrMap["gen_ai.conversation.id"],
)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
return ids, nil
}
// WriteVisualStudioCopilotConversationJSONL streams the trace data for one
// conversation across every sibling trace file in the representative trace's
// directory, since a conversation's spans can be split across rotated trace
// files. VS 2026 session-file paths already point at one conversation file, so
// they are filtered and exported directly. From each file it emits only the
// spans whose gen_ai.conversation.id matches the requested conversation: a line
// is written verbatim when all of its spans already belong to that
// conversation, otherwise it is re-encoded with only the matching spans so a
// batched OTLP line cannot disclose another conversation's or an id-less span's
// prompts, tool arguments, command output, or secrets. A sibling that vanished
// between listing and open is skipped; any other read error is returned. When
// no trace file in the directory contains the conversation (e.g. the
// representative trace was rotated away and no sibling holds it), it returns an
// os.ErrNotExist-wrapped error rather than succeeding with empty output, so
// callers can report a clear not-found error.
func WriteVisualStudioCopilotConversationJSONL(
w io.Writer, tracePath, conversationID string,
) error {
if isVisualStudioCopilotVS2026SessionPath(tracePath) {
written, err := writeVisualStudioCopilotConversationFile(
w, tracePath, conversationID,
)
if err != nil {
return err
}
if written == 0 {
return fmt.Errorf(
"conversation %s not found in %s: %w",
conversationID, tracePath, os.ErrNotExist,
)
}
return nil
}
files, err := visualStudioCopilotSiblingTraceFiles(tracePath)
if err != nil {
return err
}
written := 0
for _, file := range files {
n, err := writeVisualStudioCopilotConversationFile(
w, file, conversationID,
)
written += n
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
}
}
if written == 0 {
return fmt.Errorf(
"conversation %s not found in %s: %w",
conversationID, filepath.Dir(tracePath), os.ErrNotExist,
)
}
return nil
}
func writeVisualStudioCopilotConversationFile(
w io.Writer, path, conversationID string,
) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, fmt.Errorf("read %s: %w", path, err)
}
defer f.Close()
written := 0
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 256*1024*1024)
for scanner.Scan() {
out, emit := visualStudioCopilotConversationLine(
scanner.Bytes(), conversationID,
)
if !emit {
continue
}
if _, err := w.Write(out); err != nil {
return written, err
}
if _, err := io.WriteString(w, "\n"); err != nil {
return written, err
}
written++
}
if err := scanner.Err(); err != nil {
return written, fmt.Errorf("scan %s: %w", path, err)
}
return written, nil
}
// visualStudioCopilotConversationLine returns the bytes to export for one trace
// line, keeping only spans for conversationID. It returns (line, true) verbatim
// when every span already belongs to the conversation, a re-encoded line when
// some spans were dropped, or (nil, false) when no span matches or the line
// cannot be parsed. Container objects are decoded into raw messages so that
// re-encoding preserves every field of the spans that are kept.
func visualStudioCopilotConversationLine(
line []byte, conversationID string,
) ([]byte, bool) {
conversationID = canonicalVisualStudioCopilotConversationID(conversationID)
var top map[string]json.RawMessage
if err := json.Unmarshal(line, &top); err != nil {
return nil, false
}
rsRaw, ok := top["resourceSpans"]
if !ok {
return nil, false
}
var resourceSpans []json.RawMessage
if err := json.Unmarshal(rsRaw, &resourceSpans); err != nil {
return nil, false
}
kept, matched, modified := visualStudioCopilotFilterArray(
resourceSpans, conversationID, visualStudioCopilotFilterResourceSpan,
)
if !matched {
return nil, false
}
if !modified {
return line, true
}
rsBytes, err := json.Marshal(kept)
if err != nil {
return nil, false
}
top["resourceSpans"] = rsBytes
out, err := json.Marshal(top)
if err != nil {
return nil, false
}
return out, true
}
// visualStudioCopilotFilterArray applies a per-element filter to a decoded array
// of OTLP container objects. It reports whether any element matched the
// conversation and whether the array changed (an element was dropped or
// rewritten). A nil element returned by filter is treated as dropped.
func visualStudioCopilotFilterArray(
items []json.RawMessage,
conversationID string,
filter func(json.RawMessage, string) (json.RawMessage, bool, bool),
) ([]json.RawMessage, bool, bool) {
kept := make([]json.RawMessage, 0, len(items))
matched, modified := false, false
for _, item := range items {
out, m, mod := filter(item, conversationID)
matched = matched || m
modified = modified || mod || out == nil
if out == nil {
continue
}
kept = append(kept, out)
}
return kept, matched, modified
}
func visualStudioCopilotFilterResourceSpan(
rs json.RawMessage, conversationID string,
) (json.RawMessage, bool, bool) {
var m map[string]json.RawMessage
if err := json.Unmarshal(rs, &m); err != nil {
return nil, false, true
}
ssRaw, ok := m["scopeSpans"]
if !ok {
return nil, false, true
}
var scopeSpans []json.RawMessage
if err := json.Unmarshal(ssRaw, &scopeSpans); err != nil {
return nil, false, true
}
kept, matched, modified := visualStudioCopilotFilterArray(
scopeSpans, conversationID, visualStudioCopilotFilterScopeSpan,
)
if len(kept) == 0 {
return nil, matched, true
}
if !modified {
return rs, matched, false
}
ssBytes, err := json.Marshal(kept)
if err != nil {
return nil, false, true
}
m["scopeSpans"] = ssBytes
out, err := json.Marshal(m)
if err != nil {
return nil, false, true
}
return out, matched, true
}
func visualStudioCopilotFilterScopeSpan(
ss json.RawMessage, conversationID string,
) (json.RawMessage, bool, bool) {
var m map[string]json.RawMessage
if err := json.Unmarshal(ss, &m); err != nil {
return nil, false, true
}
spansRaw, ok := m["spans"]
if !ok {
return nil, false, true
}
var spans []json.RawMessage
if err := json.Unmarshal(spansRaw, &spans); err != nil {
return nil, false, true
}
kept := make([]json.RawMessage, 0, len(spans))
modified := false
for _, sp := range spans {
if sameVisualStudioCopilotConversationID(
visualStudioCopilotSpanConversationID(sp), conversationID,
) {
kept = append(kept, sp)
} else {
modified = true
}
}
if len(kept) == 0 {
return nil, false, true
}
if !modified {
return ss, true, false
}
spansBytes, err := json.Marshal(kept)
if err != nil {
return nil, false, true
}
m["spans"] = spansBytes
out, err := json.Marshal(m)
if err != nil {
return nil, false, true
}
return out, true, true
}
// visualStudioCopilotSpanConversationID extracts a span's gen_ai.conversation.id
// attribute, returning "" when the span carries no conversation id. An id-less
// span never matches a requested conversation, so it is dropped from exports.
func visualStudioCopilotSpanConversationID(span json.RawMessage) string {
var s struct {
Attributes []vsCopilotTraceAttr `json:"attributes"`
}
if err := json.Unmarshal(span, &s); err != nil {
return ""
}
for _, attr := range s.Attributes {
if attr.Key == "gen_ai.conversation.id" {
return canonicalVisualStudioCopilotConversationID(
attr.Value.StringValue,
)
}
}
return ""
}
func readVisualStudioCopilotTraceSpans(
path string,
) ([]vsCopilotSpan, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("read %s: %w", path, err)
}
defer f.Close()
var spans []vsCopilotSpan
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 256*1024*1024)
lineNo := 0
for scanner.Scan() {
lineNo++
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
var trace vsCopilotTraceLine
if err := json.Unmarshal([]byte(line), &trace); err != nil {
return nil, fmt.Errorf(
"decode %s line %d: %w", path, lineNo, err,
)
}
for _, resourceSpan := range trace.ResourceSpans {
for _, scopeSpan := range resourceSpan.ScopeSpans {
for _, span := range scopeSpan.Spans {
span.attrMap = vsCopilotTraceAttrs(span.Attributes)
span.start = parseUnixNano(span.StartTimeUnixNano)
span.end = parseUnixNano(span.EndTimeUnixNano)
if span.attrMap["gen_ai.conversation.id"] == "" {
continue
}
spans = append(spans, span)
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scan %s: %w", path, err)
}
return spans, nil
}
// visualStudioCopilotSiblingTraceSpans collects spans for one conversation from
// every sibling trace file in the directory. Any sibling read error is returned,
// including a sibling that vanished between directory listing and open: because
// sessions are written with full message replacement, reconstructing from the
// readable subset would overwrite an indexed conversation with a partial
// transcript and drop archived messages, so an incomplete read must fail the
// parse and be retried instead. Once the file is permanently gone it no longer
// appears in the listing, so the next parse succeeds and archive preservation in
// the sync engine guards the stored transcript.
func visualStudioCopilotSiblingTraceSpans(
path, conversationID string,
) ([]vsCopilotSpan, error) {
siblings, err := visualStudioCopilotSiblingTraceFiles(path)
if err != nil {
return nil, err
}
var spans []vsCopilotSpan
for _, sibling := range siblings {
if sibling == path {
continue
}
candidateSpans, err := readVisualStudioCopilotTraceSpans(sibling)
if err != nil {
return nil, err
}
for _, span := range candidateSpans {
if sameVisualStudioCopilotConversationID(
span.attrMap["gen_ai.conversation.id"], conversationID,
) {
spans = append(spans, span)
}
}
}
return spans, nil
}
// visualStudioCopilotSiblingTraceFiles lists the trace files in a trace file's
// directory. A directory read error is returned rather than swallowed: silently
// treating it as "no siblings" would let the primary trace be reconstructed and
// written as a complete session even though sibling enumeration failed,
// defeating the partial-transcript guard.
func visualStudioCopilotSiblingTraceFiles(path string) ([]string, error) {
dir := filepath.Dir(path)
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("read dir %s: %w", dir, err)
}
files := make([]string, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !IsVisualStudioCopilotTraceFile(entry.Name()) {
continue
}
files = append(files, filepath.Join(dir, entry.Name()))
}
sort.Strings(files)
return files, nil
}
// VisualStudioCopilotTraceFingerprint returns a composite size and mtime
// (nanoseconds) spanning every Visual Studio Copilot trace file in the
// directory holding tracePath. A conversation's transcript is rebuilt from all
// sibling trace files, so a skip fingerprint keyed only on the representative
// trace file would miss spans appended to, rotated into, or removed from a
// sibling. Summing sizes and taking the maximum mtime makes the fingerprint
// change on any of those events. It falls back to the single file's stat when
// the directory cannot be listed.
func VisualStudioCopilotTraceFingerprint(
tracePath string,
) (size, mtime int64) {
if isVisualStudioCopilotVS2026SessionPath(tracePath) {
if info, err := os.Stat(tracePath); err == nil {
return info.Size(), info.ModTime().UnixNano()
}
return 0, 0
}
size, mtime, err := visualStudioCopilotTraceFingerprint(tracePath, false)
if err != nil {
if info, statErr := os.Stat(tracePath); statErr == nil {
return info.Size(), info.ModTime().UnixNano()
}
return 0, 0
}
return size, mtime
}
// VisualStudioCopilotTraceFingerprintStrict is like
// VisualStudioCopilotTraceFingerprint but returns any directory-enumeration or
// per-sibling stat error instead of falling back to the representative file's
// stat or skipping an unstattable sibling. Sync skip checks use it so a read
// error surfaces and is retried rather than being mistaken for an "unchanged"
// fingerprint: when the readable files still match the stored composite, a
// transient ReadDir or stat failure would otherwise be cached as a skip and
// leave the session stale. The best-effort fallback stays for display-only paths
// such as SourceMtime.
func VisualStudioCopilotTraceFingerprintStrict(
tracePath string,
) (size, mtime int64, err error) {
if isVisualStudioCopilotVS2026SessionPath(tracePath) {
info, err := os.Stat(tracePath)
if err != nil {
return 0, 0, err
}
return info.Size(), info.ModTime().UnixNano(), nil
}
return visualStudioCopilotTraceFingerprint(tracePath, true)
}
func visualStudioCopilotTraceFingerprint(
tracePath string, strict bool,
) (size, mtime int64, err error) {
siblings, err := visualStudioCopilotSiblingTraceFiles(tracePath)
if err != nil {
return 0, 0, err
}
for _, sibling := range siblings {
info, statErr := os.Stat(sibling)
if statErr != nil {
if strict {
return 0, 0, statErr
}
continue
}
size += info.Size()
if m := info.ModTime().UnixNano(); m > mtime {
mtime = m
}
}
return size, mtime, nil
}
func vsCopilotTraceAttrs(
attrs []vsCopilotTraceAttr,
) map[string]string {
out := make(map[string]string, len(attrs))
for _, attr := range attrs {
value := attr.Value.StringValue
if value == "" && attr.Value.IntValue != "" {
value = attr.Value.IntValue
}
out[attr.Key] = value
}
return out
}
func visualStudioCopilotTraceMessages(
spans []vsCopilotSpan,
) []ParsedMessage {
sort.SliceStable(spans, func(i, j int) bool {
return spans[i].start.Before(spans[j].start)
})
executedToolIDs := visualStudioCopilotExecutedToolIDs(spans)
preferredToolSpans := visualStudioCopilotPreferredToolSpans(spans)
preferredChatSpans := visualStudioCopilotPreferredChatSpans(
spans, executedToolIDs,
)
preferredChatUsage := visualStudioCopilotPreferredChatUsageSpans(
spans, executedToolIDs, preferredChatSpans,
)
messages := make([]ParsedMessage, 0, len(spans))
fallbackMessages := make([]ParsedMessage, 0, len(spans))
seenUserPrompts := map[string]struct{}{}
seenChatOutputs := map[string]struct{}{}
seenChatUsage := map[string]struct{}{}
seenToolSpans := map[string]struct{}{}
for _, span := range spans {
if prompt := visualStudioCopilotChatPrompt(span); prompt != "" {
promptKey := visualStudioCopilotPromptKey(span, prompt)
if _, seen := seenUserPrompts[promptKey]; !seen {
messages = append(messages, ParsedMessage{
Ordinal: len(messages),
Role: RoleUser,
Content: prompt,
Timestamp: span.start,
ContentLength: len(prompt),
})
seenUserPrompts[promptKey] = struct{}{}
}
if content, toolCalls := visualStudioCopilotChatOutput(span, executedToolIDs); content != "" || len(toolCalls) > 0 {
messages = visualStudioCopilotAppendChatOutput(
messages, seenChatOutputs, span, content, toolCalls,
preferredChatSpans, executedToolIDs,
)
} else {
messages = visualStudioCopilotAppendChatTurnUsage(
messages, seenChatUsage, span,
preferredChatSpans, preferredChatUsage,
)
}
continue
}
if content, toolCalls := visualStudioCopilotChatOutput(span, executedToolIDs); content != "" || len(toolCalls) > 0 {
messages = visualStudioCopilotAppendChatOutput(
messages, seenChatOutputs, span, content, toolCalls,
preferredChatSpans, executedToolIDs,
)
continue
}
contentSpan, toolKey := visualStudioCopilotToolEmission(
span, preferredToolSpans,
)
if _, seen := seenToolSpans[toolKey]; seen {
continue
}
content, toolCalls := visualStudioCopilotTraceContent(contentSpan)
if content == "" && len(toolCalls) == 0 {
continue
}
seenToolSpans[toolKey] = struct{}{}
message := ParsedMessage{
Role: RoleAssistant,
Content: content,
// Anchor the timestamp to the span being iterated, which sets
// this message's ordinal via append order. The content may come
// from a more complete duplicate encountered later, but timing
// the message by that later copy would let it jump ahead of
// intervening messages.
Timestamp: span.start,
HasToolUse: len(toolCalls) > 0,
ContentLength: len(content),
ToolCalls: toolCalls,
}
visualStudioCopilotApplyUsage(&message, contentSpan)
if message.HasToolUse {
message.Ordinal = len(messages)
messages = append(messages, message)
} else {
message.Ordinal = len(fallbackMessages)
fallbackMessages = append(fallbackMessages, message)
}
}
if len(messages) == 0 {
return fallbackMessages
}
return messages
}
// visualStudioCopilotAppendChatOutput appends one assistant message for a chat
// turn, skipping turns already emitted. A single conversation can be split
// across sibling trace files and a streaming chat span can be flushed to more
// than one file with a growing payload, so the turn is keyed on span identity
// and emitted from its richest copy. This prevents duplicate assistant messages
// and double-counted token usage while keeping the complete content and tool
// calls. The message is positioned by the iterated span so a later, richer copy
// supplies content without reordering the transcript.
func visualStudioCopilotAppendChatOutput(
messages []ParsedMessage, seen map[string]struct{},
span vsCopilotSpan, content string, toolCalls []ParsedToolCall,
preferred map[string]vsCopilotSpan, executedToolIDs map[string]struct{},
) []ParsedMessage {
key := visualStudioCopilotChatOutputIdentity(span, content)
if _, ok := seen[key]; ok {
return messages
}
seen[key] = struct{}{}
emitSpan := span
if best, ok := preferred[key]; ok {
emitSpan = best
content, toolCalls = visualStudioCopilotChatOutput(best, executedToolIDs)
}
message := ParsedMessage{
Ordinal: len(messages),
Role: RoleAssistant,
Content: content,
Timestamp: span.end,
HasToolUse: len(toolCalls) > 0,
ContentLength: len(content),
ToolCalls: toolCalls,
}
visualStudioCopilotApplyUsage(&message, emitSpan)
return append(messages, message)
}
// visualStudioCopilotChatOutputIdentity identifies a chat turn for
// deduplication. Real spans carry trace and span IDs that stay stable across
// the sibling files one span is flushed to, so keying on identity collapses
// every flush of a turn to a single message regardless of how complete each
// copy was. Only when both IDs are absent does the output content key the
// entry, keeping genuinely distinct turns separate.
func visualStudioCopilotChatOutputIdentity(span vsCopilotSpan, content string) string {
if span.TraceID != "" || span.SpanID != "" {
return "id:" + span.TraceID + ":" + span.SpanID
}
return "content:" + content
}
// visualStudioCopilotPreferredChatSpans chooses one chat-output span per stable
// identity. A streaming chat span can be flushed to several sibling trace files
// with a growing payload, so the richest copy wins and the turn emits once with
// complete content, tool calls, and token usage rather than once per flush.
func visualStudioCopilotPreferredChatSpans(
spans []vsCopilotSpan, executedToolIDs map[string]struct{},
) map[string]vsCopilotSpan {
best := map[string]vsCopilotSpan{}
for _, span := range spans {
content, toolCalls := visualStudioCopilotChatOutput(span, executedToolIDs)
if content == "" && len(toolCalls) == 0 {
continue
}
key := visualStudioCopilotChatOutputIdentity(span, content)
if current, ok := best[key]; !ok ||
visualStudioCopilotPreferChatSpan(span, current, executedToolIDs) {
best[key] = span
}
}
return best
}
// visualStudioCopilotPreferChatSpan reports whether candidate carries a more
// complete chat output than current: more tool calls win, then longer text,
// then more complete token usage, then the later flush. The usage tie-breaker
// keeps two flushes with identical visible output from applying the leaner
// usage copy, which would undercount the turn's tokens.
func visualStudioCopilotPreferChatSpan(
candidate, current vsCopilotSpan, executedToolIDs map[string]struct{},
) bool {
candidateContent, candidateTools := visualStudioCopilotChatOutput(
candidate, executedToolIDs,
)
currentContent, currentTools := visualStudioCopilotChatOutput(
current, executedToolIDs,
)
if len(candidateTools) != len(currentTools) {
return len(candidateTools) > len(currentTools)
}
if len(candidateContent) != len(currentContent) {
return len(candidateContent) > len(currentContent)
}
return visualStudioCopilotPreferUsageSpan(candidate, current)
}
// visualStudioCopilotAppendChatTurnUsage records token usage for a chat turn
// whose only output is executed tool calls, which are shown via their
// execute_tool spans. Without this, the LLM turn that produced those calls -
// and its token usage and model - would be dropped from the transcript and
// usage totals. The turn is keyed on span identity and emitted once; a turn
// that produced visible output elsewhere already carries its usage on that
// message, so it is skipped here. Turns carrying no usage add nothing.
func visualStudioCopilotAppendChatTurnUsage(
messages []ParsedMessage, seen map[string]struct{},
span vsCopilotSpan, preferred, preferredUsage map[string]vsCopilotSpan,
) []ParsedMessage {
key := visualStudioCopilotChatOutputIdentity(span, "")
if _, ok := preferred[key]; ok {
return messages
}
if _, ok := seen[key]; ok {
return messages
}
usageSpan := span
if best, ok := preferredUsage[key]; ok {
usageSpan = best
}
if !visualStudioCopilotSpanHasUsage(usageSpan) {
return messages
}
seen[key] = struct{}{}
content := visualStudioCopilotChatSummary(usageSpan)
message := ParsedMessage{
Ordinal: len(messages),
Role: RoleAssistant,
Content: content,
Timestamp: span.end,
ContentLength: len(content),
}
visualStudioCopilotApplyUsage(&message, usageSpan)
return append(messages, message)
}
// visualStudioCopilotPreferredChatUsageSpans chooses, per chat identity with no
// visible output, the span carrying the most complete token usage. A tool-only
// chat turn can be flushed to several sibling files with growing token counts,
// so the richest copy wins and the turn's usage is recorded once and in full
// rather than from whichever partial copy was seen first.
func visualStudioCopilotPreferredChatUsageSpans(
spans []vsCopilotSpan, executedToolIDs map[string]struct{},
visibleOutput map[string]vsCopilotSpan,
) map[string]vsCopilotSpan {
best := map[string]vsCopilotSpan{}
for _, span := range spans {
if !visualStudioCopilotIsChatSpan(span) {
continue
}
content, toolCalls := visualStudioCopilotChatOutput(span, executedToolIDs)
if content != "" || len(toolCalls) > 0 {
continue
}
if !visualStudioCopilotSpanHasUsage(span) {
continue
}
key := visualStudioCopilotChatOutputIdentity(span, "")
if _, ok := visibleOutput[key]; ok {
continue
}