-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate_codex_data.go
More file actions
2088 lines (1942 loc) · 59.3 KB
/
generate_codex_data.go
File metadata and controls
2088 lines (1942 loc) · 59.3 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 main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/tidwall/gjson"
)
const cacheVersion = 6
const minReadableCacheVersion = 4
// Usage mirrors the token fields emitted by Codex token_count events.
// Total is kept from the log when present; it is not recomputed from the
// other fields because Codex may define totals differently across versions.
type Usage struct {
Input int64 `json:"input_tokens"`
Cached int64 `json:"cached_input_tokens"`
Output int64 `json:"output_tokens"`
Reasoning int64 `json:"reasoning_output_tokens"`
Total int64 `json:"total_tokens"`
}
type UsageEvent struct {
Ts string `json:"ts"`
Sid string `json:"sid"`
Usage Usage `json:"usage"`
Model string `json:"model"`
Snapshot Usage `json:"snapshot,omitempty"`
HasSnapshot bool `json:"hasSnapshot,omitempty"`
}
type CompletionEvent struct {
Ts string `json:"ts"`
Sid string `json:"sid"`
Model string `json:"model"`
DurationMs int64 `json:"duration_ms,omitempty"`
TTFBMs int64 `json:"ttfb_ms,omitempty"`
}
type FailureEvent struct {
Ts string `json:"ts"`
Sid string `json:"sid"`
Model string `json:"model"`
}
// ParsedFile is the minimal metadata retained from one JSONL session file.
// Prompt text, assistant text, tool output, and file contents are intentionally
// not copied into this structure.
type ParsedFile struct {
Sid string `json:"sid,omitempty"`
File string `json:"file,omitempty"`
Cwd string `json:"cwd,omitempty"`
Model string `json:"model,omitempty"`
UsageEvents []UsageEvent `json:"usageEvents,omitempty"`
CompletionEvents []CompletionEvent `json:"completionEvents,omitempty"`
FailureEvents []FailureEvent `json:"failureEvents,omitempty"`
LatestLimits map[string]any `json:"latestLimits,omitempty"`
LatestLimitsTs string `json:"latestLimitsTs,omitempty"`
LastTotal Usage `json:"lastTotal,omitempty"`
HasLastTotal bool `json:"hasLastTotal,omitempty"`
}
type FileCache struct {
MtimeNs int64 `json:"mtimeNs"`
Size int64 `json:"size"`
Parsed ParsedFile `json:"parsed"`
}
type CachePayload struct {
Version int `json:"version"`
WindowDays int `json:"windowDays"`
Files map[string]FileCache `json:"files"`
}
type SessionStats struct {
Sid string
File string
Cwd string
Model string
StartedAt time.Time
EndedAt time.Time
DurationMs int64
TTFBMs int64
TTFBCount int64
Calls int64
Completions int64
Failures int64
Usage Usage
}
type RuntimeEvent struct {
Ts time.Time
Sid string
Usage Usage
Model string
}
type RuntimeTTFBEvent struct {
Ts time.Time
Sid string
Model string
TTFBMs int64
}
type RuntimeFailureEvent struct {
Ts time.Time
Sid string
Model string
}
type LoadedData struct {
Sessions []SessionStats
Events []RuntimeEvent
Limits map[string]any
TTFBEvents []RuntimeTTFBEvent
FailureEvents []RuntimeFailureEvent
}
type CostSummary struct {
Input float64
Cached float64
Output float64
Reasoning float64
Total float64
PricedTokens int64
UnpricedTokens int64
}
type RawExportPayload struct {
SchemaVersion any `json:"schemaVersion"`
RawSchemaVersion int `json:"rawSchemaVersion"`
Catalog any `json:"catalog"`
RecordBase any `json:"recordBase"`
RecordsV2 any `json:"recordsV2"`
TTFBRecordsV2 any `json:"ttfbRecordsV2"`
FailureRecordsV2 any `json:"failureRecordsV2"`
}
type bucketAccumulator struct {
start time.Time
end time.Time
usage Usage
calls int64
cost CostSummary
}
type rangeBucketSet struct {
start time.Time
end time.Time
step time.Duration
alignedStartMs int64
stepMs int64
buckets []bucketAccumulator
}
type peakWindowItem struct {
ts time.Time
tokens int64
}
type peakWindowAccumulator struct {
window time.Duration
items []peakWindowItem
left int
total int64
peakTotal int64
peakTs time.Time
hasPeak bool
}
type pricingRule struct {
label string
patterns []string
input float64
cached float64
output float64
}
type PricingRuleExport struct {
Label string `json:"label"`
Patterns []string `json:"patterns"`
Input float64 `json:"input"`
Cached float64 `json:"cached"`
Output float64 `json:"output"`
}
type sessionFileCandidate struct {
path string
mtimeNs int64
size int64
}
type parsedSessionFile struct {
file sessionFileCandidate
parsed ParsedFile
}
func parseTime(value string) (time.Time, bool) {
if value == "" {
return time.Time{}, false
}
ts, err := time.Parse(time.RFC3339Nano, value)
if err == nil {
return ts, true
}
if strings.HasSuffix(value, "+00:00") {
ts, err = time.Parse(time.RFC3339Nano, strings.TrimSuffix(value, "+00:00")+"Z")
}
if err != nil {
return time.Time{}, false
}
return ts, true
}
func isoTime(value time.Time, ok bool) string {
if !ok || value.IsZero() {
return ""
}
return value.UTC().Format(time.RFC3339Nano)
}
func rateLimitPriority(limits map[string]any) int {
if limits == nil {
return -1
}
limitID := strings.ToLower(strings.TrimSpace(stringValue(limits, "limit_id")))
limitName := strings.TrimSpace(stringValue(limits, "limit_name"))
switch {
case limitID == "codex":
return 100
case limitID != "" && limitName == "":
return 80
case limitID != "" || limitName != "":
return 50
default:
return 10
}
}
func preferRateLimits(candidate map[string]any, candidateTs time.Time, hasCandidateTs bool, current map[string]any, currentTs time.Time, hasCurrentTs bool) bool {
if candidate == nil {
return false
}
if current == nil {
return true
}
candidatePriority := rateLimitPriority(candidate)
currentPriority := rateLimitPriority(current)
if candidatePriority != currentPriority {
return candidatePriority > currentPriority
}
if !hasCurrentTs {
return true
}
if !hasCandidateTs {
return false
}
return !candidateTs.Before(currentTs)
}
func fmtInt(value int64) string {
abs := math.Abs(float64(value))
switch {
case abs >= 1_000_000_000:
return fmt.Sprintf("%.2fB", float64(value)/1_000_000_000)
case abs >= 1_000_000:
return fmt.Sprintf("%.2fM", float64(value)/1_000_000)
case abs >= 1_000:
return fmt.Sprintf("%.0fK", math.Round(float64(value)/1_000))
default:
return fmt.Sprintf("%d", value)
}
}
func displayTime(ts time.Time, ok bool) string {
if !ok || ts.IsZero() {
return "--"
}
return ts.Local().Format("15:04")
}
func projectName(cwd, fallback string) string {
if cwd == "" {
return fallback
}
name := strings.TrimSpace(filepath.Base(cwd))
if name == "" || name == "." || name == string(filepath.Separator) {
return fallback
}
return name
}
func number(value any) (float64, bool) {
finite := func(v float64) bool {
return !math.IsNaN(v) && !math.IsInf(v, 0)
}
switch v := value.(type) {
case float64:
return v, finite(v)
case int:
return float64(v), true
case int64:
return float64(v), true
case json.Number:
f, err := v.Float64()
return f, err == nil && finite(f)
default:
return 0, false
}
}
func usageSnapshot(value any) (Usage, bool) {
values, ok := value.(map[string]any)
if !ok {
return Usage{}, false
}
var usage Usage
hasValue := false
read := func(key string) int64 {
raw, ok := number(values[key])
if !ok {
return 0
}
hasValue = true
if raw < 0 {
return 0
}
return int64(raw)
}
usage.Input = read("input_tokens")
usage.Cached = read("cached_input_tokens")
usage.Output = read("output_tokens")
usage.Reasoning = read("reasoning_output_tokens")
usage.Total = read("total_tokens")
return usage, hasValue
}
func usageSnapshotResult(value gjson.Result) (Usage, bool) {
if !value.Exists() || !value.IsObject() {
return Usage{}, false
}
hasValue := false
read := func(key string) int64 {
result := value.Get(key)
if !result.Exists() {
return 0
}
hasValue = true
raw := result.Int()
if raw < 0 {
return 0
}
return raw
}
usage := Usage{
Input: read("input_tokens"),
Cached: read("cached_input_tokens"),
Output: read("output_tokens"),
Reasoning: read("reasoning_output_tokens"),
Total: read("total_tokens"),
}
return usage, hasValue
}
func addUsage(dst *Usage, src Usage) {
dst.Input += src.Input
dst.Cached += src.Cached
dst.Output += src.Output
dst.Reasoning += src.Reasoning
dst.Total += src.Total
}
func usageDelta(current, previous Usage) (Usage, bool) {
// Codex often reports cumulative total_token_usage. The dashboard needs
// per-event usage, so subtract the previous total and clamp negative values
// to tolerate log rewrites or counter resets.
usage := Usage{
Input: max64(0, current.Input-previous.Input),
Cached: max64(0, current.Cached-previous.Cached),
Output: max64(0, current.Output-previous.Output),
Reasoning: max64(0, current.Reasoning-previous.Reasoning),
Total: max64(0, current.Total-previous.Total),
}
return usage, usage.Input != 0 || usage.Cached != 0 || usage.Output != 0 || usage.Reasoning != 0 || usage.Total != 0
}
func usageSnapshotKey(sid, model string, usage Usage) string {
return fmt.Sprintf("%s\x00%s\x00%d\x00%d\x00%d\x00%d\x00%d",
sid, model, usage.Input, usage.Cached, usage.Output, usage.Reasoning, usage.Total)
}
func max64(a, b int64) int64 {
if a > b {
return a
}
return b
}
func safePercent(value any) *float64 {
raw, ok := number(value)
if !ok {
return nil
}
if raw < 0 {
raw = 0
}
if raw > 100 {
raw = 100
}
return &raw
}
func clampPercentValue(value float64) float64 {
if value < 0 {
return 0
}
if value > 100 {
return 100
}
return value
}
func successFailureRates(calls int64, failures int) (float64, float64) {
if calls <= 0 {
if failures > 0 {
return 0, 100
}
return 100, 0
}
failureRate := clampPercentValue(float64(failures) / float64(calls) * 100)
return 100 - failureRate, failureRate
}
func cutoffForDays(days int, now time.Time) time.Time {
if days <= 0 {
return time.Time{}
}
return now.Add(-time.Duration(days) * 24 * time.Hour)
}
func localDayStart(value time.Time) time.Time {
local := value.Local()
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, local.Location())
}
func ymd(value time.Time) string {
return value.Local().Format("2006-01-02")
}
func formatRangeLabel(start, end time.Time, preset string) string {
switch preset {
case "24h":
return "最近24小时"
case "today":
return "今天"
case "7":
return "7天内"
case "30":
return "30天内"
case "history":
return "历史总览"
default:
return fmt.Sprintf("%s 至 %s", ymd(start), ymd(end.Add(-time.Millisecond)))
}
}
func cacheCoversDays(cachedDays int, requestedDays int) bool {
if requestedDays <= 0 {
return cachedDays <= 0
}
if cachedDays <= 0 {
return true
}
return cachedDays >= requestedDays
}
func loadCache(cachePath string, days int) map[string]FileCache {
// A cache generated for a shorter window cannot safely answer a longer one
// because older files may have been skipped. Older readable cache versions
// can still serve unchanged files; they just miss newer append-only metadata.
if cachePath == "" {
return map[string]FileCache{}
}
body, err := os.ReadFile(cachePath)
if err != nil {
return map[string]FileCache{}
}
var payload CachePayload
if err := json.Unmarshal(body, &payload); err != nil {
return map[string]FileCache{}
}
if payload.Version < minReadableCacheVersion || payload.Version > cacheVersion || !cacheCoversDays(payload.WindowDays, days) || payload.Files == nil {
return map[string]FileCache{}
}
return payload.Files
}
func writeCache(cachePath string, days int, files map[string]FileCache) {
// Write through a temporary file so an interrupted run does not leave a
// partially-written cache that would poison later hot starts.
if cachePath == "" {
return
}
dir := filepath.Dir(cachePath)
if dir != "." && dir != "" {
_ = os.MkdirAll(dir, 0o755)
}
payload := CachePayload{Version: cacheVersion, WindowDays: days, Files: files}
body, err := json.Marshal(payload)
if err != nil {
return
}
tmp, err := os.CreateTemp(dir, filepath.Base(cachePath)+".*.tmp")
if err != nil {
return
}
tmpName := tmp.Name()
defer os.Remove(tmpName)
if _, err := tmp.Write(body); err != nil {
_ = tmp.Close()
return
}
if err := tmp.Close(); err != nil {
return
}
if err := os.Rename(tmpName, cachePath); err != nil {
_ = os.Remove(cachePath)
_ = os.Rename(tmpName, cachePath)
}
}
func cacheStampPath(cachePath string) string {
if cachePath == "" {
return ""
}
return cachePath + ".stamp"
}
func sourceNewerThan(ts time.Time) bool {
for _, path := range []string{"generate_codex_data.go", "go.mod", "go.sum"} {
info, err := os.Stat(path)
if err == nil && info.ModTime().After(ts) {
return true
}
}
return false
}
func fileSignature(root string, out string, rawOut string, days int, files []sessionFileCandidate) string {
var totalSize int64
var maxMtimeNs int64
for _, file := range files {
totalSize += file.size
if file.mtimeNs > maxMtimeNs {
maxMtimeNs = file.mtimeNs
}
}
return fmt.Sprintf("v=%d\nroot=%s\nout=%s\nraw=%s\ndays=%d\nfiles=%d:%d:%d\n",
cacheVersion, root, out, rawOut, days, len(files), totalSize, maxMtimeNs)
}
func outputIsStampedFresh(outPath string, rawOutPath string, files []sessionFileCandidate, stampPath string, expectedSignature string) bool {
if outPath == "" || stampPath == "" {
return false
}
outInfo, err := os.Stat(outPath)
if err != nil || outInfo.IsDir() || sourceNewerThan(outInfo.ModTime()) {
return false
}
rawInfo, err := os.Stat(rawOutPath)
if rawOutPath == "" || err != nil || rawInfo.IsDir() || sourceNewerThan(rawInfo.ModTime()) {
return false
}
stampInfo, err := os.Stat(stampPath)
if err != nil || stampInfo.IsDir() || stampInfo.ModTime().Before(outInfo.ModTime()) || stampInfo.ModTime().Before(rawInfo.ModTime()) {
return false
}
body, err := os.ReadFile(stampPath)
if err != nil {
return false
}
if string(body) != expectedSignature || !outputHasCurrentSchemaForRawPath(outPath, browserRawDataPath(outPath, rawOutPath)) || !rawOutputHasCurrentSchema(rawOutPath) {
return false
}
outMtime := outInfo.ModTime()
if rawInfo.ModTime().Before(outMtime) {
outMtime = rawInfo.ModTime()
}
for _, file := range files {
if time.Unix(0, file.mtimeNs).After(outMtime) {
return false
}
}
return true
}
func outputHasCurrentSchema(outPath string) bool {
return outputHasCurrentSchemaForRawPath(outPath, "")
}
func outputHasCurrentSchemaForRawPath(outPath string, rawDataPath string) bool {
needles := []string{`"schemaVersion":2`, `"rawDataPath"`, `"views"`, `"pricingRules"`}
if rawDataPath != "" {
quoted, err := json.Marshal(rawDataPath)
if err != nil {
return false
}
needles = append(needles, `"rawDataPath":`+string(quoted))
}
return fileHeadContainsAll(outPath, 128*1024, needles...)
}
func rawOutputHasCurrentSchema(outPath string) bool {
return fileHeadContainsAll(outPath, 16*1024, `window.CODEXSCOPE_RAW_DATA`, `"schemaVersion":2`, `"rawSchemaVersion":1`)
}
func fileHeadContainsAll(path string, limit int64, needles ...string) bool {
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
if limit <= 0 {
limit = 4096
}
body, err := io.ReadAll(io.LimitReader(file, limit))
if err != nil {
return false
}
text := string(body)
for _, needle := range needles {
if !strings.Contains(text, needle) {
return false
}
}
return true
}
func writeRunStamp(stampPath string, signature string) {
if stampPath == "" {
return
}
_ = os.WriteFile(stampPath, []byte(signature), 0o644)
}
func canAppendFrom(path string, offset int64) bool {
if offset <= 0 {
return false
}
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
if _, err := file.Seek(offset-1, io.SeekStart); err != nil {
return false
}
var lastByte [1]byte
n, err := file.Read(lastByte[:])
return err == nil && n == 1 && lastByte[0] == '\n'
}
func parseSessionFile(path string, cutoff time.Time) ParsedFile {
parsed := ParsedFile{Sid: strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)), File: path, Model: "unknown"}
return parseSessionFileFrom(path, cutoff, parsed, 0)
}
func parseSessionFileAppend(path string, cutoff time.Time, cached ParsedFile, offset int64) ParsedFile {
if cached.Sid == "" {
cached.Sid = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
}
if cached.File == "" {
cached.File = path
}
if cached.Model == "" {
cached.Model = "unknown"
}
return parseSessionFileFrom(path, cutoff, cached, offset)
}
func parseSessionFileFrom(path string, cutoff time.Time, parsed ParsedFile, offset int64) ParsedFile {
// Parse JSONL incrementally instead of loading the whole file. Large Codex
// sessions can grow quickly, and only a small set of metadata fields is
// needed for the dashboard.
file, err := os.Open(path)
if err != nil {
return parsed
}
defer file.Close()
if offset > 0 {
if _, err := file.Seek(offset, io.SeekStart); err != nil {
return parsed
}
}
reader := bufio.NewReaderSize(file, 1024*1024)
prevTotal := parsed.LastTotal
hasPrevTotal := parsed.HasLastTotal
var latestLimitsTs time.Time
hasLatestLimitsTs := false
if ts, ok := parseTime(parsed.LatestLimitsTs); ok {
latestLimitsTs = ts
hasLatestLimitsTs = true
}
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
obj := gjson.ParseBytes(line)
topType := obj.Get("type").String()
payloadType := obj.Get("payload.type").String()
switch {
case topType == "session_meta":
if id := obj.Get("payload.id").String(); id != "" {
parsed.Sid = id
}
if cwd := obj.Get("payload.cwd").String(); cwd != "" {
parsed.Cwd = cwd
}
case topType == "turn_context":
if model := obj.Get("payload.model").String(); model != "" {
parsed.Model = model
}
if cwd := obj.Get("payload.cwd").String(); cwd != "" {
parsed.Cwd = cwd
}
case payloadType == "token_count":
ts, hasTs := parseTime(obj.Get("timestamp").String())
limitsResult := obj.Get("payload.rate_limits")
if limitsResult.Exists() && limitsResult.IsObject() {
var limits map[string]any
if json.Unmarshal([]byte(limitsResult.Raw), &limits) == nil {
// Codex can emit both global quota and model-specific quota
// records. Prefer the global codex object; for the same
// quota class, keep the newest record.
if preferRateLimits(limits, ts, hasTs, parsed.LatestLimits, latestLimitsTs, hasLatestLimitsTs) {
parsed.LatestLimits = limits
if hasTs {
latestLimitsTs = ts
hasLatestLimitsTs = true
parsed.LatestLimitsTs = isoTime(ts, true)
}
}
}
}
lastUsage, hasLast := usageSnapshotResult(obj.Get("payload.info.last_token_usage"))
totalUsage, hasTotal := usageSnapshotResult(obj.Get("payload.info.total_token_usage"))
prev := prevTotal
hadPrev := hasPrevTotal
if hasTotal {
prevTotal = totalUsage
hasPrevTotal = true
parsed.LastTotal = totalUsage
parsed.HasLastTotal = true
}
if hasTs && !ts.Before(cutoff) {
var usage Usage
hasUsage := false
// Prefer cumulative deltas when possible. Fall back to
// last_token_usage for the first event or older log shapes.
if hasTotal && hadPrev {
usage, hasUsage = usageDelta(totalUsage, prev)
} else if hasLast {
usage, hasUsage = lastUsage, true
}
if hasUsage {
event := UsageEvent{Ts: isoTime(ts, true), Sid: parsed.Sid, Usage: usage, Model: parsed.Model}
if hasTotal {
event.Snapshot = totalUsage
event.HasSnapshot = true
}
parsed.UsageEvents = append(parsed.UsageEvents, event)
}
}
case payloadType == "task_complete":
ts, hasTs := parseTime(obj.Get("timestamp").String())
if hasTs && !ts.Before(cutoff) {
event := CompletionEvent{Ts: isoTime(ts, true), Sid: parsed.Sid, Model: parsed.Model}
if duration := obj.Get("payload.duration_ms"); duration.Exists() {
event.DurationMs = duration.Int()
}
if ttfb := obj.Get("payload.time_to_first_token_ms"); ttfb.Exists() {
event.TTFBMs = ttfb.Int()
}
parsed.CompletionEvents = append(parsed.CompletionEvents, event)
}
case payloadType == "error" || payloadType == "turn_aborted":
ts, hasTs := parseTime(obj.Get("timestamp").String())
if hasTs && !ts.Before(cutoff) {
parsed.FailureEvents = append(parsed.FailureEvents, FailureEvent{Ts: isoTime(ts, true), Sid: parsed.Sid, Model: parsed.Model})
}
}
}
if err != nil {
if err == io.EOF {
break
}
break
}
}
return parsed
}
func markSeen(stat *SessionStats, ts time.Time) {
if stat.StartedAt.IsZero() || ts.Before(stat.StartedAt) {
stat.StartedAt = ts
}
if stat.EndedAt.IsZero() || ts.After(stat.EndedAt) {
stat.EndedAt = ts
}
}
func mergeSessionFile(parsed ParsedFile, cutoff time.Time, loaded *LoadedData, latestLimitsTs *time.Time, seenUsageEvents map[string]struct{}) {
// Parsed files are per-log artifacts; LoadedData is the normalized runtime
// model used for totals, rankings, chart records, and latest quota status.
sid := parsed.Sid
if sid == "" {
sid = strings.TrimSuffix(filepath.Base(parsed.File), filepath.Ext(parsed.File))
}
model := parsed.Model
if model == "" {
model = "unknown"
}
stat := SessionStats{Sid: sid, File: parsed.File, Cwd: parsed.Cwd, Model: model}
for _, event := range parsed.UsageEvents {
ts, ok := parseTime(event.Ts)
if !ok || ts.Before(cutoff) {
continue
}
eventSid := event.Sid
if eventSid == "" {
eventSid = sid
}
eventModel := event.Model
if eventModel == "" {
eventModel = model
}
if event.HasSnapshot {
key := usageSnapshotKey(eventSid, eventModel, event.Snapshot)
if _, ok := seenUsageEvents[key]; ok {
continue
}
seenUsageEvents[key] = struct{}{}
}
markSeen(&stat, ts)
addUsage(&stat.Usage, event.Usage)
stat.Calls++
loaded.Events = append(loaded.Events, RuntimeEvent{Ts: ts, Sid: eventSid, Usage: event.Usage, Model: eventModel})
}
for _, event := range parsed.CompletionEvents {
ts, ok := parseTime(event.Ts)
if !ok || ts.Before(cutoff) {
continue
}
markSeen(&stat, ts)
stat.Completions++
stat.DurationMs += event.DurationMs
if event.TTFBMs > 0 {
stat.TTFBMs += event.TTFBMs
stat.TTFBCount++
eventSid := event.Sid
if eventSid == "" {
eventSid = sid
}
eventModel := event.Model
if eventModel == "" {
eventModel = model
}
loaded.TTFBEvents = append(loaded.TTFBEvents, RuntimeTTFBEvent{Ts: ts, Sid: eventSid, Model: eventModel, TTFBMs: event.TTFBMs})
}
}
for _, event := range parsed.FailureEvents {
ts, ok := parseTime(event.Ts)
if !ok || ts.Before(cutoff) {
continue
}
markSeen(&stat, ts)
stat.Failures++
eventSid := event.Sid
if eventSid == "" {
eventSid = sid
}
eventModel := event.Model
if eventModel == "" {
eventModel = model
}
loaded.FailureEvents = append(loaded.FailureEvents, RuntimeFailureEvent{Ts: ts, Sid: eventSid, Model: eventModel})
}
if parsed.LatestLimits != nil {
ts, ok := parseTime(parsed.LatestLimitsTs)
if preferRateLimits(parsed.LatestLimits, ts, ok, loaded.Limits, *latestLimitsTs, !latestLimitsTs.IsZero()) {
loaded.Limits = parsed.LatestLimits
if ok {
*latestLimitsTs = ts
}
}
}
if stat.Calls != 0 || stat.Completions != 0 || stat.Failures != 0 {
loaded.Sessions = append(loaded.Sessions, stat)
}
}
func collectSessionFiles(root string, cutoff time.Time) []sessionFileCandidate {
files := make([]sessionFileCandidate, 0, 1024)
_ = filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil || entry == nil || entry.IsDir() || !strings.HasSuffix(entry.Name(), ".jsonl") {
return nil
}
info, err := entry.Info()
if err != nil {
return nil
}
// Use one day of slack around the event cutoff because file mtimes and
// event timestamps can diverge after syncs, copies, or manual moves.
if info.ModTime().UTC().Before(cutoff.Add(-24 * time.Hour)) {
return nil
}
files = append(files, sessionFileCandidate{
path: path,
mtimeNs: info.ModTime().UnixNano(),
size: info.Size(),
})
return nil
})
sort.Slice(files, func(i, j int) bool { return files[i].path < files[j].path })
return files
}
func parseSessionFiles(files []sessionFileCandidate, cutoff time.Time, cacheFiles map[string]FileCache) []parsedSessionFile {
// Bound concurrency to keep launches fast without making the generator noisy
// on small laptops. Cached files skip JSON parsing when mtime and size match.
results := make([]parsedSessionFile, len(files))
if len(files) == 0 {
return results
}
workerCount := runtime.GOMAXPROCS(0) * 2
if workerCount < 2 {
workerCount = 2
}
if workerCount > 16 {
workerCount = 16
}
if workerCount > len(files) {
workerCount = len(files)
}
jobs := make(chan int)
var wg sync.WaitGroup
wg.Add(workerCount)
for worker := 0; worker < workerCount; worker++ {
go func() {
defer wg.Done()
for index := range jobs {
file := files[index]
cached, ok := cacheFiles[file.path]
var parsed ParsedFile
if ok && cached.MtimeNs == file.mtimeNs && cached.Size == file.size {
parsed = cached.Parsed
} else if ok && file.size > cached.Size && cached.Parsed.HasLastTotal && canAppendFrom(file.path, cached.Size) {
parsed = parseSessionFileAppend(file.path, cutoff, cached.Parsed, cached.Size)
} else {
parsed = parseSessionFile(file.path, cutoff)
}
results[index] = parsedSessionFile{file: file, parsed: parsed}
}
}()
}
for index := range files {
jobs <- index
}
close(jobs)
wg.Wait()
return results
}
func loadSessions(root string, cutoff time.Time, cachePath string, days int, cacheFiles map[string]FileCache) LoadedData {
loaded := LoadedData{}
if cacheFiles == nil {
cacheFiles = loadCache(cachePath, days)
}
var latestLimitsTs time.Time