diff --git a/CLAUDE.md b/CLAUDE.md index caffb32..af13374 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,6 +103,8 @@ times out (a sync to a slow server holds the single processor), it saves the hea Optional daemon services (feature-gated via config): - **CCInfoTimerService**: Lazy-fetch background timer for Claude Code statusline data (cost, quota, git info), plus an always-on Anthropic usage sync (10-min interval, only while a `claude` process is running) that pushes quota to `/api/v1/anthropic-usage` without needing statusline activity - **CodexUsageSyncService**: Syncs Codex usage to `/api/v1/codex-usage` every 10 min, only while a `codex`/`chatgpt` process is running (both intervals share the `usageSyncInterval` const in `daemon/usage_sync.go`) +- **CursorUsageSyncService**: Syncs Cursor monthly quota (`/api/v1/cursor-usage`) and recent billed token usage (`/api/v1/cc/backfill`) every 10 min while a `cursor` process is running, resolving auth from `CURSOR_AUTH_TOKEN`, `CURSOR_API_KEY`, `config.cursor.apiKey`, `~/.cursor/auth.json`, or local Cursor `state.vscdb` +- **AntigravityUsageSyncService**: Scans modified local Antigravity SQLite conversation DBs (`~/.gemini/antigravity*`, `~/.config/antigravity`, or `ANTIGRAVITY_DATA_DIR`) every 10 min while `antigravity`/`agy` is running and uploads deduplicated token usage to `/api/v1/cc/backfill` - **SyncCircuitBreakerService**: Retry failed syncs with file-based persistence (`~/.shelltime/sync-pending.jsonl`, one sync message per line, of any length) and hourly recovery timer. `SaveForRetry` and the timer's read-republish-rewrite share a lock, and the rewrite keeps lines saved while it was republishing - **AICodeOtelServer**: gRPC OTEL collector for AI coding CLI metrics, logs and traces (Claude Code, Codex). Spans (`claude_code.interaction`, `llm_request`, `tool`, ...) go to the same `/api/v1/cc/otel` endpoint in `spans`; a span without `session.id` takes it from another span of its trace in the same export. `shelltime cc install` turns traces on (`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, `OTEL_TRACES_EXPORTER=otlp`). In a Claude Code cloud session (`CLAUDE_CODE_REMOTE=true`, where the SessionStart hook starts the daemon) it adds the VM's `CLAUDE_CODE_REMOTE_SESSION_ID` as the `ccr.session.id` attribute to Claude Code records that lack it; the server marks those sessions as cloud sessions. `daemon/main_test.go` clears both variables so tests behave the same inside a cloud session - **Git repositories** (`model/git_repository.go`): the server groups coding agent sessions into projects by git repository, not folder, so a renamed or moved clone, a worktree or a subfolder stays one project. `GitRepositoryResolver` asks the git CLI (found through `CommandService`, so the daemon's limited PATH reaches Homebrew) for a directory's top level and its `origin` remote (else `upstream`, else the first by name; `remote get-url`, so `insteadOf` applies) without optional locks, within one 2 s budget per lookup, since the daemon resolves on the OTLP export path. Concurrent lookups of one directory share one run, which goes on its own goroutine: a stat or git blocked in the kernel (a hung network mount) ignores the context, so the lookup is given up on after the budget (plus `gitRepositoryGrace`), or when its caller's context ends, and the directory gets no other until it returns (its answer is kept then). git runs with `LC_ALL=C`, since its messages are read; a remote's path segments are decoded and escaped again (`url.PathEscape`), like the server's. A migration run stops asking after `projectMigrationMaxUnanswered` folders' stats timed out (a hung mount; git refusing a folder doesn't count), and a folder that doesn't exist counts as missing, one it can't stat otherwise as unchecked. git refusing a repository it doesn't trust (`safe.directory`) or killed by a signal is no answer about the directory; a git binary not found is looked for again every 30 s. It keeps definitive answers, negative ones too (10 min in the daemon), and a timeout or git failing to start for 30 s only, reported as unknown by `Lookup` (`Resolve` drops the flag). `CanonicalRepositoryURL` turns any remote into `https:///` without credentials, port or `.git`, the form Claude Code reports; a local path is no repository. The repository travels as `vcs.repository.url.full` (`model.AICodeRepositoryAttribute`): the OTEL processor adds it to metrics and log events whose resource has a `pwd` and that don't name one (not to spans: the server keys a session from its events), and never when the resource names one (Claude Code's own value wins; git isn't asked then), the socket's `session_project` handler sends it with the statusline's directory, and backfill adds it to uploaded events (Codex's `session_meta.git.repository_url` first, since it was true when the session ran, else the transcript directory's). `aiCodeOtel.sendRepository: false` (`ShellTimeConfig.SendsRepository`) turns all of it off: no resolver in the processor or the socket, the processor removes the attribute from every record (the agent's own too), backfill attaches none, and neither the daemon nor `cc projects` migrates diff --git a/README.md b/README.md index c493c71..3794b51 100644 --- a/README.md +++ b/README.md @@ -245,16 +245,20 @@ Codex decides which windows are present. ShellTime displays the windows returned ## Backfilling AI Usage -Live tracking only records sessions that run while the OTEL configuration is installed and the daemon is running. To upload earlier sessions from the transcripts Claude Code and Codex keep on disk: +Live tracking records sessions while OTEL or daemon sync is running. To upload historical usage for Claude Code, Codex, Cursor, or Google Antigravity: ```bash -shelltime cc backfill --dry-run # show what would be uploaded -shelltime cc backfill # upload Claude Code sessions -shelltime codex backfill # upload Codex sessions +shelltime cc backfill --dry-run # show what would be uploaded +shelltime cc backfill # upload Claude Code sessions +shelltime codex backfill # upload Codex sessions +shelltime cursor backfill # upload Cursor token & cost usage +shelltime agy backfill # upload Antigravity token usage ``` -- Claude Code transcripts are read from `~/.claude/projects` and `~/.config/claude/projects`, or the directories in `CLAUDE_CONFIG_DIR`. Codex sessions are read from `~/.codex/sessions` and `~/.codex/archived_sessions`, or `CODEX_HOME`. -- Prompts, token usage, models and tool calls are uploaded as if they had been tracked live; the server adds costs. Lines of code, commits and active time are not in the transcripts. +- Claude Code transcripts are read from `~/.claude/projects` and `~/.config/claude/projects`, or `CLAUDE_CONFIG_DIR`. Codex sessions are read from `~/.codex/sessions` and `~/.codex/archived_sessions`, or `CODEX_HOME`. +- Cursor usage is fetched from Cursor's `GetFilteredUsageEvents` API using `CURSOR_AUTH_TOKEN`, `CURSOR_API_KEY`, `cursor.apiKey` in config, `~/.cursor/auth.json`, or Cursor IDE's local `state.vscdb`. The daemon also syncs Cursor subscription quota (`GetCurrentPeriodUsage`) and recent token usage every 10 minutes while Cursor is running. +- Antigravity usage is parsed from local conversation SQLite databases under `~/.gemini/antigravity*` and `~/.config/antigravity` (or `ANTIGRAVITY_DATA_DIR`). The daemon also scans modified conversation databases every 10 minutes while Antigravity (`agy`) is running. +- Prompts, token usage, models and tool calls are uploaded as if they had been tracked live; the server fills in costs when the agent did not report one. - Sessions the server already has from live tracking are skipped, as are sessions still running. Running the command again only uploads what is missing. - Flags: `--since` / `--until` (`YYYY-MM-DD`) limit the range, `--no-prompts` uploads prompt lengths without the text, and `--ai-summary` also generates AI session summaries, which use your monthly AI credits. - Claude Code deletes transcripts after 30 days by default (`cleanupPeriodDays`), so only recent history may be available. diff --git a/cmd/daemon/main.go b/cmd/daemon/main.go index 054763c..c7ef838 100644 --- a/cmd/daemon/main.go +++ b/cmd/daemon/main.go @@ -196,6 +196,24 @@ func main() { } } + if !aiCloudOnly && cfg.CursorUsageSyncEnabled() { + cursorUsageSyncService := daemon.NewCursorUsageSyncService(cfg) + if err := cursorUsageSyncService.Start(ctx); err != nil { + slog.Error("Failed to start Cursor usage sync service", slog.Any("err", err)) + } else { + defer cursorUsageSyncService.Stop() + } + } + + if !aiCloudOnly && cfg.AntigravityUsageSyncEnabled() { + antigravityUsageSyncService := daemon.NewAntigravityUsageSyncService(cfg) + if err := antigravityUsageSyncService.Start(ctx); err != nil { + slog.Error("Failed to start Antigravity usage sync service", slog.Any("err", err)) + } else { + defer antigravityUsageSyncService.Stop() + } + } + // Create processor instance processor := daemon.NewSocketHandler(&cfg, pubsub) processor.SetConfigService(daemonConfigService) diff --git a/commands/agy.go b/commands/agy.go index 6e680e5..646b4cd 100644 --- a/commands/agy.go +++ b/commands/agy.go @@ -11,6 +11,7 @@ var AgyCommand = &cli.Command{ Subcommands: []*cli.Command{ AgyInstallCommand, AgyUninstallCommand, + AgyBackfillCommand, }, } diff --git a/commands/aicode_backfill.go b/commands/aicode_backfill.go index 1f93041..84aa3a1 100644 --- a/commands/aicode_backfill.go +++ b/commands/aicode_backfill.go @@ -33,13 +33,28 @@ var CodexBackfillCommand = &cli.Command{ Action: commandCodexBackfill, } -// aiCodeBackfillSource describes where a client keeps its transcripts and +var CursorBackfillCommand = &cli.Command{ + Name: "backfill", + Usage: "Upload Cursor token and cost usage from your Cursor account history", + Flags: aiCodeBackfillFlags(), + Action: commandCursorBackfill, +} + +var AgyBackfillCommand = &cli.Command{ + Name: "backfill", + Usage: "Upload Google Antigravity token usage from local conversation databases", + Flags: aiCodeBackfillFlags(), + Action: commandAgyBackfill, +} + +// aiCodeBackfillSource describes where a client keeps its transcripts or usage history and // how to read them. type aiCodeBackfillSource struct { clientType string name string roots func() []string parse func(roots []string, opts model.BackfillOptions) (*model.BackfillParseResult, error) + scan func(ctx context.Context, cfg model.ShellTimeConfig, opts model.BackfillOptions) (*model.BackfillParseResult, error) } func commandCCBackfill(c *cli.Context) error { @@ -60,6 +75,34 @@ func commandCodexBackfill(c *cli.Context) error { }) } +var ( + loadCursorAuthForBackfill = model.LoadCursorAuth + fetchCursorUsageForBackfill = model.FetchCursorUsageSessions +) + +func commandCursorBackfill(c *cli.Context) error { + return runAICodeBackfill(c, aiCodeBackfillSource{ + clientType: model.AICodeClientCursor, + name: "Cursor", + scan: func(ctx context.Context, cfg model.ShellTimeConfig, opts model.BackfillOptions) (*model.BackfillParseResult, error) { + auth, err := loadCursorAuthForBackfill(ctx, cfg.Cursor) + if err != nil { + return nil, fmt.Errorf("cursor auth not available (set CURSOR_API_KEY, CURSOR_AUTH_TOKEN, cursor.apiKey, or sign in to Cursor): %w", err) + } + return fetchCursorUsageForBackfill(ctx, auth, opts) + }, + }) +} + +func commandAgyBackfill(c *cli.Context) error { + return runAICodeBackfill(c, aiCodeBackfillSource{ + clientType: model.AICodeClientAntigravity, + name: "Antigravity", + roots: model.AntigravityDataRoots, + parse: model.ParseAntigravityDBs, + }) +} + func aiCodeBackfillFlags() []cli.Flag { return []cli.Flag{ &cli.StringFlag{ @@ -118,10 +161,15 @@ func runAICodeBackfill(c *cli.Context, src aiCodeBackfillSource) error { } endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} - color.Yellow.Printf("Scanning %s transcripts...\n", src.name) - parsed, err := src.parse(src.roots(), opts) + color.Yellow.Printf("Scanning %s usage...\n", src.name) + var parsed *model.BackfillParseResult + if src.scan != nil { + parsed, err = src.scan(ctx, cfg, opts) + } else { + parsed, err = src.parse(src.roots(), opts) + } if err != nil { - return fmt.Errorf("failed to read %s transcripts: %w", src.name, err) + return fmt.Errorf("failed to read %s usage: %w", src.name, err) } sessions, active := model.SelectBackfillSessions(parsed.Sessions, opts) span.SetAttributes(attribute.Int("files", parsed.Files), attribute.Int("sessions", len(sessions))) @@ -357,7 +405,7 @@ type backfillDay struct { // printBackfillDays shows per-day totals of what would be uploaded. Tokens // add up input, output and cache tokens; Codex input already includes cached -// tokens, so cache reads are only added for Claude Code. +// tokens, so cache reads are added for every other client. func printBackfillDays(clientType string, sessions []*model.BackfillSession) { if len(sessions) == 0 { return @@ -378,7 +426,7 @@ func printBackfillDays(clientType string, sessions []*model.BackfillSession) { case model.AICodeEventApiRequest, model.AICodeEventSSEEvent: d.requests++ d.tokens += derefInt(e.InputTokens) + derefInt(e.OutputTokens) + derefInt(e.CacheCreationTokens) - if clientType == model.AICodeClientClaudeCode { + if clientType != model.AICodeClientCodex { d.tokens += derefInt(e.CacheReadTokens) } } diff --git a/commands/aicode_backfill_test.go b/commands/aicode_backfill_test.go index 58d4c0e..016ca68 100644 --- a/commands/aicode_backfill_test.go +++ b/commands/aicode_backfill_test.go @@ -330,3 +330,52 @@ func TestBackfillOptionsFromFlags(t *testing.T) { _, err = parse("--since", "2026-09-30", "--until", "2026-09-01") assert.ErrorContains(t, err, "must not be after") } + +func TestCursorBackfill_UploadsSessions(t *testing.T) { + bs := setupBackfillTest(t, "test-token") + + nowMs := time.Now().Add(-2 * time.Hour).UTC().UnixMilli() + cursorAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/aiserver.v1.DashboardService/GetTeams": + _, _ = w.Write([]byte(`{"teams":[]}`)) + case "/aiserver.v1.DashboardService/GetMe": + _, _ = w.Write([]byte(`{"userId":123,"email":"dev@example.com"}`)) + case "/aiserver.v1.DashboardService/GetFilteredUsageEvents": + _, _ = fmt.Fprintf(w, `{"usageEventsDisplay":[{"timestamp":%d,"model":"claude-4-sonnet","conversationId":"cursor-conv-1","tokenUsage":{"inputTokens":1200,"outputTokens":300,"cacheReadTokens":400,"cacheWriteTokens":100,"totalCents":4.5}}]}`, nowMs) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer cursorAPI.Close() + + t.Setenv("CURSOR_AUTH_TOKEN", "test-cursor-jwt") + t.Setenv("CURSOR_API_ENDPOINT", cursorAPI.URL) + + require.NoError(t, runBackfill(t, CursorBackfillCommand, "cursor")) + + require.Len(t, bs.uploads, 1) + upload := bs.uploads[0] + assert.Equal(t, model.AICodeClientCursor, upload.ClientType) + assert.Equal(t, []string{"cursor-conv-1"}, upload.CompletedSessionIDs) + require.Len(t, upload.Events, 1) + ev := upload.Events[0] + assert.Equal(t, model.AICodeEventApiRequest, ev.EventType) + assert.Equal(t, "claude-4-sonnet", ev.Model) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 1200, *ev.InputTokens) + require.NotNil(t, ev.CostUSD) + assert.InDelta(t, 0.045, *ev.CostUSD, 1e-6) + require.Len(t, bs.completeCalls, 1) + assert.Equal(t, model.AICodeClientCursor, bs.completeCalls[0].ClientType) +} + +func TestAgyBackfill_EmptyDirSucceeds(t *testing.T) { + bs := setupBackfillTest(t, "test-token") + root := t.TempDir() + t.Setenv("ANTIGRAVITY_DATA_DIR", root) + + require.NoError(t, runBackfill(t, AgyBackfillCommand, "agy", "--dry-run")) + assert.Empty(t, bs.uploads) + assert.Empty(t, bs.completeCalls) +} diff --git a/commands/cursor.go b/commands/cursor.go index 4f723e7..7151422 100644 --- a/commands/cursor.go +++ b/commands/cursor.go @@ -10,6 +10,7 @@ var CursorCommand = &cli.Command{ Subcommands: []*cli.Command{ CursorInstallCommand, CursorUninstallCommand, + CursorBackfillCommand, }, } diff --git a/daemon/antigravity_usage_sync.go b/daemon/antigravity_usage_sync.go new file mode 100644 index 0000000..4799c0b --- /dev/null +++ b/daemon/antigravity_usage_sync.go @@ -0,0 +1,195 @@ +package daemon + +import ( + "context" + "log/slog" + "sync" + "time" + + "github.com/malamtime/cli/model" +) + +const antigravityUsageInitialLookback = 24 * time.Hour + +var ( + antigravityDataRootsFunc = model.AntigravityDataRoots + collectAntigravityDBFilesFunc = model.CollectAntigravityDBFiles + parseAntigravityDBFilesFunc = model.ParseAntigravityDBFiles + antigravityDBFingerprintFunc = model.AntigravityDBFingerprint +) + +// AntigravityUsageSyncService periodically scans local Antigravity SQLite conversation DBs +// and syncs newly updated token usage to the ShellTime server while Antigravity is running. +type AntigravityUsageSyncService struct { + config model.ShellTimeConfig + interval time.Duration + fingerprints map[string]string + hasPending bool + mu sync.Mutex + ticker *time.Ticker + stopChan chan struct{} + wg sync.WaitGroup +} + +// NewAntigravityUsageSyncService creates a new Antigravity usage sync service. +func NewAntigravityUsageSyncService(config model.ShellTimeConfig) *AntigravityUsageSyncService { + return &AntigravityUsageSyncService{ + config: config, + interval: usageSyncInterval, + fingerprints: make(map[string]string), + stopChan: make(chan struct{}), + } +} + +// Start begins the periodic Antigravity usage sync job. +func (s *AntigravityUsageSyncService) Start(ctx context.Context) error { + s.ticker = time.NewTicker(s.interval) + s.wg.Add(1) + + go func() { + defer s.wg.Done() + + s.sync(ctx) + + for { + select { + case <-s.ticker.C: + s.sync(ctx) + case <-s.stopChan: + return + case <-ctx.Done(): + return + } + } + }() + + slog.Info("Antigravity usage sync service started", slog.Duration("interval", s.interval)) + return nil +} + +// Stop stops the Antigravity usage sync service. +func (s *AntigravityUsageSyncService) Stop() { + if s.ticker != nil { + s.ticker.Stop() + } + close(s.stopChan) + s.wg.Wait() + slog.Info("Antigravity usage sync service stopped") +} + +func (s *AntigravityUsageSyncService) sync(parentCtx context.Context) { + if s.config.Token == "" { + return + } + + s.mu.Lock() + pending := s.hasPending + s.mu.Unlock() + + if !isAntigravityRunning() && !pending { + slog.Debug("Skipping antigravity usage sync", slog.String("reason", "antigravity_not_running")) + return + } + + if parentCtx == nil { + parentCtx = context.Background() + } + ctx, cancel := context.WithTimeout(parentCtx, 30*time.Second) + defer cancel() + + if err := s.syncOnce(ctx); err != nil { + slog.Warn("Failed to sync antigravity usage", slog.Any("err", err)) + } +} + +func (s *AntigravityUsageSyncService) syncOnce(ctx context.Context) error { + now := time.Now() + since := now.Add(-antigravityUsageInitialLookback) + + roots := antigravityDataRootsFunc() + files, err := collectAntigravityDBFilesFunc(roots, since) + if err != nil { + return err + } + if len(files) == 0 { + s.mu.Lock() + s.hasPending = false + s.mu.Unlock() + return nil + } + + s.mu.Lock() + var changed []string + nextFPs := make(map[string]string, len(files)) + for _, path := range files { + fp, _, err := antigravityDBFingerprintFunc(path) + if err != nil { + continue + } + nextFPs[path] = fp + if prev, ok := s.fingerprints[path]; !ok || prev != fp { + changed = append(changed, path) + } + } + s.mu.Unlock() + + if len(changed) == 0 { + s.mu.Lock() + s.hasPending = false + s.mu.Unlock() + return nil + } + + parseOpts := model.BackfillOptions{ + Since: since, + Until: now, + Now: now, + } + parsed, err := parseAntigravityDBFilesFunc(changed, parseOpts) + if err != nil { + return err + } + activeCount := 0 + if parsed != nil && len(parsed.Sessions) > 0 { + // Files were already pruned by mtime via CollectAntigravityDBFiles; omit Since here so + // multi-day conversations that received new events today are not dropped by their Start time. + uploadOpts := model.BackfillOptions{ + Until: now, + Now: now, + } + var uploaded int + uploaded, activeCount, err = uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientAntigravity, parsed.Sessions, uploadOpts, false) + if err != nil { + return err + } + if uploaded > 0 { + slog.Debug("Synced antigravity token usage", + slog.Int("events", uploaded), + slog.Int("sessions", len(parsed.Sessions))) + } + } + + failed := make(map[string]bool) + if parsed != nil { + for _, p := range parsed.FailedFiles { + failed[p] = true + } + } + if activeCount > 0 { + // Re-scan changed DBs on the next tick so recently active sessions upload once settled. + for _, p := range changed { + failed[p] = true + } + } + + s.mu.Lock() + s.hasPending = activeCount > 0 || (parsed != nil && len(parsed.FailedFiles) > 0) + for path, fp := range nextFPs { + if failed[path] { + continue + } + s.fingerprints[path] = fp + } + s.mu.Unlock() + return nil +} diff --git a/daemon/antigravity_usage_sync_test.go b/daemon/antigravity_usage_sync_test.go new file mode 100644 index 0000000..95993b1 --- /dev/null +++ b/daemon/antigravity_usage_sync_test.go @@ -0,0 +1,99 @@ +package daemon + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/malamtime/cli/model" + "github.com/stretchr/testify/assert" +) + +func TestAntigravityUsageSyncService_SkipsUnchangedDBs(t *testing.T) { + origList := listProcessNamesFunc + origRoots := antigravityDataRootsFunc + origCollect := collectAntigravityDBFilesFunc + origParse := parseAntigravityDBFilesFunc + origFP := antigravityDBFingerprintFunc + t.Cleanup(func() { + listProcessNamesFunc = origList + antigravityDataRootsFunc = origRoots + collectAntigravityDBFilesFunc = origCollect + parseAntigravityDBFilesFunc = origParse + antigravityDBFingerprintFunc = origFP + }) + + var backfillHits, completeHits, parseCalls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/cc/backfill/sessions": + _ = json.NewEncoder(w).Encode(model.AICodeBackfillSessionsResponse{}) + case "/api/v1/cc/backfill": + backfillHits.Add(1) + _ = json.NewEncoder(w).Encode(model.AICodeBackfillResponse{Success: true, Accepted: 1, Summarized: 1}) + case "/api/v1/cc/backfill/complete": + completeHits.Add(1) + _ = json.NewEncoder(w).Encode(map[string]bool{"success": true}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + listProcessNamesFunc = func() ([]string, error) { return []string{"/usr/local/bin/agy"}, nil } + antigravityDataRootsFunc = func() []string { return []string{"/fake/agy"} } + collectAntigravityDBFilesFunc = func([]string, time.Time) ([]string, error) { + return []string{"/fake/agy/sess-1.db"}, nil + } + fp := "100:1/-" + antigravityDBFingerprintFunc = func(string) (string, time.Time, error) { + return fp, time.Now(), nil + } + now := time.Now().Add(-time.Hour).UTC() + inTok := 200 + parseAntigravityDBFilesFunc = func([]string, model.BackfillOptions) (*model.BackfillParseResult, error) { + parseCalls.Add(1) + return &model.BackfillParseResult{ + Sessions: []*model.BackfillSession{{ + ID: "sess-1", + ClientType: model.AICodeClientAntigravity, + Start: now, + End: now, + Events: []model.AICodeBackfillEvent{{ + EventID: "bf1:fedcba9876543210fedcba9876543210fedcba98", + EventType: model.AICodeEventApiRequest, + ClientType: model.AICodeClientAntigravity, + Timestamp: now.Unix(), + SessionID: "sess-1", + Model: "gemini-3.1-pro", + InputTokens: &inTok, + }}, + }}, + }, nil + } + + svc := NewAntigravityUsageSyncService(model.ShellTimeConfig{ + Token: "st_test", + APIEndpoint: srv.URL, + }) + + // First tick parses and uploads. + svc.sync(context.Background()) + assert.Equal(t, int32(1), parseCalls.Load()) + assert.Equal(t, int32(1), backfillHits.Load()) + assert.Equal(t, int32(1), completeHits.Load()) + + // Second tick with unchanged fingerprint skips parsing entirely. + svc.sync(context.Background()) + assert.Equal(t, int32(1), parseCalls.Load()) + + // Third tick with updated WAL fingerprint re-parses and uploads. + fp = "100:1/50:2" + svc.sync(context.Background()) + assert.Equal(t, int32(2), parseCalls.Load()) + assert.Equal(t, int32(2), backfillHits.Load()) +} diff --git a/daemon/cursor_ratelimit.go b/daemon/cursor_ratelimit.go new file mode 100644 index 0000000..f7ff59c --- /dev/null +++ b/daemon/cursor_ratelimit.go @@ -0,0 +1,193 @@ +package daemon + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "math" + "net/http" + "strconv" + "strings" + "time" + + "github.com/malamtime/cli/model" +) + +var ( + loadCursorAuthFunc = model.LoadCursorAuth + fetchCursorQuotaFunc = fetchCursorQuota +) + +// CursorRateLimitData holds the parsed billing-cycle quota data from Cursor's DashboardService. +type CursorRateLimitData struct { + Plan string + Windows []CursorRateLimitWindow +} + +// CursorRateLimitWindow holds a single Cursor monthly quota window. +type CursorRateLimitWindow struct { + LimitID string + LimitName string + UsagePercentage float64 + ResetAt int64 // Unix seconds + WindowDurationMinutes int +} + +type cursorCurrentPeriodUsageResponse struct { + BillingCycleStart any `json:"billingCycleStart"` + BillingCycleEnd any `json:"billingCycleEnd"` + PlanUsage *cursorPlanUsageBody `json:"planUsage"` +} + +type cursorPlanUsageBody struct { + TotalPercentUsed *float64 `json:"totalPercentUsed"` + AutoPercentUsed *float64 `json:"autoPercentUsed"` + APIPercentUsed *float64 `json:"apiPercentUsed"` +} + +// fetchCursorQuota calls Cursor's GetCurrentPeriodUsage RPC and maps it into quota windows. +func fetchCursorQuota(ctx context.Context, auth *model.CursorAuthData) (*CursorRateLimitData, error) { + client := &http.Client{ + Timeout: 10 * time.Second, + Transport: model.HTTPTransport(), + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } + return fetchCursorQuotaFromEndpoint(ctx, auth, client) +} + +func fetchCursorQuotaFromEndpoint(ctx context.Context, auth *model.CursorAuthData, client *http.Client) (*CursorRateLimitData, error) { + if auth == nil || strings.TrimSpace(auth.AccessToken) == "" { + return nil, model.ErrCursorAuthMissing + } + endpoint := strings.TrimRight(strings.TrimSpace(auth.Endpoint), "/") + if endpoint == "" { + endpoint = model.DefaultCursorAPIEndpoint + } + + req, err := http.NewRequestWithContext( + ctx, + http.MethodPost, + endpoint+"/aiserver.v1.DashboardService/GetCurrentPeriodUsage", + bytes.NewReader([]byte("{}")), + ) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+auth.AccessToken) + req.Header.Set("connect-protocol-version", "1") + req.Header.Set("x-cursor-client-type", "cli") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "shelltime-daemon") + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + return nil, model.ErrCursorTokenInvalid + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("cursor quota API returned status %d", resp.StatusCode) + } + + var body cursorCurrentPeriodUsageResponse + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return nil, fmt.Errorf("failed to decode cursor quota response: %w", err) + } + + return mapCursorCurrentPeriodUsage(&body) +} + +func mapCursorCurrentPeriodUsage(body *cursorCurrentPeriodUsageResponse) (*CursorRateLimitData, error) { + if body == nil || body.PlanUsage == nil { + return &CursorRateLimitData{}, nil + } + + cycleEndMs := parseCursorMillis(body.BillingCycleEnd) + cycleStartMs := parseCursorMillis(body.BillingCycleStart) + if cycleEndMs <= 0 { + return &CursorRateLimitData{}, nil + } + + resetAtSec := cycleEndMs / 1000 + windowDurationMinutes := 0 + if cycleStartMs > 0 && cycleEndMs > cycleStartMs { + windowDurationMinutes = int(math.Round(float64(cycleEndMs-cycleStartMs) / 60_000.0)) + } + + specs := []struct { + id string + name string + value *float64 + }{ + {id: "totalPercentUsed", name: "Overall", value: body.PlanUsage.TotalPercentUsed}, + {id: "autoPercentUsed", name: "Cursor Models", value: body.PlanUsage.AutoPercentUsed}, + {id: "apiPercentUsed", name: "Other Models", value: body.PlanUsage.APIPercentUsed}, + } + + windows := make([]CursorRateLimitWindow, 0, len(specs)) + for _, spec := range specs { + if spec.value == nil || math.IsNaN(*spec.value) || math.IsInf(*spec.value, 0) { + continue + } + pct := *spec.value + if pct < 0 { + pct = 0 + } else if pct > 100 { + pct = 100 + } + windows = append(windows, CursorRateLimitWindow{ + LimitID: spec.id, + LimitName: spec.name, + UsagePercentage: pct, + ResetAt: resetAtSec, + WindowDurationMinutes: windowDurationMinutes, + }) + } + + return &CursorRateLimitData{ + Windows: windows, + }, nil +} + +func parseCursorMillis(v any) int64 { + switch t := v.(type) { + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) { + return 0 + } + return int64(t) + case int64: + return t + case string: + trimmed := strings.TrimSpace(t) + if trimmed == "" { + return 0 + } + f, err := strconv.ParseFloat(trimmed, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0 + } + return int64(f) + default: + return 0 + } +} + +// CursorSyncSkipReason classifies expected non-error skip reasons for Cursor usage sync. +func CursorSyncSkipReason(err error) (string, bool) { + switch { + case errors.Is(err, model.ErrCursorAuthMissing): + return "missing_cursor_auth", true + case errors.Is(err, model.ErrCursorTokenInvalid): + return "invalid_cursor_token", true + default: + return "", false + } +} diff --git a/daemon/cursor_usage_sync.go b/daemon/cursor_usage_sync.go new file mode 100644 index 0000000..a1a6b96 --- /dev/null +++ b/daemon/cursor_usage_sync.go @@ -0,0 +1,380 @@ +package daemon + +import ( + "context" + "encoding/json" + "log/slog" + "os" + "path/filepath" + "sync" + "time" + + "github.com/malamtime/cli/model" +) + +const ( + cursorUsageInitialLookback = 24 * time.Hour + cursorUsageSyncOverlap = 45 * time.Minute + cursorUsageStateFileName = "cursor_usage_sync_state.json" +) + +var fetchCursorUsageSessionsFunc = model.FetchCursorUsageSessions + +// CursorUsageSyncService periodically fetches Cursor subscription quota and recent billed +// token usage and syncs them to the ShellTime server while Cursor is running. +type CursorUsageSyncService struct { + config model.ShellTimeConfig + interval time.Duration + statePath string + hasPending bool + mu sync.Mutex + ticker *time.Ticker + stopChan chan struct{} + wg sync.WaitGroup +} + +type cursorUsageSyncState struct { + LastSyncedUnix int64 `json:"lastSyncedUnix"` +} + +// NewCursorUsageSyncService creates a new Cursor usage sync service. +func NewCursorUsageSyncService(config model.ShellTimeConfig) *CursorUsageSyncService { + statePath := "" + if home, err := os.UserHomeDir(); err == nil && home != "" { + statePath = filepath.Join(home, model.COMMAND_BASE_STORAGE_FOLDER, cursorUsageStateFileName) + } + return &CursorUsageSyncService{ + config: config, + interval: usageSyncInterval, + statePath: statePath, + stopChan: make(chan struct{}), + } +} + +// Start begins the periodic Cursor usage sync job. +func (s *CursorUsageSyncService) Start(ctx context.Context) error { + s.ticker = time.NewTicker(s.interval) + s.wg.Add(1) + + go func() { + defer s.wg.Done() + + s.sync(ctx) + + for { + select { + case <-s.ticker.C: + s.sync(ctx) + case <-s.stopChan: + return + case <-ctx.Done(): + return + } + } + }() + + slog.Info("Cursor usage sync service started", slog.Duration("interval", s.interval)) + return nil +} + +// Stop stops the Cursor usage sync service. +func (s *CursorUsageSyncService) Stop() { + if s.ticker != nil { + s.ticker.Stop() + } + close(s.stopChan) + s.wg.Wait() + slog.Info("Cursor usage sync service stopped") +} + +func (s *CursorUsageSyncService) sync(parentCtx context.Context) { + if s.config.Token == "" { + return + } + + running := isCursorRunning() + s.mu.Lock() + pending := s.hasPending + s.mu.Unlock() + + if !running && !pending { + slog.Debug("Skipping cursor usage sync", slog.String("reason", "cursor_not_running")) + return + } + + if parentCtx == nil { + parentCtx = context.Background() + } + ctx, cancel := context.WithTimeout(parentCtx, 30*time.Second) + defer cancel() + + auth, err := loadCursorAuthFunc(ctx, s.config.Cursor) + if err != nil { + if reason, ok := CursorSyncSkipReason(err); ok { + slog.Debug("Skipping cursor usage sync", slog.String("reason", reason)) + return + } + slog.Warn("Failed to load cursor auth", slog.Any("err", err)) + return + } + + if running { + if err := syncCursorQuota(ctx, s.config, auth); err != nil { + if reason, ok := CursorSyncSkipReason(err); ok { + slog.Info("Skipping cursor quota sync", slog.String("reason", reason)) + } else { + slog.Warn("Failed to sync cursor quota", slog.Any("err", err)) + } + } + } + + if err := s.syncTokenUsage(ctx, auth); err != nil { + if reason, ok := CursorSyncSkipReason(err); ok { + slog.Info("Skipping cursor token usage sync", slog.String("reason", reason)) + } else { + slog.Warn("Failed to sync cursor token usage", slog.Any("err", err)) + } + } +} + +func syncCursorQuota(ctx context.Context, config model.ShellTimeConfig, auth *model.CursorAuthData) error { + if config.Token == "" { + return nil + } + + quota, err := fetchCursorQuotaFunc(ctx, auth) + if err != nil { + return err + } + if quota == nil || len(quota.Windows) == 0 { + return nil + } + + return sendCursorUsageToServer(ctx, config, quota) +} + +func sendCursorUsageToServer(ctx context.Context, config model.ShellTimeConfig, usage *CursorRateLimitData) error { + if config.Token == "" || usage == nil || len(usage.Windows) == 0 { + return nil + } + + type usageWindow struct { + LimitID string `json:"limit_id"` + LimitName string `json:"limit_name"` + UsagePercentage float64 `json:"usage_percentage"` + ResetsAt string `json:"resets_at"` + WindowDurationMinutes int `json:"window_duration_minutes"` + } + type usagePayload struct { + SchemaVersion int `json:"schema_version"` + Plan string `json:"plan"` + Windows []usageWindow `json:"windows"` + } + + windows := make([]usageWindow, len(usage.Windows)) + for i, w := range usage.Windows { + windows[i] = usageWindow{ + LimitID: w.LimitID, + LimitName: w.LimitName, + UsagePercentage: w.UsagePercentage, + ResetsAt: time.Unix(w.ResetAt, 0).UTC().Format(time.RFC3339), + WindowDurationMinutes: w.WindowDurationMinutes, + } + } + + payload := usagePayload{ + SchemaVersion: 1, + Plan: usage.Plan, + Windows: windows, + } + + return model.SendHTTPRequestJSON(model.HTTPRequestOptions[usagePayload, any]{ + Context: ctx, + Endpoint: model.Endpoint{ + Token: config.Token, + APIEndpoint: config.APIEndpoint, + }, + Method: "POST", + Path: "/api/v1/cursor-usage", + Payload: payload, + Timeout: 5 * time.Second, + }) +} + +func (s *CursorUsageSyncService) syncTokenUsage(ctx context.Context, auth *model.CursorAuthData) error { + now := time.Now() + since := now.Add(-cursorUsageInitialLookback) + if st := s.loadState(); st.LastSyncedUnix > 0 { + candidate := time.Unix(st.LastSyncedUnix, 0).Add(-cursorUsageSyncOverlap) + if candidate.After(since) && candidate.Before(now) { + since = candidate + } + } + + opts := model.BackfillOptions{ + Since: since, + Until: now, + Now: now, + } + parsed, err := fetchCursorUsageSessionsFunc(ctx, auth, opts) + if err != nil { + return err + } + if parsed == nil || len(parsed.Sessions) == 0 { + s.mu.Lock() + s.hasPending = false + s.mu.Unlock() + s.saveState(cursorUsageSyncState{LastSyncedUnix: now.Unix()}) + return nil + } + + uploaded, activeCount, err := uploadDaemonUsageSessions(ctx, s.config, model.AICodeClientCursor, parsed.Sessions, opts, true) + if err != nil { + return err + } + if uploaded > 0 { + slog.Debug("Synced cursor token usage", slog.Int("events", uploaded), slog.Int("sessions", len(parsed.Sessions))) + } + s.mu.Lock() + s.hasPending = activeCount > 0 + s.mu.Unlock() + if activeCount == 0 { + s.saveState(cursorUsageSyncState{LastSyncedUnix: now.Unix()}) + } + return nil +} + +func (s *CursorUsageSyncService) loadState() cursorUsageSyncState { + if s.statePath == "" { + return cursorUsageSyncState{} + } + raw, err := os.ReadFile(s.statePath) + if err != nil { + return cursorUsageSyncState{} + } + var st cursorUsageSyncState + if err := json.Unmarshal(raw, &st); err != nil { + return cursorUsageSyncState{} + } + return st +} + +func (s *CursorUsageSyncService) saveState(st cursorUsageSyncState) { + if s.statePath == "" { + return + } + raw, err := json.Marshal(st) + if err != nil { + return + } + _ = os.MkdirAll(filepath.Dir(s.statePath), 0700) + _ = os.WriteFile(s.statePath, raw, 0600) +} + +// uploadDaemonUsageSessions filters settled sessions within opts (respecting the backfill settle +// window so in-progress sessions are not finalized early), checks server backfill status, and +// uploads new/updated events idempotently via /api/v1/cc/backfill + /api/v1/cc/backfill/complete. +// When skipCountCheck is true (for incremental window fetches like Cursor), already-backfilled +// sessions are still uploaded so server-side event_id deduplication accepts new events. +func uploadDaemonUsageSessions( + ctx context.Context, + config model.ShellTimeConfig, + clientType string, + sessions []*model.BackfillSession, + opts model.BackfillOptions, + skipCountCheck bool, +) (int, int, error) { + if config.Token == "" || len(sessions) == 0 { + return 0, 0, nil + } + settled, activeCount := model.SelectBackfillSessions(sessions, opts) + if len(settled) == 0 { + return 0, activeCount, nil + } + sessions = settled + endpoint := model.Endpoint{ + Token: config.Token, + APIEndpoint: config.APIEndpoint, + } + + sessionIDs := make([]string, 0, len(sessions)) + for _, sess := range sessions { + if len(sess.Events) > 0 { + sessionIDs = append(sessionIDs, sess.ID) + } + } + if len(sessionIDs) == 0 { + return 0, activeCount, nil + } + + statuses := map[string]model.AICodeBackfillSessionStatus{} + for start := 0; start < len(sessionIDs); start += model.AICodeBackfillMaxSessionIDs { + end := min(start+model.AICodeBackfillMaxSessionIDs, len(sessionIDs)) + rows, err := model.FetchAICodeBackfillStatus(ctx, endpoint, clientType, sessionIDs[start:end]) + if err != nil { + return 0, activeCount, err + } + for _, st := range rows { + statuses[st.SessionID] = st + } + } + + var toUpload []*model.BackfillSession + for _, sess := range sessions { + if len(sess.Events) == 0 { + continue + } + st, ok := statuses[sess.ID] + if !ok { + toUpload = append(toUpload, sess) + continue + } + if st.Status == model.AICodeBackfillStatusLive || st.Status == model.AICodeBackfillStatusArchived { + continue + } + if !skipCountCheck && st.Status == model.AICodeBackfillStatusBackfilled && st.EventCount >= len(sess.Events) { + continue + } + toUpload = append(toUpload, sess) + } + if len(toUpload) == 0 { + return 0, activeCount, nil + } + + batches := model.PackBackfillBatches( + clientType, + toUpload, + model.AICodeBackfillMaxEvents, + model.AICodeBackfillMaxBatchBytes, + model.AICodeBackfillMaxCompleted, + ) + + accepted := 0 + for _, batch := range batches { + resp, err := model.SendAICodeBackfill(ctx, endpoint, batch) + if err != nil { + return accepted, activeCount, err + } + accepted += resp.Accepted + } + + from := toUpload[0].Start + to := toUpload[0].End + for _, sess := range toUpload[1:] { + if sess.Start.Before(from) { + from = sess.Start + } + if sess.End.After(to) { + to = sess.End + } + } + if err := model.CompleteAICodeBackfill(ctx, endpoint, model.AICodeBackfillCompleteRequest{ + ClientType: clientType, + From: from, + To: to, + }); err != nil { + slog.Warn("Failed to finalize daemon usage sync", slog.String("clientType", clientType), slog.Any("err", err)) + } + + return accepted, activeCount, nil +} diff --git a/daemon/cursor_usage_sync_test.go b/daemon/cursor_usage_sync_test.go new file mode 100644 index 0000000..3d981ca --- /dev/null +++ b/daemon/cursor_usage_sync_test.go @@ -0,0 +1,137 @@ +package daemon + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/malamtime/cli/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMapCursorCurrentPeriodUsage(t *testing.T) { + total := 42.5 + auto := 30.0 + api := 110.0 // clamped to 100 + start := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC).UnixMilli() + end := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC).UnixMilli() + + got, err := mapCursorCurrentPeriodUsage(&cursorCurrentPeriodUsageResponse{ + BillingCycleStart: float64(start), + BillingCycleEnd: float64(end), + PlanUsage: &cursorPlanUsageBody{ + TotalPercentUsed: &total, + AutoPercentUsed: &auto, + APIPercentUsed: &api, + }, + }) + require.NoError(t, err) + require.Len(t, got.Windows, 3) + + assert.Equal(t, "totalPercentUsed", got.Windows[0].LimitID) + assert.Equal(t, "Overall", got.Windows[0].LimitName) + assert.InDelta(t, 42.5, got.Windows[0].UsagePercentage, 1e-6) + assert.Equal(t, end/1000, got.Windows[0].ResetAt) + assert.Equal(t, 30*24*60, got.Windows[0].WindowDurationMinutes) + + assert.Equal(t, "autoPercentUsed", got.Windows[1].LimitID) + assert.Equal(t, "Cursor Models", got.Windows[1].LimitName) + + assert.Equal(t, "apiPercentUsed", got.Windows[2].LimitID) + assert.Equal(t, "Other Models", got.Windows[2].LimitName) + assert.Equal(t, 100.0, got.Windows[2].UsagePercentage) +} + +func TestCursorUsageSyncService_SyncsQuotaAndTokens(t *testing.T) { + origList := listProcessNamesFunc + origAuth := loadCursorAuthFunc + origQuota := fetchCursorQuotaFunc + origUsage := fetchCursorUsageSessionsFunc + t.Cleanup(func() { + listProcessNamesFunc = origList + loadCursorAuthFunc = origAuth + fetchCursorQuotaFunc = origQuota + fetchCursorUsageSessionsFunc = origUsage + }) + + var quotaHits, statusHits, backfillHits, completeHits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/cursor-usage": + quotaHits.Add(1) + w.WriteHeader(http.StatusNoContent) + case "/api/v1/cc/backfill/sessions": + statusHits.Add(1) + _ = json.NewEncoder(w).Encode(model.AICodeBackfillSessionsResponse{}) + case "/api/v1/cc/backfill": + backfillHits.Add(1) + _ = json.NewEncoder(w).Encode(model.AICodeBackfillResponse{Success: true, Accepted: 1, Summarized: 1}) + case "/api/v1/cc/backfill/complete": + completeHits.Add(1) + _ = json.NewEncoder(w).Encode(map[string]bool{"success": true}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + listProcessNamesFunc = func() ([]string, error) { return []string{"/Applications/Cursor.app/Contents/MacOS/Cursor"}, nil } + loadCursorAuthFunc = func(context.Context, *model.CursorConfig) (*model.CursorAuthData, error) { + return &model.CursorAuthData{AccessToken: "tok", Endpoint: "https://api2.cursor.sh"}, nil + } + fetchCursorQuotaFunc = func(context.Context, *model.CursorAuthData) (*CursorRateLimitData, error) { + return &CursorRateLimitData{ + Windows: []CursorRateLimitWindow{{ + LimitID: "totalPercentUsed", + LimitName: "Overall", + UsagePercentage: 55, + ResetAt: time.Now().Add(24 * time.Hour).Unix(), + WindowDurationMinutes: 43200, + }}, + }, nil + } + now := time.Now().Add(-time.Hour).UTC() + inTok := 100 + fetchCursorUsageSessionsFunc = func(context.Context, *model.CursorAuthData, model.BackfillOptions) (*model.BackfillParseResult, error) { + return &model.BackfillParseResult{ + Sessions: []*model.BackfillSession{{ + ID: "cursor-sess-1", + ClientType: model.AICodeClientCursor, + Start: now, + End: now, + Events: []model.AICodeBackfillEvent{{ + EventID: "bf1:0123456789abcdef0123456789abcdef01234567", + EventType: model.AICodeEventApiRequest, + ClientType: model.AICodeClientCursor, + Timestamp: now.Unix(), + SessionID: "cursor-sess-1", + Model: "claude-sonnet-4-5", + InputTokens: &inTok, + }}, + }}, + }, nil + } + + svc := NewCursorUsageSyncService(model.ShellTimeConfig{ + Token: "st_test", + APIEndpoint: srv.URL, + }) + svc.statePath = filepath.Join(t.TempDir(), "state.json") + svc.sync(context.Background()) + + assert.Equal(t, int32(1), quotaHits.Load()) + assert.Equal(t, int32(1), statusHits.Load()) + assert.Equal(t, int32(1), backfillHits.Load()) + assert.Equal(t, int32(1), completeHits.Load()) + + // When Cursor is not running, sync skips immediately. + listProcessNamesFunc = func() ([]string, error) { return []string{"zsh"}, nil } + svc.sync(context.Background()) + assert.Equal(t, int32(1), quotaHits.Load()) +} diff --git a/daemon/usage_sync.go b/daemon/usage_sync.go index 908d9dd..8f6e471 100644 --- a/daemon/usage_sync.go +++ b/daemon/usage_sync.go @@ -8,13 +8,15 @@ import ( "time" ) -// usageSyncInterval is how often the daemon syncs Claude and Codex usage in the background. +// usageSyncInterval is how often the daemon syncs Claude, Codex, Cursor, and Antigravity usage in the background. const usageSyncInterval = 10 * time.Minute // Process name keywords (lowercase) that mean an AI coding client is running. var ( - claudeProcessKeywords = []string{"claude"} - codexProcessKeywords = []string{"codex", "chatgpt"} + claudeProcessKeywords = []string{"claude"} + codexProcessKeywords = []string{"codex", "chatgpt"} + cursorProcessKeywords = []string{"cursor"} + antigravityProcessKeywords = []string{"antigravity"} ) // listProcessNamesFunc lists running process names. It is a var so tests can stub it. @@ -63,3 +65,22 @@ func isClaudeRunning() bool { func isCodexRunning() bool { return isProcessRunning(codexProcessKeywords) } + +func isCursorRunning() bool { + return isProcessRunning(cursorProcessKeywords) +} + +func isAntigravityRunning() bool { + names, err := listProcessNamesFunc() + if err != nil { + slog.Debug("Failed to list processes, assuming client is running", slog.Any("err", err)) + return true + } + for _, name := range names { + base := filepath.Base(name) + if strings.EqualFold(base, "agy") || matchKnownName(base, antigravityProcessKeywords) != "" { + return true + } + } + return false +} diff --git a/docs/CONFIG.md b/docs/CONFIG.md index def3fe4..e2ee34d 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -354,6 +354,28 @@ agentHooks: `shelltime config disable agentHooks.sendContent` writes this for you. The daemon reads the setting for each batch, so no restart is needed. +### Cursor and Antigravity Usage Collection + +In addition to hooks, `shelltime-daemon` collects token usage (and Cursor subscription quota) every 10 minutes while the agent is running when enabled (follows `aiCodeOtel.enabled` by default, or `cursor.enabled` / `antigravity.enabled` explicitly; skipped in `aiCloudOnly` mode). `shelltime cursor backfill` and `shelltime agy backfill` upload historical usage on demand: + +- **Cursor**: Reads `CURSOR_AUTH_TOKEN`, `CURSOR_API_KEY`, `cursor.apiKey` in config, `~/.cursor/auth.json`, or Cursor IDE's local `state.vscdb` (read-only). Credentials stay on your machine; only quota windows (`/api/v1/cursor-usage`) and token/cost events (`/api/v1/cc/backfill`) are sent to ShellTime. +- **Antigravity (`agy`)**: Reads local SQLite conversation databases under `~/.gemini/antigravity*` and `~/.config/antigravity` (or `ANTIGRAVITY_DATA_DIR`). + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `cursor.enabled` | boolean | follows `aiCodeOtel.enabled` (or `true` if `cursor.apiKey` is set) | Enable or disable periodic Cursor quota & token usage sync in the daemon | +| `cursor.apiKey` | string | `""` | Optional Cursor API key for usage & quota sync (exchanged locally for a bearer token) | +| `cursor.apiEndpoint` | string | `"https://api2.cursor.sh"` | Optional custom Cursor API endpoint (also configurable via `CURSOR_API_ENDPOINT`) | +| `antigravity.enabled` | boolean | follows `aiCodeOtel.enabled` | Enable or disable periodic Antigravity usage sync in the daemon | + +```yaml +cursor: + enabled: true + apiKey: "key_..." +antigravity: + enabled: true +``` + ## Codex Usage Tracking Codex usage has two separate data paths: diff --git a/go.mod b/go.mod index fad119a..8f348ba 100644 --- a/go.mod +++ b/go.mod @@ -24,11 +24,12 @@ require ( go.opentelemetry.io/otel/trace v1.39.0 go.opentelemetry.io/proto/otlp v1.9.0 golang.org/x/net v0.48.0 - golang.org/x/sys v0.39.0 + golang.org/x/sys v0.49.0 golang.org/x/term v0.38.0 google.golang.org/grpc v1.77.0 google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v3 v3.0.1 + modernc.org/sqlite v1.63.0 ) require ( @@ -46,6 +47,7 @@ require ( github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect github.com/cyphar/filepath-securejoin v0.6.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect @@ -58,14 +60,16 @@ require ( github.com/lithammer/fuzzysearch v1.1.8 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 // indirect github.com/olekukonko/errors v1.1.0 // indirect github.com/olekukonko/ll v0.1.3 // indirect github.com/pjbgf/sha1cd v0.5.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/stretchr/objx v0.5.3 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect @@ -87,4 +91,7 @@ require ( google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect ) diff --git a/go.sum b/go.sum index fb86f4e..107fbf4 100644 --- a/go.sum +++ b/go.sum @@ -50,6 +50,8 @@ github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= @@ -75,6 +77,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -86,6 +90,8 @@ github.com/gookit/color v1.6.0 h1:JjJXBTk1ETNyqyilJhkTXJYYigHG24TM9Xa2M1xAhRA= github.com/gookit/color v1.6.0/go.mod h1:9ACFc7/1IpHGBW8RwuDm/0YEnhg3dwwXpoMsmtyHfjs= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E= github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= @@ -113,11 +119,13 @@ github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0 github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc= @@ -149,6 +157,8 @@ github.com/pterm/pterm v0.12.36/go.mod h1:NjiL09hFhT/vWjQHSj1athJpx6H8cjpHXNAK5b github.com/pterm/pterm v0.12.40/go.mod h1:ffwPLwlbXxP+rxT0GsgDTzS3y3rmpAO1NMjUkGTYf8s= github.com/pterm/pterm v0.12.82 h1:+D9wYhCaeaK0FIQoZtqbNQuNpe2lB2tajKKsTd5paVQ= github.com/pterm/pterm v0.12.82/go.mod h1:TyuyrPjnxfwP+ccJdBTeWHtd/e0ybQHkOS/TakajZCw= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= @@ -227,6 +237,8 @@ golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -236,8 +248,8 @@ golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -249,9 +261,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= -golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -270,6 +281,8 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= @@ -294,3 +307,31 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.63.0 h1:ClxazqRFNfr7XPHTVLbyzTVz2PjWPz+BfJNu2e8JDMs= +modernc.org/sqlite v1.63.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/model/aicode_backfill_antigravity.go b/model/aicode_backfill_antigravity.go new file mode 100644 index 0000000..e413a0c --- /dev/null +++ b/model/aicode_backfill_antigravity.go @@ -0,0 +1,1034 @@ +package model + +import ( + "database/sql" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + "unicode/utf8" + + _ "modernc.org/sqlite" +) + +// Offline fallback for Antigravity records without explicit model names. +// Cross-checked against t3code's antigravityUsageReader.ts. +var antigravityModelIDs = map[int]string{ + 246: "gemini-2.5-pro", + 312: "gemini-2.5-flash", + 313: "gemini-2.5-flash-thinking", + 329: "gemini-2.5-flash-thinking", + 330: "gemini-2.5-flash-lite", + 281: "claude-sonnet-4", + 282: "claude-sonnet-4", + 290: "claude-opus-4", + 291: "claude-opus-4", + 333: "claude-sonnet-4-5", + 334: "claude-sonnet-4-5", + 340: "claude-haiku-4-5", + 341: "claude-haiku-4-5", + 342: "gpt-oss-120b-medium", + 1026: "claude-opus-4-6", + 1035: "claude-sonnet-4-6", + 1016: "gemini-3.1-pro", + 1036: "gemini-3.1-pro", + 1037: "gemini-3.1-pro", + 1018: "gemini-3-flash-preview", + 1084: "gemini-3-flash-preview", + 1047: "gemini-3-flash-preview", + 1020: "gemini-3.5-flash-medium", + 1021: "gemini-3.1-flash-image", + 1050: "gemini-3.1-flash-lite", + 1071: "gemini-3.6-flash-high", + 1072: "gemini-3.6-flash-medium", + 1073: "gemini-3.6-flash-low", + 1132: "gemini-3.5-flash-high", + 1133: "gemini-3.5-flash-high", + 1187: "gemini-3.5-flash-extra-low", + 1196: "gemini-3.6-flash", + 1266: "gemini-3.6-flash", + 1298: "gemini-3.7-flash-high", + 1299: "gemini-3.7-flash-medium", + 1300: "gemini-3.7-flash-low", + 1301: "gemini-3.7-flash-tiered", + 1318: "gemini-3.8-flash-high", + 1319: "gemini-3.8-flash-medium", + 1320: "gemini-3.8-flash-low", + 1322: "gemini-3.8-flash-tiered", + 1402: "claude-opus-5-5", + 1417: "gemini-4-argon", + 1418: "gemini-4-argon", + 1419: "gemini-4-argon", + 1427: "gemini-4-carbon", + 1437: "gemini-4-carbon", + 1525: "gemini-4-hydrogen", + 1526: "gemini-4-hydrogen", + 1527: "gemini-4-hydrogen", + 1532: "gemini-4-neon", + 1533: "gemini-4-neon", + 1537: "gemini-pro-orchestrator-neon", + 1667: "gemini-pro-orchestrator", + 1669: "gemini-4-hydrogen-orchestrator", +} + +var ( + agyParenSuffixRe = regexp.MustCompile(`\s*\(([^)]*)\)\s*$`) + agySpaceRe = regexp.MustCompile(`\s+`) + agyClaudeVersionRe = regexp.MustCompile(`^claude-(\d+(?:\.\d+)?)-(sonnet|opus|haiku)`) + agyConcreteModelRe = regexp.MustCompile(`^(?:gemini-\d|claude-(?:sonnet|opus|haiku)-\d|gpt-)`) + agyFlashAgentAliasRe = regexp.MustCompile(`^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$`) + agyModelPrefixRe = regexp.MustCompile(`^model[_-]`) + agyRateSuffixRe = regexp.MustCompile(`-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator|trial|n|r)$`) +) + +// AntigravityDataRoots returns the directories holding Antigravity conversation SQLite DBs: +// ANTIGRAVITY_DATA_DIR (comma-separated) if set, otherwise the default ~/.gemini/antigravity* +// and ~/.config/antigravity directories. If a root contains a conversations/ subfolder, that +// subfolder is returned. +func AntigravityDataRoots() []string { + home, _ := os.UserHomeDir() + var configured []string + if env := strings.TrimSpace(os.Getenv("ANTIGRAVITY_DATA_DIR")); env != "" { + configured = splitPathList(env) + } + var rawRoots []string + if len(configured) > 0 { + for _, r := range configured { + rawRoots = append(rawRoots, expandAntigravityHome(r, home)) + } + } else if home != "" { + for _, name := range []string{"antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"} { + rawRoots = append(rawRoots, filepath.Join(home, ".gemini", name)) + } + rawRoots = append(rawRoots, filepath.Join(home, ".config", "antigravity")) + } + + seen := map[string]bool{} + roots := make([]string, 0, len(rawRoots)) + for _, root := range rawRoots { + if root == "" { + continue + } + resolved := root + if r, err := filepath.EvalSymlinks(root); err == nil { + resolved = r + } + nested := filepath.Join(resolved, "conversations") + target := resolved + if info, err := os.Stat(nested); err == nil && info.IsDir() { + target = nested + } + if r, err := filepath.EvalSymlinks(target); err == nil { + target = r + } + if !seen[target] { + seen[target] = true + roots = append(roots, target) + } + } + return roots +} + +func expandAntigravityHome(p, home string) string { + p = strings.TrimSpace(p) + if p == "" { + return "" + } + if p == "~" && home != "" { + return home + } + if strings.HasPrefix(p, "~/") && home != "" { + return filepath.Join(home, p[2:]) + } + return p +} + +// AntigravityDBFingerprint returns a fingerprint covering both the .db file and its optional -wal file. +func AntigravityDBFingerprint(path string) (string, time.Time, error) { + st, err := os.Stat(path) + if err != nil { + return "", time.Time{}, err + } + latestMod := st.ModTime() + part := fmt.Sprintf("%d:%d", st.Size(), st.ModTime().UnixNano()) + walPart := "-" + if wst, err := os.Stat(path + "-wal"); err == nil { + walPart = fmt.Sprintf("%d:%d", wst.Size(), wst.ModTime().UnixNano()) + if wst.ModTime().After(latestMod) { + latestMod = wst.ModTime() + } + } + return part + "/" + walPart, latestMod, nil +} + +// CollectAntigravityDBFiles walks roots and returns sorted canonical *.db paths (ignoring symlinks). +// Files whose .db and -wal mtime are both more than 24h before since are pruned. +func CollectAntigravityDBFiles(roots []string, since time.Time) ([]string, error) { + seenRoots := map[string]bool{} + seenFiles := map[string]bool{} + var files []string + + var cutoff time.Time + if !since.IsZero() { + cutoff = since.Add(-24 * time.Hour) + } + + for _, root := range roots { + resolved, err := filepath.EvalSymlinks(root) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + continue + } + continue + } + if seenRoots[resolved] { + continue + } + seenRoots[resolved] = true + + _ = filepath.WalkDir(resolved, func(path string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + // Ignore symlinks (both files and directories), matching t3code. + if d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + return nil + } + if !strings.HasSuffix(d.Name(), ".db") { + return nil + } + canonical, err := filepath.EvalSymlinks(path) + if err != nil { + canonical = path + } + if seenFiles[canonical] { + return nil + } + if !cutoff.IsZero() { + _, modTime, err := AntigravityDBFingerprint(canonical) + if err == nil && modTime.Before(cutoff) { + return nil + } + } + seenFiles[canonical] = true + files = append(files, canonical) + return nil + }) + } + sort.Strings(files) + return files, nil +} + +// ParseAntigravityDBs scans Antigravity conversation SQLite databases under roots and +// rebuilds sessions with deduplicated token usage events. +func ParseAntigravityDBs(roots []string, opts BackfillOptions) (*BackfillParseResult, error) { + files, err := CollectAntigravityDBFiles(roots, opts.Since) + if err != nil { + return nil, err + } + return ParseAntigravityDBFiles(files, opts) +} + +// ParseAntigravityDBFiles parses a specific list of Antigravity SQLite *.db files into BackfillSessions. +func ParseAntigravityDBFiles(files []string, opts BackfillOptions) (*BackfillParseResult, error) { + type dbResult struct { + candidates []agyUsageCandidate + models map[int]agyLearnedModel + } + + learnedModels := map[int]agyLearnedModel{} + var pending []dbResult + badItems := 0 + var failedFiles []string + + for _, path := range files { + st, err := os.Stat(path) + if err != nil { + badItems++ + failedFiles = append(failedFiles, path) + continue + } + sessionID := strings.TrimSuffix(filepath.Base(path), ".db") + cands, models, rowBad, err := readAntigravityDatabase(path, sessionID, st.ModTime().UnixMilli()) + badItems += rowBad + if err != nil { + badItems++ + failedFiles = append(failedFiles, path) + continue + } + if cands == nil && models == nil { + // Not a conversation DB (e.g. conversation_summaries.db) + continue + } + for id, lm := range models { + rememberAgyModel(learnedModels, id, lm) + } + pending = append(pending, dbResult{candidates: cands, models: models}) + } + + // Union-find across all candidates from all databases (matches t3code's cross-DB dedup). + uf := newAgyUnionFind() + for _, item := range pending { + for _, cand := range item.candidates { + lm, hasLearned := learnedModels[cand.modelID] + learnedName := "" + if hasLearned && !lm.ambiguous { + learnedName = lm.name + } + fallback := "" + if !(hasLearned && lm.ambiguous) { + fallback = antigravityModelIDs[cand.modelID] + } + + modelName := "" + modelQuality := cand.modelQuality + switch { + case cand.modelQuality == 4 && cand.model != "": + modelName = cand.model + case learnedName != "": + modelName = learnedName + modelQuality = 3 + case fallback != "": + modelName = fallback + modelQuality = 2 + case cand.model != "": + modelName = cand.model + case cand.modelID > 0: + modelName = fmt.Sprintf("antigravity-model-%d", cand.modelID) + default: + modelName = "antigravity-unknown" + } + + cand.model = modelName + cand.modelQuality = modelQuality + uf.append(cand) + } + } + + machine := currentBackfillMachine() + bySession := map[string]*BackfillSession{} + for idx, g := range uf.groups { + if g.parent != idx { + continue + } + ts := time.UnixMilli(g.timestampMs).UTC() + ev := newBackfillEvent(AICodeClientAntigravity, AICodeEventApiRequest, g.dedupeKey, g.sessionID, ts) + machine.apply(&ev) + ev.Model = g.model + inTok := g.uncachedInputTokens + outTok := g.outputTokens + cacheRead := g.cachedInputTokens + cacheWrite := g.cacheCreationTokens + reasoning := g.reasoningTokens + ev.InputTokens = &inTok + ev.OutputTokens = &outTok + ev.CacheReadTokens = &cacheRead + ev.CacheCreationTokens = &cacheWrite + if reasoning > 0 { + ev.ReasoningTokens = &reasoning + } + + sess, ok := bySession[g.sessionID] + if !ok { + sess = &BackfillSession{ + ID: g.sessionID, + ClientType: AICodeClientAntigravity, + } + bySession[g.sessionID] = sess + } + sess.Events = append(sess.Events, ev) + } + + sessions := make([]*BackfillSession, 0, len(bySession)) + for _, s := range bySession { + finalizeBackfillSession(s) + sessions = append(sessions, s) + } + sort.Slice(sessions, func(i, j int) bool { + if !sessions[i].Start.Equal(sessions[j].Start) { + return sessions[i].Start.Before(sessions[j].Start) + } + return sessions[i].ID < sessions[j].ID + }) + + return &BackfillParseResult{ + Sessions: sessions, + Files: len(files), + BadLines: badItems, + FailedFiles: failedFiles, + }, nil +} + +// --- Protobuf wire decoder (matching t3code's antigravityUsageReader.ts) --- + +type pbFieldValue struct { + num uint64 + bytes []byte + isNum bool +} + +type pbFields map[int][]pbFieldValue + +func parseProtobufFields(data []byte) (pbFields, error) { + result := make(pbFields) + offset := 0 + readVarint := func() (uint64, error) { + var val uint64 + for shift := uint(0); shift < 70; shift += 7 { + if offset >= len(data) { + return 0, errors.New("truncated protobuf varint") + } + b := data[offset] + offset++ + if shift == 63 && b > 1 { + return 0, errors.New("overflow in protobuf varint") + } + val |= uint64(b&0x7f) << shift + if b < 0x80 { + return val, nil + } + } + return 0, errors.New("invalid protobuf varint") + } + + for offset < len(data) { + tag, err := readVarint() + if err != nil { + return nil, err + } + fieldNum := int(tag >> 3) + wireType := int(tag & 7) + if fieldNum == 0 { + return nil, errors.New("invalid protobuf field number 0") + } + switch wireType { + case 0: + v, err := readVarint() + if err != nil { + return nil, err + } + result[fieldNum] = append(result[fieldNum], pbFieldValue{num: v, isNum: true}) + case 1: + if offset+8 > len(data) { + return nil, errors.New("truncated protobuf fixed64") + } + offset += 8 + case 5: + if offset+4 > len(data) { + return nil, errors.New("truncated protobuf fixed32") + } + offset += 4 + case 2: + length, err := readVarint() + if err != nil { + return nil, err + } + if length > uint64(len(data)-offset) { + return nil, errors.New("truncated protobuf bytes field") + } + slice := data[offset : offset+int(length)] + offset += int(length) + result[fieldNum] = append(result[fieldNum], pbFieldValue{bytes: slice}) + default: + return nil, fmt.Errorf("unsupported protobuf wire type %d", wireType) + } + } + return result, nil +} + +func pbNumberAt(f pbFields, key int) int { + entries := f[key] + if len(entries) == 0 || !entries[0].isNum || entries[0].num > 1<<31-1 { + return 0 + } + return int(entries[0].num) +} + +func pbBytesAt(f pbFields, key int) []byte { + entries := f[key] + if len(entries) == 0 || entries[0].isNum { + return nil + } + return entries[0].bytes +} + +func pbNested(f pbFields, key int) pbFields { + b := pbBytesAt(f, key) + if len(b) == 0 { + return nil + } + sub, err := parseProtobufFields(b) + if err != nil { + return nil + } + return sub +} + +func pbTextAt(f pbFields, key int) string { + b := pbBytesAt(f, key) + if len(b) == 0 || !utf8.Valid(b) { + return "" + } + return strings.TrimSpace(string(b)) +} + +func pbTimestampMs(f pbFields) *int64 { + if f == nil { + return nil + } + sec := int64(pbNumberAt(f, 1)) + if sec <= 0 { + return nil + } + nanos := int64(pbNumberAt(f, 2)) + ms := sec*1000 + nanos/1_000_000 + return &ms +} + +// --- Model name normalization & learning --- + +type agyLearnedModel struct { + name string + ambiguous bool +} + +func normalizeAntigravityModelName(name string) string { + name = strings.TrimSpace(name) + if name == "" { + return "" + } + lower := strings.ToLower(name) + lower = agyParenSuffixRe.ReplaceAllString(lower, "-$1") + lower = agySpaceRe.ReplaceAllString(lower, "-") + if strings.HasPrefix(lower, "claude-") { + lower = agyClaudeVersionRe.ReplaceAllString(lower, "claude-$2-$1") + lower = strings.ReplaceAll(lower, ".", "-") + } + return lower +} + +func isConcreteAntigravityModel(model string) bool { + return agyConcreteModelRe.MatchString(model) && !agyFlashAgentAliasRe.MatchString(model) +} + +func antigravityRateModel(model string) string { + base := agyRateSuffixRe.ReplaceAllString(model, "") + switch { + case agyFlashAgentAliasRe.MatchString(model): + return "gemini-3.5-flash" + case model == "gemini-3.7-flash-safety-le": + return "gemini-3.7-flash" + case model == "gemini-pro-orchestrator-neon": + return "gemini-4-neon" + case model == "gemini-pro-orchestrator-g1-pro": + return "gemini-4-argon" + case model == "gemini-pro-orchestrator": + return "gemini-4-carbon" + case base == "gemini-3-flash": + return "gemini-3-flash-preview" + default: + return base + } +} + +func rememberAgyModel(models map[int]agyLearnedModel, id int, lm agyLearnedModel) { + prev, exists := models[id] + if !exists { + models[id] = lm + return + } + if prev.ambiguous || lm.ambiguous { + models[id] = agyLearnedModel{ambiguous: true} + return + } + if prev.name != lm.name && antigravityRateModel(prev.name) != antigravityRateModel(lm.name) { + models[id] = agyLearnedModel{ambiguous: true} + } +} + +// --- SQLite reading & candidate extraction --- + +type agyMetadata struct { + model string + modelID int + timestampMs *int64 + usages []pbFields +} + +type agyIndexedMetadata struct { + idx int + entry agyMetadata +} + +func parseAgyMetadata(raw []byte, isStep bool) (agyMetadata, error) { + root, err := parseProtobufFields(raw) + if err != nil { + return agyMetadata{}, err + } + var data pbFields + if isStep { + data = root + } else { + if pbBytesAt(root, 1) == nil { + return agyMetadata{}, errors.New("missing Antigravity generation metadata") + } + data = pbNested(root, 1) + } + + modelMsg := data + if isStep { + modelMsg = pbNested(data, 24) + } + + usageFieldNum := 4 + retryFieldNum := 17 + if isStep { + usageFieldNum = 9 + retryFieldNum = 28 + } + + var usages []pbFields + var primaryUsage pbFields + if uBytes := pbBytesAt(data, usageFieldNum); len(uBytes) > 0 { + copied := append([]byte(nil), uBytes...) + if parsed, err := parseProtobufFields(copied); err == nil { + primaryUsage = parsed + usages = append(usages, parsed) + } + } + + for _, retryVal := range data[retryFieldNum] { + if retryVal.isNum || len(retryVal.bytes) == 0 { + continue + } + retryMsg, err := parseProtobufFields(retryVal.bytes) + if err != nil { + continue + } + if ruBytes := pbBytesAt(retryMsg, 2); len(ruBytes) > 0 { + copied := append([]byte(nil), ruBytes...) + if parsed, err := parseProtobufFields(copied); err == nil { + usages = append(usages, parsed) + } + } + } + + var nameA, nameB string + var modelID int + if isStep { + nameA = normalizeAntigravityModelName(pbTextAt(modelMsg, 12)) + nameB = normalizeAntigravityModelName(pbTextAt(modelMsg, 8)) + modelID = pbNumberAt(modelMsg, 1) + } else { + nameA = normalizeAntigravityModelName(pbTextAt(modelMsg, 19)) + nameB = normalizeAntigravityModelName(pbTextAt(modelMsg, 21)) + modelID = pbNumberAt(modelMsg, 3) + } + if modelID == 0 && primaryUsage != nil { + modelID = pbNumberAt(primaryUsage, 1) + } + + chosenModel := "" + for _, n := range []string{nameA, nameB} { + if isConcreteAntigravityModel(n) { + chosenModel = n + break + } + } + if chosenModel == "" { + for _, n := range []string{nameA, nameB} { + if n != "" && !agyModelPrefixRe.MatchString(n) { + chosenModel = n + break + } + } + } + + var tsMs *int64 + if isStep { + tsMs = pbTimestampMs(pbNested(data, 8)) + if tsMs == nil { + tsMs = pbTimestampMs(pbNested(data, 1)) + } + } else { + tsMs = pbTimestampMs(pbNested(pbNested(data, 9), 4)) + } + + return agyMetadata{ + model: chosenModel, + modelID: modelID, + timestampMs: tsMs, + usages: usages, + }, nil +} + +func readAntigravityDatabase(path, sessionID string, fallbackTimestampMs int64) ([]agyUsageCandidate, map[int]agyLearnedModel, int, error) { + // Open strictly read-only with URI-encoded path so paths containing ?, #, or % work safely + // and SQLite never creates -wal/-shm files next to a live agent DB. + dsnURL := url.URL{ + Scheme: "file", + Path: path, + RawQuery: "mode=ro&_pragma=busy_timeout(100)&_pragma=query_only(ON)", + } + db, err := sql.Open("sqlite", dsnURL.String()) + if err != nil { + return nil, nil, 0, err + } + defer db.Close() + + tables := map[string]bool{} + rows, err := db.Query("SELECT name FROM sqlite_master WHERE type = 'table'") + if err != nil { + return nil, nil, 0, err + } + for rows.Next() { + var name string + if err := rows.Scan(&name); err == nil { + tables[name] = true + } + } + _ = rows.Close() + + if !tables["gen_metadata"] && !tables["steps"] { + return nil, nil, 0, nil + } + + badRows := 0 + readMeta := func(query string, pageRows int, isStep bool) ([]agyIndexedMetadata, error) { + var entries []agyIndexedMetadata + var after int64 = -1 + hasAfter := false + for { + var qRows *sql.Rows + var qErr error + if !hasAfter { + qRows, qErr = db.Query(query, -9223372036854775808, pageRows) + } else { + qRows, qErr = db.Query(query, after, pageRows) + } + if qErr != nil { + return nil, qErr + } + count := 0 + var lastRowID int64 + hasLastRowID := false + for qRows.Next() { + count++ + var rowID int64 + var idxRaw any + var blob []byte + if err := qRows.Scan(&rowID, &idxRaw, &blob); err != nil { + badRows++ + continue + } + lastRowID = rowID + hasLastRowID = true + idxVal, ok := idxRaw.(int64) + if !ok { + badRows++ + continue + } + if isStep && len(blob) == 0 { + continue + } + entry, err := parseAgyMetadata(blob, isStep) + if err != nil { + badRows++ + continue + } + entries = append(entries, agyIndexedMetadata{idx: int(idxVal), entry: entry}) + } + rowErr := qRows.Err() + _ = qRows.Close() + if rowErr != nil { + return nil, rowErr + } + if count < pageRows || !hasLastRowID || (hasAfter && lastRowID <= after) { + break + } + after = lastRowID + hasAfter = true + } + sort.Slice(entries, func(i, j int) bool { return entries[i].idx < entries[j].idx }) + return entries, nil + } + + var generations []agyIndexedMetadata + if tables["gen_metadata"] { + generations, err = readMeta( + "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?", + 64, + false, + ) + if err != nil { + return nil, nil, badRows, err + } + } + + var trajectoryTs *int64 + if tables["trajectory_metadata_blob"] { + tRows, err := db.Query("SELECT data FROM trajectory_metadata_blob") + if err == nil { + for tRows.Next() { + var blob []byte + if err := tRows.Scan(&blob); err == nil && len(blob) > 0 && trajectoryTs == nil { + if root, err := parseProtobufFields(blob); err == nil { + trajectoryTs = pbTimestampMs(pbNested(root, 2)) + } + } + } + _ = tRows.Close() + } + } + + var steps []agyIndexedMetadata + if tables["steps"] { + steps, err = readMeta( + "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?", + 64, + true, + ) + if err != nil { + return nil, nil, badRows, err + } + } + + models := map[int]agyLearnedModel{} + for _, g := range generations { + if g.entry.modelID > 0 && isConcreteAntigravityModel(g.entry.model) { + rememberAgyModel(models, g.entry.modelID, agyLearnedModel{name: g.entry.model}) + } + } + for _, s := range steps { + if s.entry.modelID > 0 && isConcreteAntigravityModel(s.entry.model) { + rememberAgyModel(models, s.entry.modelID, agyLearnedModel{name: s.entry.model}) + } + } + + cands := buildAgyUsageCandidates(sessionID, generations, steps, trajectoryTs, fallbackTimestampMs) + return cands, models, badRows, nil +} + +type agyUsageCandidate struct { + sessionID string + timestampMs int64 + model string + modelID int + modelQuality int + timestampQuality int + dedupeKey string + keys []string + uncachedInputTokens int + cachedInputTokens int + cacheCreationTokens int + outputTokens int + reasoningTokens int +} + +func buildAgyUsageCandidates( + sessionID string, + generations []agyIndexedMetadata, + steps []agyIndexedMetadata, + trajectoryTs *int64, + fallbackTs int64, +) []agyUsageCandidate { + genByIdx := make(map[int]agyMetadata, len(generations)) + for _, g := range generations { + genByIdx[g.idx] = g.entry + } + + var out []agyUsageCandidate + process := func(source string, entries []agyIndexedMetadata) { + for _, item := range entries { + entry := item.entry + for usageIdx, usage := range entry.usages { + modelID := pbNumberAt(usage, 1) + if modelID == 0 { + modelID = entry.modelID + } + var gen *agyMetadata + if source == "step" { + if g, ok := genByIdx[item.idx]; ok { + gen = &g + } + } + matches := func(m agyMetadata) bool { + return modelID == 0 || m.modelID == modelID + } + modelName := "" + if matches(entry) && entry.model != "" { + modelName = entry.model + } else if gen != nil && matches(*gen) { + modelName = gen.model + } + + uncachedIn := pbNumberAt(usage, 2) + cachedIn := pbNumberAt(usage, 5) + cacheCreate := pbNumberAt(usage, 4) + reasoningRaw := pbNumberAt(usage, 9) + visibleOut := pbNumberAt(usage, 10) + outTok := max(pbNumberAt(usage, 3), reasoningRaw+visibleOut) + reasoningTok := min(outTok, reasoningRaw) + + if uncachedIn+cachedIn+cacheCreate+outTok == 0 { + continue + } + + var keys []string + for _, fieldKey := range []int{11, 12, 7} { + if id := pbTextAt(usage, fieldKey); id != "" { + keys = append(keys, fmt.Sprintf("antigravity:%d:%s", fieldKey, id)) + } + } + if len(keys) == 0 { + // Key unkeyed records by session + item.idx + usageIdx (not source) so matching + // step/generation rows and backup-root copies merge via union-find. + keys = []string{fmt.Sprintf("antigravity:%s:idx:%d:%d", sessionID, item.idx, usageIdx)} + } + dedupeKey := keys[0] + + tsMs := fallbackTs + tsQuality := 0 + if entry.timestampMs != nil { + tsMs = *entry.timestampMs + tsQuality = 2 + } else if trajectoryTs != nil { + tsMs = *trajectoryTs + tsQuality = 1 + } + + mq := 0 + if isConcreteAntigravityModel(modelName) { + mq = 4 + } else if modelName != "" { + mq = 1 + } + + out = append(out, agyUsageCandidate{ + sessionID: sessionID, + timestampMs: tsMs, + model: modelName, + modelID: modelID, + modelQuality: mq, + timestampQuality: tsQuality, + dedupeKey: dedupeKey, + keys: keys, + uncachedInputTokens: uncachedIn, + cachedInputTokens: cachedIn, + cacheCreationTokens: cacheCreate, + outputTokens: outTok, + reasoningTokens: reasoningTok, + }) + } + } + } + + process("step", steps) + process("generation", generations) + return out +} + +type agyUFNode struct { + agyUsageCandidate + parent int + size int + owner int +} + +type agyUnionFind struct { + groups []agyUFNode + identities map[string]int +} + +func newAgyUnionFind() *agyUnionFind { + return &agyUnionFind{identities: make(map[string]int)} +} + +func (u *agyUnionFind) find(idx int) int { + root := idx + for u.groups[root].parent != root { + root = u.groups[root].parent + } + for idx != root { + next := u.groups[idx].parent + u.groups[idx].parent = root + idx = next + } + return root +} + +func (u *agyUnionFind) merge(left, right int) int { + a := u.find(left) + b := u.find(right) + if a == b { + return a + } + if u.groups[a].size < u.groups[b].size { + a, b = b, a + } + target := &u.groups[a] + source := &u.groups[b] + + first := target + if source.owner < target.owner { + first = source + } + bestModel := target + if source.modelQuality == target.modelQuality { + bestModel = first + } else if source.modelQuality > target.modelQuality { + bestModel = source + } + bestTime := target + if source.timestampQuality > target.timestampQuality || + (source.timestampQuality == target.timestampQuality && source.timestampMs < target.timestampMs) { + bestTime = source + } + + target.sessionID = first.sessionID + target.dedupeKey = first.dedupeKey + target.model = bestModel.model + target.modelQuality = bestModel.modelQuality + target.timestampMs = bestTime.timestampMs + target.timestampQuality = bestTime.timestampQuality + target.uncachedInputTokens = max(target.uncachedInputTokens, source.uncachedInputTokens) + target.cachedInputTokens = max(target.cachedInputTokens, source.cachedInputTokens) + target.cacheCreationTokens = max(target.cacheCreationTokens, source.cacheCreationTokens) + target.outputTokens = max(target.outputTokens, source.outputTokens) + target.reasoningTokens = max(target.reasoningTokens, source.reasoningTokens) + target.owner = first.owner + target.size += source.size + source.parent = a + return a +} + +func (u *agyUnionFind) append(c agyUsageCandidate) { + idx := len(u.groups) + u.groups = append(u.groups, agyUFNode{ + agyUsageCandidate: c, + parent: idx, + size: 1, + owner: idx, + }) + for _, k := range c.keys { + if existing, ok := u.identities[k]; ok { + u.merge(idx, existing) + } + u.identities[k] = idx + } +} diff --git a/model/aicode_backfill_antigravity_test.go b/model/aicode_backfill_antigravity_test.go new file mode 100644 index 0000000..6220226 --- /dev/null +++ b/model/aicode_backfill_antigravity_test.go @@ -0,0 +1,162 @@ +package model + +import ( + "database/sql" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func pbVarint(v uint64) []byte { + var out []byte + for { + b := byte(v & 0x7f) + v >>= 7 + if v != 0 { + b |= 0x80 + } + out = append(out, b) + if v == 0 { + return out + } + } +} + +func pbTag(field, wire int) []byte { + return pbVarint(uint64(field<<3 | wire)) +} + +func pbIntField(field int, v int64) []byte { + out := pbTag(field, 0) + return append(out, pbVarint(uint64(v))...) +} + +func pbBytesField(field int, payload []byte) []byte { + out := pbTag(field, 2) + out = append(out, pbVarint(uint64(len(payload)))...) + return append(out, payload...) +} + +func pbStringField(field int, s string) []byte { + return pbBytesField(field, []byte(s)) +} + +func pbTimestampMsg(ts time.Time) []byte { + var msg []byte + msg = append(msg, pbIntField(1, ts.Unix())...) + msg = append(msg, pbIntField(2, int64(ts.Nanosecond()))...) + return msg +} + +func TestParseAntigravityDBs_ProtobufAndDedup(t *testing.T) { + root := t.TempDir() + convDir := filepath.Join(root, "conversations") + require.NoError(t, os.MkdirAll(convDir, 0755)) + + // Non-conversation DB should be skipped cleanly. + summaryDB, err := sql.Open("sqlite", filepath.Join(convDir, "conversation_summaries.db")) + require.NoError(t, err) + _, err = summaryDB.Exec(`CREATE TABLE summaries (id TEXT PRIMARY KEY)`) + require.NoError(t, err) + require.NoError(t, summaryDB.Close()) + + // Conversation DB with both gen_metadata and steps referencing the same usage ID + a second distinct usage. + ts := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) + dbPath := filepath.Join(convDir, "agy-session-1.db") + db, err := sql.Open("sqlite", dbPath) + require.NoError(t, err) + _, err = db.Exec(` + CREATE TABLE gen_metadata (idx INTEGER, data BLOB); + CREATE TABLE steps (idx INTEGER, metadata BLOB); + CREATE TABLE trajectory_metadata_blob (data BLOB); + `) + require.NoError(t, err) + + // Shared usage record with ID in field 11 so step & generation merge via union-find. + var genUsage []byte + genUsage = append(genUsage, pbIntField(1, 1036)...) // gemini-3.1-pro + genUsage = append(genUsage, pbIntField(2, 1200)...) // uncached input + genUsage = append(genUsage, pbIntField(3, 300)...) // output + genUsage = append(genUsage, pbIntField(4, 150)...) // cache creation + genUsage = append(genUsage, pbIntField(5, 4000)...) // cached input + genUsage = append(genUsage, pbIntField(9, 100)...) // reasoning + genUsage = append(genUsage, pbIntField(10, 250)...) // visible output -> max(300, 350)=350 + genUsage = append(genUsage, pbStringField(11, "req-shared-1")...) + + var genData []byte + genData = append(genData, pbIntField(3, 1036)...) + genData = append(genData, pbBytesField(4, genUsage)...) + genData = append(genData, pbBytesField(9, pbBytesField(4, pbTimestampMsg(ts)))...) + genData = append(genData, pbStringField(19, "Gemini 3.1 Pro")...) + genRoot := pbBytesField(1, genData) + + _, err = db.Exec(`INSERT INTO gen_metadata (idx, data) VALUES (0, ?)`, genRoot) + require.NoError(t, err) + + // Step referencing the SAME usage ID ("req-shared-1") with lower tokens (should merge and keep max). + var stepUsageDup []byte + stepUsageDup = append(stepUsageDup, pbIntField(1, 1036)...) + stepUsageDup = append(stepUsageDup, pbIntField(2, 1000)...) + stepUsageDup = append(stepUsageDup, pbIntField(3, 200)...) + stepUsageDup = append(stepUsageDup, pbStringField(11, "req-shared-1")...) + + var stepMeta1 []byte + stepMeta1 = append(stepMeta1, pbBytesField(8, pbTimestampMsg(ts))...) + stepMeta1 = append(stepMeta1, pbBytesField(9, stepUsageDup)...) + stepMeta1 = append(stepMeta1, pbBytesField(24, pbIntField(1, 1036))...) + _, err = db.Exec(`INSERT INTO steps (idx, metadata) VALUES (0, ?)`, stepMeta1) + require.NoError(t, err) + + // Second step using model ID 1402 (fallback map -> claude-opus-5-5) and distinct usage ID. + var stepUsage2 []byte + stepUsage2 = append(stepUsage2, pbIntField(1, 1402)...) + stepUsage2 = append(stepUsage2, pbIntField(2, 500)...) + stepUsage2 = append(stepUsage2, pbIntField(3, 120)...) + stepUsage2 = append(stepUsage2, pbStringField(11, "req-unique-2")...) + + var stepMeta2 []byte + stepMeta2 = append(stepMeta2, pbBytesField(8, pbTimestampMsg(ts.Add(5*time.Minute)))...) + stepMeta2 = append(stepMeta2, pbBytesField(9, stepUsage2)...) + _, err = db.Exec(`INSERT INTO steps (idx, metadata) VALUES (1, ?)`, stepMeta2) + require.NoError(t, err) + + require.NoError(t, db.Close()) + + t.Setenv("ANTIGRAVITY_DATA_DIR", root) + roots := AntigravityDataRoots() + require.Len(t, roots, 1) + assert.Equal(t, convDir, roots[0]) + + res, err := ParseAntigravityDBs(roots, BackfillOptions{Now: ts.Add(2 * time.Hour)}) + require.NoError(t, err) + require.Len(t, res.Sessions, 1) + + sess := res.Sessions[0] + assert.Equal(t, "agy-session-1", sess.ID) + assert.Equal(t, AICodeClientAntigravity, sess.ClientType) + require.Len(t, sess.Events, 2) + + e0 := sess.Events[0] + assert.Equal(t, "gemini-3.1-pro", e0.Model) + assert.Equal(t, 1200, *e0.InputTokens) + assert.Equal(t, 350, *e0.OutputTokens) + assert.Equal(t, 4000, *e0.CacheReadTokens) + assert.Equal(t, 150, *e0.CacheCreationTokens) + require.NotNil(t, e0.ReasoningTokens) + assert.Equal(t, 100, *e0.ReasoningTokens) + + e1 := sess.Events[1] + assert.Equal(t, "claude-opus-5-5", e1.Model) + assert.Equal(t, 500, *e1.InputTokens) + assert.Equal(t, 120, *e1.OutputTokens) +} + +func TestNormalizeAntigravityModelName(t *testing.T) { + assert.Equal(t, "claude-sonnet-4-5", normalizeAntigravityModelName("Claude 4.5 Sonnet")) + assert.Equal(t, "gemini-3.5-flash-high", normalizeAntigravityModelName("Gemini 3.5 Flash (High)")) + assert.Equal(t, "gemini-3.1-pro", normalizeAntigravityModelName("Gemini 3.1 Pro")) +} diff --git a/model/aicode_backfill_common.go b/model/aicode_backfill_common.go index d58442e..4375b9a 100644 --- a/model/aicode_backfill_common.go +++ b/model/aicode_backfill_common.go @@ -79,9 +79,10 @@ func AttachBackfillRepositories(ctx context.Context, sessions []*BackfillSession // BackfillParseResult is what a transcript parser found on disk. type BackfillParseResult struct { - Sessions []*BackfillSession - Files int - BadLines int + Sessions []*BackfillSession + Files int + BadLines int + FailedFiles []string } // backfillHash derives both the event id and the in-memory dedup key from a diff --git a/model/aicode_backfill_cursor.go b/model/aicode_backfill_cursor.go new file mode 100644 index 0000000..5b96505 --- /dev/null +++ b/model/aicode_backfill_cursor.go @@ -0,0 +1,627 @@ +package model + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log/slog" + "math" + "net/http" + "sort" + "strconv" + "strings" + "time" +) + +const ( + cursorUsagePageSize = 1000 + cursorDefaultLookback = 90 * 24 * time.Hour + cursorMaxResponseBytes = 32 << 20 +) + +type cursorUsageEventRaw struct { + Timestamp any `json:"timestamp"` + Model string `json:"model"` + ConversationID string `json:"conversationId"` + TokenUsage *cursorTokenUsage `json:"tokenUsage"` +} + +type cursorTokenUsage struct { + InputTokens *float64 `json:"inputTokens"` + OutputTokens *float64 `json:"outputTokens"` + CacheReadTokens *float64 `json:"cacheReadTokens"` + CacheWriteTokens *float64 `json:"cacheWriteTokens"` + TotalCents *float64 `json:"totalCents"` +} + +type cursorNormalizedRecord struct { + timestampMs int64 + model string + sessionID string + inputTokens int + outputTokens int + cacheReadTokens int + cacheCreationTokens int + reportedCostUSD *float64 + identityHash string + dedupeKey string +} + +// FetchCursorUsageSessions fetches billed token usage from Cursor's DashboardService +// (personal scope plus every team the account belongs to) and groups them into BackfillSessions. +func FetchCursorUsageSessions(ctx context.Context, auth *CursorAuthData, opts BackfillOptions) (*BackfillParseResult, error) { + return fetchCursorUsageSessionsWithClient(ctx, auth, opts, nil) +} + +func fetchCursorUsageSessionsWithClient(ctx context.Context, auth *CursorAuthData, opts BackfillOptions, client *http.Client) (*BackfillParseResult, error) { + if auth == nil || strings.TrimSpace(auth.AccessToken) == "" { + return nil, ErrCursorAuthMissing + } + if client == nil { + client = cursorNoRedirectClient(15 * time.Second) + } + endpoint := strings.TrimRight(strings.TrimSpace(auth.Endpoint), "/") + if endpoint == "" { + endpoint = DefaultCursorAPIEndpoint + } + + now := opts.Now + if now.IsZero() { + now = time.Now() + } + since := opts.Since + if since.IsZero() { + since = now.Add(-cursorDefaultLookback) + } + until := opts.Until + if until.IsZero() || until.After(now) { + until = now + } + sinceMs := since.UnixMilli() + untilMs := until.UnixMilli() + if sinceMs < 0 { + sinceMs = 0 + } + if sinceMs > untilMs { + return &BackfillParseResult{}, nil + } + + teamIDs, userID, err := fetchCursorMembership(ctx, endpoint, auth.AccessToken, client) + if err != nil { + return nil, err + } + + accountKey, err := cursorAccountKey(auth.AccessToken, userID) + if err != nil { + return nil, err + } + + // Read personal scope (teamID == nil) plus each team scope. + scopes := make([]*int64, 0, 1+len(teamIDs)) + scopes = append(scopes, nil) + for i := range teamIDs { + id := teamIDs[i] + scopes = append(scopes, &id) + } + + var allRecords []cursorNormalizedRecord + for _, teamID := range scopes { + recs, err := fetchCursorScopeUsage(ctx, endpoint, auth.AccessToken, accountKey, sinceMs, untilMs, teamID, userID, client) + if err != nil { + return nil, err + } + allRecords = append(allRecords, recs...) + } + + machine := currentBackfillMachine() + bySession := make(map[string]*BackfillSession) + for _, rec := range allRecords { + ts := time.UnixMilli(rec.timestampMs).UTC() + sessionID := rec.sessionID + if sessionID == "" { + sessionID = "cursor-day-" + ts.Format("2006-01-02") + } + + ev := newBackfillEvent(AICodeClientCursor, AICodeEventApiRequest, rec.dedupeKey, sessionID, ts) + machine.apply(&ev) + ev.Model = rec.model + inTok := rec.inputTokens + outTok := rec.outputTokens + cacheRead := rec.cacheReadTokens + cacheWrite := rec.cacheCreationTokens + ev.InputTokens = &inTok + ev.OutputTokens = &outTok + ev.CacheReadTokens = &cacheRead + ev.CacheCreationTokens = &cacheWrite + if rec.reportedCostUSD != nil { + cost := *rec.reportedCostUSD + ev.CostUSD = &cost + } + + sess, ok := bySession[sessionID] + if !ok { + sess = &BackfillSession{ + ID: sessionID, + ClientType: AICodeClientCursor, + } + bySession[sessionID] = sess + } + sess.Events = append(sess.Events, ev) + } + + sessions := make([]*BackfillSession, 0, len(bySession)) + for _, s := range bySession { + finalizeBackfillSession(s) + sessions = append(sessions, s) + } + sort.Slice(sessions, func(i, j int) bool { + if !sessions[i].Start.Equal(sessions[j].Start) { + return sessions[i].Start.Before(sessions[j].Start) + } + return sessions[i].ID < sessions[j].ID + }) + + return &BackfillParseResult{ + Sessions: sessions, + Files: len(scopes), + }, nil +} + +func cursorAccountKey(token string, userID int64) (string, error) { + if sub := cursorJWTSubject(token); sub != "" { + sum := sha256.Sum256([]byte(sub)) + return hex.EncodeToString(sum[:]), nil + } + if userID > 0 { + sum := sha256.Sum256([]byte(fmt.Sprintf("user:%d", userID))) + return hex.EncodeToString(sum[:]), nil + } + return "", ErrCursorTokenInvalid +} + +func cursorJWTSubject(token string) string { + parts := strings.Split(token, ".") + if len(parts) < 2 { + return "" + } + decoded, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + decoded, err = base64.URLEncoding.DecodeString(parts[1]) + if err != nil { + return "" + } + } + var claims map[string]any + if err := json.Unmarshal(decoded, &claims); err != nil { + return "" + } + sub, ok := claims["sub"].(string) + if !ok { + return "" + } + return strings.TrimSpace(sub) +} + +func cursorDashboardPost(ctx context.Context, endpoint, method, accessToken string, body []byte, client *http.Client) (map[string]any, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"/aiserver.v1.DashboardService/"+method, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+accessToken) + req.Header.Set("connect-protocol-version", "1") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "shelltime-cli") + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + return nil, ErrCursorTokenInvalid + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("cursor %s returned status %d", method, resp.StatusCode) + } + + raw, err := io.ReadAll(io.LimitReader(resp.Body, cursorMaxResponseBytes)) + if err != nil { + return nil, err + } + + var parsed map[string]any + if err := json.Unmarshal(raw, &parsed); err != nil { + return nil, fmt.Errorf("cursor %s invalid JSON: %w", method, err) + } + if parsed == nil { + return nil, fmt.Errorf("cursor %s returned null body", method) + } + if _, hasErr := parsed["error"]; hasErr { + return nil, fmt.Errorf("cursor %s returned error response", method) + } + if _, hasMsg := parsed["message"]; hasMsg { + return nil, fmt.Errorf("cursor %s returned error response", method) + } + if _, hasCode := parsed["code"]; hasCode { + return nil, fmt.Errorf("cursor %s returned error response", method) + } + return parsed, nil +} + +func fetchCursorMembership(ctx context.Context, endpoint, accessToken string, client *http.Client) ([]int64, int64, error) { + teamsBody, err := cursorDashboardPost(ctx, endpoint, "GetTeams", accessToken, []byte("{}"), client) + if err != nil { + return nil, 0, err + } + meBody, err := cursorDashboardPost(ctx, endpoint, "GetMe", accessToken, []byte("{}"), client) + if err != nil { + return nil, 0, err + } + + userIDFloat, ok := meBody["userId"].(float64) + if !ok || userIDFloat <= 0 || math.Trunc(userIDFloat) != userIDFloat { + return nil, 0, fmt.Errorf("cursor GetMe returned invalid userId") + } + userID := int64(userIDFloat) + + seenTeams := map[int64]bool{} + var teamIDs []int64 + if rawTeams, ok := teamsBody["teams"].([]any); ok { + for _, entry := range rawTeams { + m, ok := entry.(map[string]any) + if !ok { + continue + } + idFloat, ok := m["id"].(float64) + if !ok || idFloat <= 0 || math.Trunc(idFloat) != idFloat { + return nil, 0, fmt.Errorf("cursor GetTeams returned invalid team id") + } + id := int64(idFloat) + if !seenTeams[id] { + seenTeams[id] = true + teamIDs = append(teamIDs, id) + } + } + } + sort.Slice(teamIDs, func(i, j int) bool { return teamIDs[i] < teamIDs[j] }) + return teamIDs, userID, nil +} + +func fetchCursorScopeUsage( + ctx context.Context, + endpoint, accessToken, accountKey string, + sinceMs, untilMs int64, + teamID *int64, + userID int64, + client *http.Client, +) ([]cursorNormalizedRecord, error) { + type pageSlice struct { + start int + end int + overlap int + } + + var ( + total *int + normalized []*cursorNormalizedRecord + pages []pageSlice + previousEvents []any + ) + + const cursorUsageMaxPages = 200 + for page := 1; page <= cursorUsageMaxPages; page++ { + payload := map[string]any{ + "page": page, + "pageSize": cursorUsagePageSize, + "startDate": strconv.FormatInt(sinceMs, 10), + "endDate": strconv.FormatInt(untilMs, 10), + } + if teamID != nil { + payload["teamId"] = *teamID + payload["userId"] = userID + } + reqBytes, err := json.Marshal(payload) + if err != nil { + return nil, err + } + + body, err := cursorDashboardPost(ctx, endpoint, "GetFilteredUsageEvents", accessToken, reqBytes, client) + if err != nil { + return nil, err + } + + var events []any + if len(body) == 0 { + z := 0 + total = &z + } else { + if rawCount, exists := body["totalUsageEventsCount"]; exists { + cFloat, ok := rawCount.(float64) + if !ok || cFloat < 0 || math.Trunc(cFloat) != cFloat { + return nil, fmt.Errorf("cursor GetFilteredUsageEvents returned invalid totalUsageEventsCount") + } + c := int(cFloat) + if total == nil || c > *total { + total = &c + } + } + if rawEvents, exists := body["usageEventsDisplay"]; exists { + arr, ok := rawEvents.([]any) + if !ok || len(arr) > cursorUsagePageSize { + return nil, fmt.Errorf("cursor GetFilteredUsageEvents returned invalid usageEventsDisplay") + } + events = arr + } else if !(len(body) == 1 && total != nil) { + return nil, fmt.Errorf("cursor GetFilteredUsageEvents missing usageEventsDisplay") + } + } + + start := len(normalized) + overlap := 0 + if len(events) > 0 && len(previousEvents) > 0 { + if cursorPagesMayOverlap(previousEvents, events) { + overlap = cursorBoundaryOverlap(cursorCanonicalList(previousEvents), cursorCanonicalList(events)) + } + } + if len(events) > 0 && overlap == len(events) { + break + } + previousEvents = events + + for _, raw := range events { + rec, err := normalizeCursorUsageEvent(raw, sinceMs, untilMs, teamID) + if err != nil { + slog.Debug("Skipping malformed Cursor usage event", slog.Any("err", err)) + normalized = append(normalized, nil) + continue + } + normalized = append(normalized, rec) + } + pages = append(pages, pageSlice{start: start, end: len(normalized), overlap: overlap}) + + if len(events) < cursorUsagePageSize { + break + } + } + + rawCount := len(normalized) + occurrences := map[string]int{} + records := make([]cursorNormalizedRecord, 0, rawCount) + for _, p := range pages { + for idx := p.start + p.overlap; idx < p.end; idx++ { + rec := normalized[idx] + if rec == nil { + continue + } + occ := occurrences[rec.identityHash] + occurrences[rec.identityHash] = occ + 1 + rec.dedupeKey = fmt.Sprintf("cursor-account:%s:%s:%d", accountKey, rec.identityHash, occ) + records = append(records, *rec) + } + } + + return records, nil +} + +func normalizeCursorUsageEvent(raw any, sinceMs, untilMs int64, teamID *int64) (*cursorNormalizedRecord, error) { + m, ok := raw.(map[string]any) + if !ok { + return nil, fmt.Errorf("invalid cursor usage event object") + } + tuRaw, hasUsage := m["tokenUsage"] + if !hasUsage || tuRaw == nil { + return nil, nil + } + tu, ok := tuRaw.(map[string]any) + if !ok { + return nil, fmt.Errorf("invalid cursor tokenUsage object") + } + + parseNonNeg := func(key string) (float64, bool, error) { + v, ok := tu[key] + if !ok || v == nil { + return 0, false, nil + } + f, ok := v.(float64) + if !ok || math.IsNaN(f) || math.IsInf(f, 0) || f < 0 { + return 0, false, fmt.Errorf("invalid cursor tokenUsage.%s", key) + } + return f, true, nil + } + + inF, _, err := parseNonNeg("inputTokens") + if err != nil { + return nil, err + } + outF, _, err := parseNonNeg("outputTokens") + if err != nil { + return nil, err + } + cacheReadF, _, err := parseNonNeg("cacheReadTokens") + if err != nil { + return nil, err + } + cacheWriteF, _, err := parseNonNeg("cacheWriteTokens") + if err != nil { + return nil, err + } + totalCents, hasCents, err := parseNonNeg("totalCents") + if err != nil { + return nil, err + } + + tsMs, err := parseCursorTimestampMs(m["timestamp"]) + if err != nil { + return nil, err + } + modelName, _ := m["model"].(string) + if strings.TrimSpace(modelName) == "" { + return nil, fmt.Errorf("invalid cursor usage event: missing model") + } + if tsMs < sinceMs || tsMs > untilMs { + return nil, nil + } + + sessionID, _ := m["conversationId"].(string) + inTok := int(math.Trunc(inF)) + outTok := int(math.Trunc(outF)) + cacheRead := int(math.Trunc(cacheReadF)) + cacheWrite := int(math.Trunc(cacheWriteF)) + + var costUSD *float64 + if hasCents { + c := totalCents / 100.0 + costUSD = &c + } + + identityFields := make([]any, 0, 7) + if teamID != nil { + identityFields = append(identityFields, *teamID) + } + identityFields = append(identityFields, + tsMs, + modelName, + sessionID, + map[string]int{ + "uncachedInputTokens": inTok, + "cachedInputTokens": cacheRead, + "cacheCreationTokens": cacheWrite, + "outputTokens": outTok, + "reasoningTokens": 0, + }, + costUSD, + ) + identityJSON, _ := json.Marshal(identityFields) + sum := sha256.Sum256(identityJSON) + + return &cursorNormalizedRecord{ + timestampMs: tsMs, + model: modelName, + sessionID: sessionID, + inputTokens: inTok, + outputTokens: outTok, + cacheReadTokens: cacheRead, + cacheCreationTokens: cacheWrite, + reportedCostUSD: costUSD, + identityHash: hex.EncodeToString(sum[:]), + }, nil +} + +func parseCursorTimestampMs(v any) (int64, error) { + switch t := v.(type) { + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) { + return 0, fmt.Errorf("invalid cursor event timestamp") + } + return int64(t), nil + case string: + trimmed := strings.TrimSpace(t) + if trimmed == "" { + return 0, fmt.Errorf("empty cursor event timestamp") + } + f, err := strconv.ParseFloat(trimmed, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, fmt.Errorf("invalid cursor event timestamp %q", t) + } + return int64(f), nil + default: + return 0, fmt.Errorf("missing cursor event timestamp") + } +} + +func cursorPagesMayOverlap(prev, curr []any) bool { + firstMap, ok := curr[0].(map[string]any) + if !ok { + return true + } + firstTs, err := parseCursorTimestampMs(firstMap["timestamp"]) + if err != nil { + return true + } + for _, ev := range prev { + if m, ok := ev.(map[string]any); ok { + if ts, err := parseCursorTimestampMs(m["timestamp"]); err == nil && ts == firstTs { + return true + } + } + } + return false +} + +func cursorCanonicalList(events []any) []string { + out := make([]string, len(events)) + for i, ev := range events { + out[i] = cursorCanonicalJSON(ev) + } + return out +} + +func cursorCanonicalJSON(v any) string { + switch x := v.(type) { + case []any: + var b strings.Builder + b.WriteByte('[') + for i, item := range x { + if i > 0 { + b.WriteByte(',') + } + b.WriteString(cursorCanonicalJSON(item)) + } + b.WriteByte(']') + return b.String() + case map[string]any: + keys := make([]string, 0, len(x)) + for k := range x { + keys = append(keys, k) + } + sort.Strings(keys) + var b strings.Builder + b.WriteByte('{') + for i, k := range keys { + if i > 0 { + b.WriteByte(',') + } + kb, _ := json.Marshal(k) + b.Write(kb) + b.WriteByte(':') + b.WriteString(cursorCanonicalJSON(x[k])) + } + b.WriteByte('}') + return b.String() + default: + b, err := json.Marshal(v) + if err != nil { + return "null" + } + return string(b) + } +} + +// cursorBoundaryOverlap computes the longest suffix of previous that matches a prefix of current via KMP. +func cursorBoundaryOverlap(previous, current []string) int { + if len(previous) == 0 || len(current) == 0 { + return 0 + } + seq := make([]string, 0, len(current)+1+len(previous)) + seq = append(seq, current...) + seq = append(seq, "\x00") + seq = append(seq, previous...) + pi := make([]int, len(seq)) + for i := 1; i < len(seq); i++ { + j := pi[i-1] + for j > 0 && seq[i] != seq[j] { + j = pi[j-1] + } + if seq[i] == seq[j] { + j++ + } + pi[i] = j + } + return pi[len(pi)-1] +} diff --git a/model/aicode_backfill_cursor_test.go b/model/aicode_backfill_cursor_test.go new file mode 100644 index 0000000..374be3a --- /dev/null +++ b/model/aicode_backfill_cursor_test.go @@ -0,0 +1,194 @@ +package model + +import ( + "context" + "database/sql" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func makeFakeJWT(sub string) string { + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + payload, _ := json.Marshal(map[string]any{"sub": sub, "exp": time.Now().Add(time.Hour).Unix()}) + return header + "." + base64.RawURLEncoding.EncodeToString(payload) + ".sig" +} + +func TestLoadCursorAuth_PrecedenceAndExchange(t *testing.T) { + exchangedToken := makeFakeJWT("user-123") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/auth/exchange_user_api_key", r.URL.Path) + assert.Equal(t, "Bearer key_secret", r.Header.Get("Authorization")) + _ = json.NewEncoder(w).Encode(map[string]string{"accessToken": exchangedToken}) + })) + defer srv.Close() + + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("CURSOR_AUTH_TOKEN", "") + t.Setenv("CURSOR_API_KEY", "") + t.Setenv("CURSOR_API_ENDPOINT", srv.URL) + + // 1. Missing everywhere + _, err := loadCursorAuthWithClient(context.Background(), nil, srv.Client()) + require.ErrorIs(t, err, ErrCursorAuthMissing) + + // 2. Config API key exchanged + auth, err := loadCursorAuthWithClient(context.Background(), &CursorConfig{APIKey: "key_secret"}, srv.Client()) + require.NoError(t, err) + assert.Equal(t, exchangedToken, auth.AccessToken) + assert.Equal(t, "config:cursor.apiKey", auth.Source) + + // 3. Env API key overrides config + t.Setenv("CURSOR_API_KEY", "key_secret") + auth, err = loadCursorAuthWithClient(context.Background(), &CursorConfig{APIKey: "other"}, srv.Client()) + require.NoError(t, err) + assert.Equal(t, "env:CURSOR_API_KEY", auth.Source) + + // 4. Env auth token overrides everything without exchange + t.Setenv("CURSOR_AUTH_TOKEN", "direct-token") + auth, err = loadCursorAuthWithClient(context.Background(), nil, srv.Client()) + require.NoError(t, err) + assert.Equal(t, "direct-token", auth.AccessToken) + assert.Equal(t, "env:CURSOR_AUTH_TOKEN", auth.Source) +} + +func TestReadAccessTokenFromVscdb(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "state.vscdb") + db, err := sql.Open("sqlite", dbPath) + require.NoError(t, err) + _, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)`) + require.NoError(t, err) + _, err = db.Exec(`INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', 'vscdb-jwt-token')`) + require.NoError(t, err) + require.NoError(t, db.Close()) + + assert.Equal(t, "vscdb-jwt-token", readAccessTokenFromVscdb(dbPath)) + assert.Equal(t, "", readAccessTokenFromVscdb(filepath.Join(dir, "missing.vscdb"))) +} + +func TestFetchCursorUsageSessions_PersonalAndTeamWithOverlap(t *testing.T) { + now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) + ts1 := now.Add(-2 * time.Hour).UnixMilli() + ts2 := now.Add(-1 * time.Hour).UnixMilli() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "1", r.Header.Get("connect-protocol-version")) + switch r.URL.Path { + case "/aiserver.v1.DashboardService/GetTeams": + _ = json.NewEncoder(w).Encode(map[string]any{ + "teams": []map[string]any{{"id": 42}}, + }) + case "/aiserver.v1.DashboardService/GetMe": + _ = json.NewEncoder(w).Encode(map[string]any{"userId": 7}) + case "/aiserver.v1.DashboardService/GetFilteredUsageEvents": + var req map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&req)) + if req["teamId"] == nil { + _ = json.NewEncoder(w).Encode(map[string]any{ + "totalUsageEventsCount": 2, + "usageEventsDisplay": []map[string]any{ + { + "timestamp": ts1, + "model": "claude-sonnet-4-5", + "conversationId": "conv-personal-1", + "tokenUsage": map[string]any{ + "inputTokens": 1000, + "outputTokens": 250, + "cacheReadTokens": 500, + "cacheWriteTokens": 100, + "totalCents": 12.5, + }, + }, + { + // Event without tokenUsage is skipped + "timestamp": ts1, + "model": "cursor-small", + }, + }, + }) + } else { + assert.Equal(t, float64(42), req["teamId"]) + assert.Equal(t, float64(7), req["userId"]) + _ = json.NewEncoder(w).Encode(map[string]any{ + "totalUsageEventsCount": 1, + "usageEventsDisplay": []map[string]any{ + { + "timestamp": ts2, + "model": "gpt-5", + "conversationId": "", + "tokenUsage": map[string]any{ + "inputTokens": 400, + "outputTokens": 100, + "totalCents": 3.0, + }, + }, + }, + }) + } + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + auth := &CursorAuthData{ + AccessToken: makeFakeJWT("auth0|cursor-user-1"), + Endpoint: srv.URL, + } + res, err := fetchCursorUsageSessionsWithClient(context.Background(), auth, BackfillOptions{ + Since: now.Add(-24 * time.Hour), + Until: now, + Now: now, + }, srv.Client()) + require.NoError(t, err) + require.Len(t, res.Sessions, 2) + + // Personal session + s0 := res.Sessions[0] + assert.Equal(t, "conv-personal-1", s0.ID) + assert.Equal(t, AICodeClientCursor, s0.ClientType) + require.Len(t, s0.Events, 1) + assert.Equal(t, "claude-sonnet-4-5", s0.Events[0].Model) + assert.Equal(t, 1000, *s0.Events[0].InputTokens) + assert.Equal(t, 250, *s0.Events[0].OutputTokens) + assert.Equal(t, 500, *s0.Events[0].CacheReadTokens) + assert.Equal(t, 100, *s0.Events[0].CacheCreationTokens) + require.NotNil(t, s0.Events[0].CostUSD) + assert.InDelta(t, 0.125, *s0.Events[0].CostUSD, 1e-9) + + // Team session with empty conversationId falls back to daily bucket + s1 := res.Sessions[1] + assert.Equal(t, "cursor-day-2026-11-20", s1.ID) + require.Len(t, s1.Events, 1) + assert.Equal(t, "gpt-5", s1.Events[0].Model) + assert.InDelta(t, 0.03, *s1.Events[0].CostUSD, 1e-9) +} + +func TestCursorBoundaryOverlap(t *testing.T) { + prev := []string{"a", "b", "c", "d"} + curr := []string{"c", "d", "e", "f"} + assert.Equal(t, 2, cursorBoundaryOverlap(prev, curr)) + assert.Equal(t, 0, cursorBoundaryOverlap(prev, []string{"x", "y"})) +} + +func TestReadLocalCursorAuthFile(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + require.NoError(t, os.MkdirAll(filepath.Join(home, ".cursor"), 0700)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".cursor", "auth.json"), []byte(`{"accessToken":"file-tok"}`), 0600)) + + tok, key, src := readLocalCursorAuthFile() + assert.Equal(t, "file-tok", tok) + assert.Equal(t, "", key) + assert.Contains(t, src, "auth.json") +} diff --git a/model/aicode_backfill_types.go b/model/aicode_backfill_types.go index fee32f3..0863161 100644 --- a/model/aicode_backfill_types.go +++ b/model/aicode_backfill_types.go @@ -6,8 +6,10 @@ import "time" // "claude-code", which the server maps to claude_code; backfill sends the // canonical values directly. const ( - AICodeClientClaudeCode = "claude_code" - AICodeClientCodex = "codex" + AICodeClientClaudeCode = "claude_code" + AICodeClientCodex = "codex" + AICodeClientCursor = "cursor" + AICodeClientAntigravity = "antigravity" ) // Backfill session statuses reported by the server. diff --git a/model/config.go b/model/config.go index c153e71..9077511 100644 --- a/model/config.go +++ b/model/config.go @@ -231,6 +231,32 @@ func mergeConfig(base, local *ShellTimeConfig) { } base.AgentHooks = &merged } + if local.Cursor != nil { + if base.Cursor == nil { + base.Cursor = &CursorConfig{} + } + merged := *base.Cursor + if local.Cursor.Enabled != nil { + merged.Enabled = local.Cursor.Enabled + } + if local.Cursor.APIKey != "" { + merged.APIKey = local.Cursor.APIKey + } + if local.Cursor.APIEndpoint != "" { + merged.APIEndpoint = local.Cursor.APIEndpoint + } + base.Cursor = &merged + } + if local.Antigravity != nil { + if base.Antigravity == nil { + base.Antigravity = &AntigravityConfig{} + } + merged := *base.Antigravity + if local.Antigravity.Enabled != nil { + merged.Enabled = local.Antigravity.Enabled + } + base.Antigravity = &merged + } if local.AICloudOnly != nil { base.AICloudOnly = local.AICloudOnly } diff --git a/model/config_log.go b/model/config_log.go index 67d2b6e..b7cf5e2 100644 --- a/model/config_log.go +++ b/model/config_log.go @@ -54,6 +54,12 @@ func (c ShellTimeConfig) LogValue() slog.Value { boolPtrAttr("sendContent", c.AgentHooks.SendContent), )) } + if c.Cursor != nil { + attrs = append(attrs, slog.Group("cursor", + slog.String("apiEndpoint", c.Cursor.APIEndpoint), + slog.String("apiKey", maskToken(c.Cursor.APIKey)), + )) + } if c.LogCleanup != nil { attrs = append(attrs, slog.Group("logCleanup", boolPtrAttr("enabled", c.LogCleanup.Enabled), diff --git a/model/cursor_auth.go b/model/cursor_auth.go new file mode 100644 index 0000000..c8fa6b3 --- /dev/null +++ b/model/cursor_auth.go @@ -0,0 +1,267 @@ +package model + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + _ "modernc.org/sqlite" +) + +const DefaultCursorAPIEndpoint = "https://api2.cursor.sh" + +var ( + ErrCursorAuthMissing = errors.New("cursor authentication not found") + ErrCursorTokenInvalid = errors.New("cursor auth token invalid") +) + +// CursorAuthData holds the resolved Cursor bearer access token and API endpoint. +type CursorAuthData struct { + AccessToken string + Endpoint string + Source string +} + +// cursorNoRedirectClient builds an HTTP client that never forwards bearer tokens across redirects. +func cursorNoRedirectClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + Transport: HTTPTransport(), + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} + +// ResolveCursorAPIEndpoint returns the Cursor API base URL from config, CURSOR_API_ENDPOINT, or default. +func ResolveCursorAPIEndpoint(cfg *CursorConfig) string { + if cfg != nil { + if ep := strings.TrimSpace(cfg.APIEndpoint); ep != "" { + return strings.TrimRight(ep, "/") + } + } + if ep := strings.TrimSpace(os.Getenv("CURSOR_API_ENDPOINT")); ep != "" { + return strings.TrimRight(ep, "/") + } + return DefaultCursorAPIEndpoint +} + +// ExchangeCursorAPIKey trades a Cursor user API key for the access token Cursor's RPCs accept. +func ExchangeCursorAPIKey(ctx context.Context, endpoint, apiKey string, client *http.Client) (string, error) { + if client == nil { + client = cursorNoRedirectClient(10 * time.Second) + } + ep := strings.TrimRight(strings.TrimSpace(endpoint), "/") + if ep == "" { + ep = DefaultCursorAPIEndpoint + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, ep+"/auth/exchange_user_api_key", bytes.NewReader([]byte("{}"))) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+apiKey) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "shelltime-cli") + + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + return "", ErrCursorTokenInvalid + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("cursor API key exchange returned status %d", resp.StatusCode) + } + + var parsed struct { + AccessToken string `json:"accessToken"` + } + if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { + return "", fmt.Errorf("failed to decode cursor API key exchange response: %w", err) + } + if strings.TrimSpace(parsed.AccessToken) == "" { + return "", ErrCursorTokenInvalid + } + return strings.TrimSpace(parsed.AccessToken), nil +} + +// LoadCursorAuth resolves a Cursor bearer access token from: +// 1. CURSOR_AUTH_TOKEN environment variable +// 2. CURSOR_API_KEY environment variable (exchanged via /auth/exchange_user_api_key) +// 3. cfg.APIKey from ShellTime config (exchanged via /auth/exchange_user_api_key) +// 4. Local Cursor CLI auth files (~/.cursor/auth.json, ~/.config/cursor/auth.json) +// 5. Local Cursor IDE state.vscdb (cursorAuth/accessToken) +func LoadCursorAuth(ctx context.Context, cfg *CursorConfig) (*CursorAuthData, error) { + return loadCursorAuthWithClient(ctx, cfg, nil) +} + +func loadCursorAuthWithClient(ctx context.Context, cfg *CursorConfig, client *http.Client) (*CursorAuthData, error) { + endpoint := ResolveCursorAPIEndpoint(cfg) + + if token := strings.TrimSpace(os.Getenv("CURSOR_AUTH_TOKEN")); token != "" { + return &CursorAuthData{ + AccessToken: token, + Endpoint: endpoint, + Source: "env:CURSOR_AUTH_TOKEN", + }, nil + } + + if apiKey := strings.TrimSpace(os.Getenv("CURSOR_API_KEY")); apiKey != "" { + token, err := ExchangeCursorAPIKey(ctx, endpoint, apiKey, client) + if err != nil { + return nil, err + } + return &CursorAuthData{ + AccessToken: token, + Endpoint: endpoint, + Source: "env:CURSOR_API_KEY", + }, nil + } + + if cfg != nil && strings.TrimSpace(cfg.APIKey) != "" { + token, err := ExchangeCursorAPIKey(ctx, endpoint, strings.TrimSpace(cfg.APIKey), client) + if err != nil { + return nil, err + } + return &CursorAuthData{ + AccessToken: token, + Endpoint: endpoint, + Source: "config:cursor.apiKey", + }, nil + } + + if token, apiKey, src := readLocalCursorAuthFile(); token != "" || apiKey != "" { + if token != "" { + return &CursorAuthData{ + AccessToken: token, + Endpoint: endpoint, + Source: src, + }, nil + } + exchanged, err := ExchangeCursorAPIKey(ctx, endpoint, apiKey, client) + if err != nil { + return nil, err + } + return &CursorAuthData{ + AccessToken: exchanged, + Endpoint: endpoint, + Source: src, + }, nil + } + + if token := readCursorStateVscdbToken(); token != "" { + return &CursorAuthData{ + AccessToken: token, + Endpoint: endpoint, + Source: "cursor:state.vscdb", + }, nil + } + + return nil, ErrCursorAuthMissing +} + +func readLocalCursorAuthFile() (accessToken, apiKey, source string) { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return "", "", "" + } + candidates := []string{ + filepath.Join(home, ".cursor", "auth.json"), + filepath.Join(home, ".config", "cursor", "auth.json"), + } + for _, p := range candidates { + data, err := os.ReadFile(p) + if err != nil { + continue + } + var doc struct { + AccessToken string `json:"accessToken"` + AccessSnake string `json:"access_token"` + APIKey string `json:"apiKey"` + APIKeySnake string `json:"api_key"` + } + if err := json.Unmarshal(data, &doc); err != nil { + continue + } + tok := strings.TrimSpace(doc.AccessToken) + if tok == "" { + tok = strings.TrimSpace(doc.AccessSnake) + } + key := strings.TrimSpace(doc.APIKey) + if key == "" { + key = strings.TrimSpace(doc.APIKeySnake) + } + if tok != "" || key != "" { + return tok, key, "file:" + p + } + } + return "", "", "" +} + +func cursorStateVscdbPaths() []string { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return nil + } + switch runtime.GOOS { + case "darwin": + return []string{ + filepath.Join(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb"), + } + case "linux": + xdg := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")) + if xdg == "" { + xdg = filepath.Join(home, ".config") + } + return []string{ + filepath.Join(xdg, "Cursor", "User", "globalStorage", "state.vscdb"), + } + default: + return nil + } +} + +func readCursorStateVscdbToken() string { + for _, p := range cursorStateVscdbPaths() { + if tok := readAccessTokenFromVscdb(p); tok != "" { + return tok + } + } + return "" +} + +func readAccessTokenFromVscdb(dbPath string) string { + if _, err := os.Stat(dbPath); err != nil { + return "" + } + dsn := (&url.URL{ + Scheme: "file", + Path: dbPath, + RawQuery: "mode=ro&_pragma=busy_timeout(100)&_pragma=query_only(ON)", + }).String() + db, err := sql.Open("sqlite", dsn) + if err != nil { + return "" + } + defer db.Close() + + var raw string + err = db.QueryRow("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'").Scan(&raw) + if err != nil { + return "" + } + return strings.TrimSpace(raw) +} diff --git a/model/types.go b/model/types.go index 677fd22..087d445 100644 --- a/model/types.go +++ b/model/types.go @@ -59,6 +59,40 @@ func (c ShellTimeConfig) AgentHooksSendContent() bool { return c.AgentHooks == nil || c.AgentHooks.SendContent == nil || *c.AgentHooks.SendContent } +// CursorConfig configures optional Cursor API credentials and usage sync. +// When credentials are unset, ShellTime checks CURSOR_AUTH_TOKEN, CURSOR_API_KEY, and local Cursor auth files. +type CursorConfig struct { + Enabled *bool `toml:"enabled,omitempty" yaml:"enabled,omitempty" json:"enabled,omitempty"` + APIKey string `toml:"apiKey,omitempty" yaml:"apiKey,omitempty" json:"apiKey,omitempty"` + APIEndpoint string `toml:"apiEndpoint,omitempty" yaml:"apiEndpoint,omitempty" json:"apiEndpoint,omitempty"` +} + +// AntigravityConfig configures optional Google Antigravity usage sync. +type AntigravityConfig struct { + Enabled *bool `toml:"enabled,omitempty" yaml:"enabled,omitempty" json:"enabled,omitempty"` +} + +// CursorUsageSyncEnabled reports whether the daemon should poll Cursor quota and token usage: +// explicitly controlled by cursor.enabled, otherwise enabled when aiCodeOtel.enabled is true or cursor.apiKey is set. +func (c ShellTimeConfig) CursorUsageSyncEnabled() bool { + if c.Cursor != nil && c.Cursor.Enabled != nil { + return *c.Cursor.Enabled + } + if c.Cursor != nil && c.Cursor.APIKey != "" { + return true + } + return c.AICodeOtel != nil && c.AICodeOtel.Enabled != nil && *c.AICodeOtel.Enabled +} + +// AntigravityUsageSyncEnabled reports whether the daemon should poll local Antigravity state DBs: +// explicitly controlled by antigravity.enabled, otherwise enabled when aiCodeOtel.enabled is true. +func (c ShellTimeConfig) AntigravityUsageSyncEnabled() bool { + if c.Antigravity != nil && c.Antigravity.Enabled != nil { + return *c.Antigravity.Enabled + } + return c.AICodeOtel != nil && c.AICodeOtel.Enabled != nil && *c.AICodeOtel.Enabled +} + // CodeTracking configuration for coding activity heartbeat tracking type CodeTracking struct { Enabled *bool `toml:"enabled" yaml:"enabled" json:"enabled"` @@ -113,6 +147,12 @@ type ShellTimeConfig struct { // AgentHooks configures what the Cursor and Antigravity hooks send AgentHooks *AgentHooksConfig `toml:"agentHooks,omitempty" yaml:"agentHooks,omitempty" json:"agentHooks,omitempty"` + // Cursor configures optional Cursor API credentials and usage sync + Cursor *CursorConfig `toml:"cursor,omitempty" yaml:"cursor,omitempty" json:"cursor,omitempty"` + + // Antigravity configures optional Google Antigravity usage sync + Antigravity *AntigravityConfig `toml:"antigravity,omitempty" yaml:"antigravity,omitempty" json:"antigravity,omitempty"` + // AICloudOnly collects only AI coding agent telemetry (aiCodeOtel) and nothing about the // machine: no shell commands, editor heartbeats, aliases or dotfiles, so it never becomes a // host. Unset, it is on in a cloud agent's VM, which isn't one of the user's machines: a