Repository navigation
Expand file tree
/
Copy pathusage.go
More file actions
808 lines (752 loc) · 23.3 KB
/
Copy pathusage.go
File metadata and controls
808 lines (752 loc) · 23.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
package main
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync/atomic"
"text/tabwriter"
"time"
"github.com/doordash-oss/oapi-codegen-dd/v3/pkg/runtime"
"go.kenn.io/agentsview/internal/apiclient"
"go.kenn.io/agentsview/internal/config"
"go.kenn.io/agentsview/internal/db"
"go.kenn.io/agentsview/internal/export"
"go.kenn.io/agentsview/internal/money"
"go.kenn.io/agentsview/internal/parser"
"go.kenn.io/agentsview/internal/pricing"
"go.kenn.io/agentsview/internal/pricingrefresh"
"go.kenn.io/agentsview/internal/service"
"go.kenn.io/agentsview/internal/sync"
"go.kenn.io/agentsview/internal/timeutil"
)
// quickSyncMargin pads the mtime cutoff backward from the
// last recorded sync start time to catch files modified
// during the prior sync. Smaller values are faster but risk
// missing recent writes; 10s is a safe default.
const quickSyncMargin = 10 * time.Second
// defaultUsageDays is the default lookback window for
// `agentsview usage daily` when neither --since nor --all is
// given. Matches ccusage's default and avoids scanning the
// full history when users usually want recent spend.
const defaultUsageDays = 30
// defaultUsageDateRange mirrors the HTTP usage route's default range:
// fill a missing upper bound with today, then fill a missing lower
// bound relative to that upper bound. Callers that intentionally want
// an open-ended range must set NoDefaultRange instead of calling this.
func defaultUsageDateRange(
from, to string, now time.Time,
) (string, string) {
now = now.UTC()
if to == "" {
to = now.Format("2006-01-02")
}
if from == "" {
t, err := time.Parse("2006-01-02", to)
if err != nil {
t = now
}
from = t.AddDate(0, 0, -defaultUsageDays).Format("2006-01-02")
}
return from, to
}
type UsageDailyConfig struct {
JSON bool
Since string
Until string
All bool
Agent string
Breakdown bool
Offline bool
NoSync bool
Timezone string
}
type usageDailyDocument struct {
db.DailyUsageResult
MachineLabels service.MachineLabelCatalog `json:"machine_labels,omitzero"`
}
// resolveUsageWindow resolves the raw --since/--until flags into concrete
// inclusive YYYY-MM-DD bounds. Both accept a duration like 28d or a date,
// the same syntax as `stats`. --until resolves first; a duration --since is
// then measured back from the resolved --until (or from now when --until is
// open), matching how stats anchors a duration window. An inverted explicit
// window is rejected so a reversed range fails loudly instead of returning
// an empty result.
func resolveUsageWindow(
since, until string, now time.Time, loc *time.Location,
) (string, string, error) {
if loc == nil {
loc = time.UTC
}
now = now.In(loc)
// Resolve --until first and keep it as the anchor for --since:
// ParseWindowPoint measures a duration back from its time argument, so
// a duration --since is measured from the resolved --until while a date
// stands alone. --until open leaves the anchor at now.
anchor := now
to := ""
if until != "" {
t, date, err := resolveUsageWindowPoint(until, now, loc)
if err != nil {
return "", "", fmt.Errorf("invalid --until: %w", err)
}
anchor, to = t, date
}
from := ""
if since != "" {
_, date, err := resolveUsageWindowPoint(since, anchor, loc)
if err != nil {
return "", "", fmt.Errorf("invalid --since: %w", err)
}
from = date
}
// Bounds are inclusive, so from == to is a valid single day (hence >
// not >=). String comparison is valid because YYYY-MM-DD sorts
// lexically.
if from != "" && to != "" && from > to {
return "", "", fmt.Errorf(
"--since (%s) must not be after --until (%s)", from, to)
}
return from, to, nil
}
func resolveUsageWindowPoint(
raw string, anchor time.Time, loc *time.Location,
) (time.Time, string, error) {
if t, err := time.ParseInLocation("2006-01-02", raw, loc); err == nil {
return t, raw, nil
}
t, err := db.ParseWindowPoint(raw, anchor)
if err != nil {
return time.Time{}, "", err
}
return t, t.In(loc).Format("2006-01-02"), nil
}
func runUsageDaily(cfg UsageDailyConfig) {
if err := runUsageDailyResult(cfg); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func runUsageDailyResult(cfg UsageDailyConfig) error {
tz := cfg.Timezone
if tz == "" {
tz = localTimezone()
}
loc, err := time.LoadLocation(tz)
if err != nil {
return fmt.Errorf("invalid --timezone: %w", err)
}
since, until, err := resolveUsageWindow(cfg.Since, cfg.Until, time.Now(), loc)
if err != nil {
return err
}
filter := db.UsageFilter{
From: since,
To: until,
Agent: cfg.Agent,
Timezone: tz,
}
noDefaultRange := cfg.All || cfg.Since != "" || cfg.Until != ""
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
backend, cleanup, err := resolveArchiveQueryBackend(ctx, archiveQueryPolicy{
Offline: cfg.Offline,
NoSync: cfg.NoSync,
AutoStart: true,
SkipInitialSync: true,
ReadOnlyDaemon: archiveQuerySkipReadOnlyDaemon,
DirectReadOnlyAction: "refresh usage directly",
})
if err != nil {
return err
}
defer closeArchiveQueryBackend(cleanup)
progress, finishProgress := newUsageProgressPrinter(os.Stderr)
result, err := backend.DailyUsage(ctx, dailyUsageQuery{
Progress: progress,
Filter: filter,
NoDefaultRange: noDefaultRange,
Breakdowns: cfg.Breakdown,
SessionCounts: cfg.JSON,
})
finishProgress()
if err != nil {
return err
}
if cfg.JSON {
document := usageDailyDocument{DailyUsageResult: result}
if cfg.Breakdown {
keys := make(map[string]struct{})
for _, day := range result.Daily {
for _, breakdown := range day.MachineBreakdowns {
keys[breakdown.MachineName] = struct{}{}
}
}
document.MachineLabels = machineLabelsForKeys(machineLabelCatalog(
ctx, os.Stderr, backend.MachineLabels,
), keys)
}
enc := jsontext.NewEncoder(os.Stdout, jsontext.WithIndent(" "))
if err := json.MarshalEncode(enc, document); err != nil {
return err
}
return nil
}
printDailyTable(result, cfg.Breakdown)
if note := noTokenDataNote(cfg.Agent, result.Totals); note != "" {
fmt.Fprintln(os.Stderr, note)
}
return nil
}
// noTokenDataNote returns a one-line stderr note for a zero usage result when
// the user has filtered to agents that do not record per-message token usage.
// The wording follows the service's unsupported-usage kind for the same
// filter, so the CLI and the dashboard cannot drift: all-Copilot filters keep
// the Copilot-specific wording and every other no-token filter gets the
// generic note. It returns "" when the filter does not select only
// no-token-data agents or real token/cost data exists. This is an
// agent-property statement (issue #349) shown in response to an explicit
// --agent the user typed, so it needs no session-presence check; it is
// appropriate even for an empty window.
func noTokenDataNote(agent string, totals db.UsageTotals) string {
if !parser.AgentFilterLacksPerMessageTokenData(agent) ||
!db.NoTokenData(totals) {
return ""
}
if service.UnsupportedUsageKindForAgentFilter(agent) ==
service.UnsupportedUsageKindCopilotNoTokenData {
return "note: these GitHub Copilot records do not include token " +
"or cost data that agentsview can total."
}
return "note: matching sessions do not record per-message token usage."
}
type UsageStatuslineConfig struct {
JSON bool
Agent string
Offline bool
NoSync bool
}
// usageStatuslineReport is the machine-readable form of the statusline. It
// carries the same facts as the human line and nothing more: today's cost,
// the day it covers, and the agent filter that produced it. Cost stays a
// money.Money so callers read exact microdollars instead of scraping the
// formatted string.
type usageStatuslineReport struct {
Date string `json:"date"`
Cost money.Money `json:"cost"`
Agent string `json:"agent,omitempty"`
}
func usageDateForTimezone(now time.Time, timezone string) string {
loc, err := time.LoadLocation(timezone)
if err != nil {
loc = time.UTC
}
return now.In(loc).Format("2006-01-02")
}
func runUsageStatusline(cfg UsageStatuslineConfig) {
if err := runUsageStatuslineResult(cfg); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func runUsageStatuslineResult(cfg UsageStatuslineConfig) error {
timezone := localTimezone()
today := usageDateForTimezone(time.Now(), timezone)
filter := db.UsageFilter{
From: today,
To: today,
Agent: cfg.Agent,
Timezone: timezone,
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
backend, cleanup, err := resolveArchiveQueryBackend(ctx, archiveQueryPolicy{
Offline: cfg.Offline,
NoSync: cfg.NoSync,
AutoStart: true,
ReadOnlyDaemon: archiveQuerySkipReadOnlyDaemon,
DirectReadOnlyAction: "refresh usage directly",
})
if err != nil {
return err
}
defer closeArchiveQueryBackend(cleanup)
result, err := backend.DailyUsage(ctx, dailyUsageQuery{
Filter: filter,
NoDefaultRange: true,
})
if err != nil {
return err
}
if cfg.JSON {
return printUsageStatuslineJSON(result, cfg.Agent, today)
}
printUsageStatusline(result, cfg.Agent)
return nil
}
func printUsageStatuslineJSON(
result db.DailyUsageResult, agent, date string,
) error {
enc := jsontext.NewEncoder(os.Stdout, jsontext.WithIndent(" "))
report := usageStatuslineReport{
Date: date,
Cost: result.Totals.TotalCost,
Agent: agent,
}
if err := json.MarshalEncode(enc, report); err != nil {
return err
}
return nil
}
func printUsageStatusline(result db.DailyUsageResult, agent string) {
if agent != "" {
fmt.Printf("%s today (%s)\n",
fmtCost(result.Totals.TotalCost), agent)
} else {
fmt.Printf("%s today\n",
fmtCost(result.Totals.TotalCost))
}
}
func applyCustomPricing(database *db.DB, cfg config.Config) {
if len(cfg.CustomModelPricing) == 0 {
return
}
database.SetCustomPricing(cfg.CustomModelPricing)
}
// ensureFreshData makes sure the database reflects recent
// session file changes before serving a usage query.
//
// Decision tree:
// 1. If the stored data version is stale (parser changes on
// upgrade), run a full resync.
// 2. If a server process is active (via kit runtime record), trust
// its file watcher and skip on-demand sync. This avoids
// duplicate work and write contention.
// 3. Otherwise, run a quick incremental sync scoped to files
// modified since the last recorded sync start time, with
// a small safety margin.
//
// Callers that need stale data (e.g. offline benchmarks) can
// bypass via skip=true.
func ensureFreshData(
ctx context.Context, appCfg config.Config, database *db.DB, skip bool,
) {
if skip {
return
}
if ctx == nil {
ctx = context.Background()
}
// Silence engine worker log.Printf lines (e.g. "db:
// InsertMessages (N msgs)") for both branches so --json and
// statusline output stay clean. Progress goes to stderr
// below to stay out of stdout-bound payloads.
origLog := log.Writer()
log.SetOutput(io.Discard)
defer log.SetOutput(origLog)
if database.NeedsResync() {
engine := sync.NewEngine(ctx, database, sync.EngineConfig{
AgentDirs: appCfg.AgentDirs,
SourceMachines: appCfg.SourceMachines,
ProviderMetadata: appCfg.ProviderMetadata,
DisabledAgents: appCfg.DisabledAgents,
IncludeCwdPrefixes: appCfg.SyncIncludeCwdPrefixes,
ScanProtectedPaths: appCfg.ScanProtectedPaths,
Machine: appCfg.InstallationID,
ArchiveContent: appCfg.ArchiveContent,
})
defer engine.Close()
fmt.Fprintln(os.Stderr,
"Data version changed, running full resync...")
t := time.Now()
progress := newResyncProgressPrinter(os.Stderr, time.Now)
stats := engine.ResyncAll(ctx, progress.Print)
progress.Finish()
printSyncSummaryStderr(stats, t)
return
}
// Skip on-demand sync only when a writable local daemon is
// already keeping the SQLite archive fresh. pg serve daemons
// (read-only) do not sync the local DB, so we still want to
// run our own sync when only one of those is present.
if IsLocalDaemonActive(appCfg.DataDir, appCfg.AuthToken) {
return
}
engine := sync.NewEngine(ctx, database, sync.EngineConfig{
AgentDirs: appCfg.AgentDirs,
SourceMachines: appCfg.SourceMachines,
ProviderMetadata: appCfg.ProviderMetadata,
DisabledAgents: appCfg.DisabledAgents,
IncludeCwdPrefixes: appCfg.SyncIncludeCwdPrefixes,
ScanProtectedPaths: appCfg.ScanProtectedPaths,
Machine: appCfg.InstallationID,
ArchiveContent: appCfg.ArchiveContent,
})
defer engine.Close()
since := engine.LastSyncStartedAt(ctx)
if !since.IsZero() {
since = since.Add(-quickSyncMargin)
}
engine.SyncAllSince(ctx, since, func(sync.Progress) {})
}
// printSyncSummaryStderr mirrors printSyncSummary but writes to
// stderr so it does not pollute stdout-bound JSON or statusline output.
func printSyncSummaryStderr(stats sync.SyncStats, t time.Time) {
summary := fmt.Sprintf(
"Sync complete: %d sessions synced",
stats.Synced,
)
if isTerminalWriter(os.Stderr) {
summary = "\n" + summary
}
if stats.OrphanedCopied > 0 {
summary += fmt.Sprintf(
", %d archived sessions preserved",
stats.OrphanedCopied,
)
}
if stats.Failed > 0 {
summary += fmt.Sprintf(", %d failed", stats.Failed)
}
summary += fmt.Sprintf(
" in %s\n", time.Since(t).Round(time.Millisecond),
)
summary += formatAnomalySummary(stats.Anomalies)
fmt.Fprint(os.Stderr, summary)
for _, w := range stats.Warnings {
fmt.Fprintf(os.Stderr, "warning: %s\n", w)
}
}
// seedPricing ensures fallback rates are present in model_pricing.
//
// Fallback rates are only upserted when the stored seed
// version differs from pricing.SeedVersion (or is
// absent). This avoids overwriting live LiteLLM rates on
// every restart while still propagating corrected fallback
// rates when the binary is upgraded. SeedVersion folds in
// the supplemental alias version, so curated alias additions
// (see internal/pricing/supplemental.go) also reach existing
// databases without a resync.
func seedPricing(
database *db.DB,
runner remoteSyncExclusiveRunner,
) {
err := runPricingExclusive(runner, func() error {
return pricingrefresh.SeedFallback(database)
})
if err != nil {
log.Printf("pricing seed: %v", err)
}
}
func ensurePricing(database *db.DB, offline bool) {
if _, err := pricingrefresh.Ensure(
database, offline, pricing.FetchCatalog, time.Now(),
); err != nil {
fmt.Fprintf(os.Stderr,
"warning: pricing refresh failed: %v\n", err)
}
}
func ensureUsagePricing(
database *db.DB, offline bool,
custom map[string]config.CustomModelRate,
) {
if offline && database.ReadOnly() {
applyFallbackPricing(database, custom)
return
}
ensurePricing(database, offline)
}
func applyFallbackPricing(
database *db.DB, custom map[string]config.CustomModelRate,
) {
database.SetEffectivePricing(fallbackPricingRates(custom))
}
func applyEmptyCatalogPricing(
database *db.DB, custom map[string]config.CustomModelRate,
) {
database.SetEmptyCatalogPricing(fallbackPricingRates(custom))
}
func fallbackPricingRates(
custom map[string]config.CustomModelRate,
) map[string]export.ModelRates {
rates := make(map[string]export.ModelRates)
for _, p := range pricing.FallbackPricing() {
// These keys are the same concrete model-pattern keys that the
// model_pricing table stores. SQLite usage lookups run the merged map
// through pricing.Resolve, so normalized/canonical aliases still match
// when this read-only path cannot seed model_pricing rows.
bands := make([]export.PricingBand, len(p.Bands))
for i, band := range p.Bands {
bands[i] = export.PricingBand{
AboveInputTokens: band.AboveInputTokens,
InputPerMTok: band.InputPerMTok,
OutputPerMTok: band.OutputPerMTok,
CacheWritePerMTok: band.CacheCreationPerMTok,
CacheWrite1hPerMTok: band.CacheCreation1hPerMTok,
CacheReadPerMTok: band.CacheReadPerMTok,
}
}
rates[p.ModelPattern] = export.ModelRates{
InputPerMTok: p.InputPerMTok,
OutputPerMTok: p.OutputPerMTok,
CacheWritePerMTok: p.CacheCreationPerMTok,
CacheWrite1hPerMTok: p.CacheCreation1hPerMTok,
CacheReadPerMTok: p.CacheReadPerMTok,
Source: export.PricingRowSourceEmbedded,
Bands: bands,
}
}
for model, rate := range custom {
rates[model] = export.ModelRates{
InputPerMTok: money.Money{
Microdollars: rate.InputMicrodollarsPerMTok,
},
OutputPerMTok: money.Money{
Microdollars: rate.OutputMicrodollarsPerMTok,
},
CacheWritePerMTok: money.Money{
Microdollars: rate.CacheCreationMicrodollarsPerMTok,
},
CacheWrite1hPerMTok: money.Money{
Microdollars: rate.CacheCreation1hMicrodollarsPerMTok,
},
CacheReadPerMTok: money.Money{
Microdollars: rate.CacheReadMicrodollarsPerMTok,
},
Source: export.PricingRowSourceCustom,
}
}
return rates
}
func fetchHTTPDailyUsage(
ctx context.Context,
tr transport,
authToken string,
query dailyUsageQuery,
) (db.DailyUsageResult, error) {
filter := query.Filter
q := apiclient.GetAPIV1UsageSummaryStreamQuery{
NoDefaultRange: new(query.NoDefaultRange), Breakdowns: new(query.Breakdowns), SessionCounts: new(query.SessionCounts),
IncludeOneShot: new(!filter.ExcludeOneShot), IncludeAutomated: new(!filter.ExcludeAutomated),
}
if filter.Timezone != "" {
q.Timezone = new(filter.Timezone)
}
if filter.Agent != "" {
q.Agent = new(filter.Agent)
}
if filter.Project != "" {
q.Project = new(filter.Project)
}
if filter.Machine != "" {
q.Machine = new(filter.Machine)
}
if filter.ExcludeProject != "" {
q.ExcludeProject = new(filter.ExcludeProject)
}
if filter.ExcludeAgent != "" {
q.ExcludeAgent = new(filter.ExcludeAgent)
}
if filter.ExcludeModel != "" {
q.ExcludeModel = new(filter.ExcludeModel)
}
if filter.Model != "" {
q.Model = new(filter.Model)
}
if filter.Termination != "" {
q.Termination = new(filter.Termination)
}
if filter.From != "" {
parsed, err := time.Parse(time.DateOnly, filter.From)
if err != nil {
return db.DailyUsageResult{}, err
}
q.From = &runtime.Date{Time: parsed}
}
if filter.To != "" {
parsed, err := time.Parse(time.DateOnly, filter.To)
if err != nil {
return db.DailyUsageResult{}, err
}
q.To = &runtime.Date{Time: parsed}
}
if filter.ActiveSince != "" {
parsed, err := time.Parse(time.RFC3339, filter.ActiveSince)
if err != nil {
return db.DailyUsageResult{}, err
}
q.ActiveSince = &parsed
}
if filter.MinUserMessages > 0 {
q.MinUserMessages = new(int64(filter.MinUserMessages))
}
api, err := apiclient.NewHTTPClient(tr.URL, authToken, &http.Client{Timeout: 0})
if err != nil {
return db.DailyUsageResult{}, err
}
var resp *http.Response
var payload []byte
var out apiclient.UsageSummaryResponse
var stream *runtime.Stream[[]byte]
if query.Progress != nil {
response, requestErr := api.GetAPIV1UsageSummaryStreamStreamWithResponse(ctx, &apiclient.GetAPIV1UsageSummaryStreamRequestOptions{Query: &q})
if response == nil {
return db.DailyUsageResult{}, requestErr
}
resp, payload, stream = response.HTTPResponse, response.Body, response.Stream200
} else {
bufferedQuery := apiclient.GetAPIV1UsageSummaryQuery(q)
response, requestErr := api.GetAPIV1UsageSummaryWithResponse(ctx, &apiclient.GetAPIV1UsageSummaryRequestOptions{Query: &bufferedQuery})
if response == nil {
return db.DailyUsageResult{}, requestErr
}
resp, payload = response.HTTPResponse, response.Body
if response.StatusCode == http.StatusOK {
if requestErr != nil {
return db.DailyUsageResult{}, requestErr
}
if len(response.Body) == 0 {
return db.DailyUsageResult{}, io.ErrUnexpectedEOF
}
out = *response.JSON200
}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body := payload
return db.DailyUsageResult{}, fmt.Errorf(
"usage summary: HTTP %d: %s",
resp.StatusCode, strings.TrimSpace(string(body)),
)
}
if query.Progress != nil {
if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
return db.DailyUsageResult{}, fmt.Errorf("usage summary: expected a progress stream, received %q", resp.Header.Get("Content-Type"))
}
data, err := consumeDaemonPushEvents[apiclient.UsageSummaryResponse](stream, func(p struct {
Detail string `json:"detail"`
},
) {
query.Progress(p.Detail)
})
if err != nil {
return db.DailyUsageResult{}, fmt.Errorf("usage summary: %w", err)
}
out = data
}
if out.Projects == nil {
out.Projects = map[string]export.ProjectMapEntry{}
}
schemaVersion := 0
if out.SchemaVersion != nil {
schemaVersion = int(*out.SchemaVersion)
}
return db.DailyUsageResult{
SchemaVersion: schemaVersion,
Pricing: out.Pricing,
Projects: out.Projects,
Daily: out.Daily,
Totals: out.Totals,
SessionCounts: out.SessionCounts,
}, nil
}
func newUsageProgressPrinter(w io.Writer) (func(string), func()) {
started := time.Now()
var phase atomic.Pointer[string]
phase.Store(new("Preparing usage report from the archive"))
stop, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var lastPhase string
var lastPrinted time.Duration
for {
select {
case <-stop:
return
case <-ticker.C:
current, elapsed := *phase.Load(), time.Since(started)
if current != lastPhase || elapsed-lastPrinted >= 5*time.Second {
fmt.Fprintf(w, "%s (%s)\n", current, elapsed.Round(time.Second))
lastPhase, lastPrinted = current, elapsed
}
}
}
}()
return func(current string) { phase.Store(¤t) }, func() { close(stop); <-done }
}
func printDailyTable(
result db.DailyUsageResult, breakdown bool,
) {
w := tabwriter.NewWriter(
os.Stdout, 0, 4, 2, ' ', 0,
)
fmt.Fprintln(w,
"DATE\tINPUT\tOUTPUT\tCACHE_CR\tCACHE_RD\tCOST\tMODELS")
fmt.Fprintln(w,
"----\t-----\t------\t--------\t--------\t----\t------")
for _, day := range result.Daily {
models := joinModels(day.ModelsUsed)
fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%d\t%s\t%s\n",
day.Date,
day.InputTokens,
day.OutputTokens,
day.CacheCreationTokens,
day.CacheReadTokens,
fmtCost(day.TotalCost),
models,
)
if breakdown {
for _, mb := range day.ModelBreakdowns {
fmt.Fprintf(w,
" %s\t%d\t%d\t%d\t%d\t%s\t\n",
mb.ModelName,
mb.InputTokens,
mb.OutputTokens,
mb.CacheCreationTokens,
mb.CacheReadTokens,
fmtCost(mb.Cost),
)
}
}
}
fmt.Fprintln(w,
"----\t-----\t------\t--------\t--------\t----\t------")
fmt.Fprintf(w, "TOTAL\t%d\t%d\t%d\t%d\t%s\t\n",
result.Totals.InputTokens,
result.Totals.OutputTokens,
result.Totals.CacheCreationTokens,
result.Totals.CacheReadTokens,
fmtCost(result.Totals.TotalCost),
)
w.Flush()
}
// localTimezone returns the IANA name of the system's local timezone.
func localTimezone() string {
return timeutil.LocalTimezoneOrUTC()
}
// fmtCost formats a dollar amount with two decimal places,
// matching conventional currency display. Non-zero values
// under half a cent would otherwise round to "$0.00" and
// read as "free", so they render as "<$0.01" instead.
func fmtCost(v money.Money) string {
return money.FormatUSD(v, money.DisplayCents)
}
func joinModels(models []string) string {
if len(models) == 0 {
return ""
}
var s strings.Builder
s.WriteString(models[0])
for _, m := range models[1:] {
s.WriteString(", " + m)
}
return s.String()
}