Files
Local-Cursor/internal/historymetrics/usage_json.go
FuDie0915 db73cf5a39 chore: import Local-Cursor v1.1.8 source snapshot
Includes the current working directory changes. Historical commits and release binaries are excluded to limit Gitea storage.
Source base: d7515973fbfd6dd2001fa156c483455b8081c7cb
2026-11-10 01:24:28 +08:00

58 lines
2.0 KiB
Go

package historymetrics
import (
"encoding/json"
"errors"
"fmt"
"os"
)
type usageFileDocument struct {
Totals struct {
ProviderCalls int64 `json:"provider_calls"`
TurnsTotal int64 `json:"turns_total"`
ValidTurnsTotal int64 `json:"valid_turns_total"`
InvalidTurnsTotal int64 `json:"invalid_turns_total"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
TotalTokens int64 `json:"total_tokens"`
} `json:"totals"`
}
func LoadUsageSummary(path string, includeCacheWriteInHitRate bool) (Summary, error) {
body, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Summary{}, nil
}
return Summary{}, fmt.Errorf("read usage file: %w", err)
}
var doc usageFileDocument
if err := json.Unmarshal(body, &doc); err != nil {
return Summary{}, fmt.Errorf("decode usage file: %w", err)
}
totals := Totals{
InputTokens: doc.Totals.InputTokens,
OutputTokens: doc.Totals.OutputTokens,
CacheReadTokens: doc.Totals.CacheReadTokens,
CacheWriteTokens: doc.Totals.CacheWriteTokens,
PromptTokensTotal: doc.Totals.InputTokens + doc.Totals.CacheReadTokens + doc.Totals.CacheWriteTokens,
RequestTokensTotal: doc.Totals.TotalTokens,
}
// 命中率口径统一由后端按用户配置计算,前端只消费该结果,避免两套口径漂移。
totals.IncludeCacheWriteInHitRate = includeCacheWriteInHitRate
return Summary{
ProviderCallsTotal: int(doc.Totals.ProviderCalls),
TurnsTotal: int(doc.Totals.TurnsTotal),
ValidTurnsTotal: int(doc.Totals.ValidTurnsTotal),
InvalidTurnsTotal: int(doc.Totals.InvalidTurnsTotal),
RequestTokensTotal: totals.RequestTokensTotal,
PromptTokensTotal: totals.PromptTokensTotal,
CacheReadTokens: totals.CacheReadTokens,
CacheWriteTokens: totals.CacheWriteTokens,
CacheHitRate: cacheHitRateFromTotals(totals),
}, nil
}