From 4a5f2ab562a53cb254a9fa7233ca7b7f59708628 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 10:13:28 +0000 Subject: [PATCH] feat(daemon): read Antigravity quota with `agy usage --json` The Antigravity usage sync now runs `agy usage --json` (the Antigravity CLI, found on PATH or in ~/.local/bin where its installer puts it) and posts each model group's 5-hour and weekly window to /api/v1/antigravity-usage. It is on wherever the Antigravity sync runs, with no extra setting. A missing agy or a non-SUCCESS status is skipped quietly. agy reports no tokens, so the conversation DB scan stays for token usage and cost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRfuvHAKPrJdv5Pd2Ym --- CLAUDE.md | 2 +- README.md | 2 +- daemon/antigravity_usage_sync.go | 85 +++++++- daemon/antigravity_usage_sync_test.go | 89 +++++++++ daemon/main_test.go | 6 + docs/CONFIG.md | 6 +- model/antigravity_quota.go | 275 ++++++++++++++++++++++++++ model/antigravity_quota_test.go | 179 +++++++++++++++++ 8 files changed, 636 insertions(+), 8 deletions(-) create mode 100644 model/antigravity_quota.go create mode 100644 model/antigravity_quota_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 9977a66..d603cd8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -104,7 +104,7 @@ 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` +- **AntigravityUsageSyncService**: every 10 min while `antigravity`/`agy` is running, reads Antigravity's quota by running `agy usage --json` (`model/antigravity_quota.go`: the Antigravity CLI, found on PATH, else `~/.local/bin`, `/opt/homebrew/bin`, `/usr/local/bin`; 20 s budget; a missing agy or a non-`SUCCESS` status is skipped quietly, `AntigravityQuotaSkipReason`) and posts it to `/api/v1/antigravity-usage`: every bucket of every model group as a window with its used share (100 minus `remaining_fraction`), reset time (empty for agy's epoch, a window not started) and length (`5h` 300, `weekly` 10080 minutes). `agy usage` reports no tokens, so the service also scans modified local Antigravity SQLite conversation DBs (`~/.gemini/antigravity*`, `~/.config/antigravity`, or `ANTIGRAVITY_DATA_DIR`) and uploads deduplicated token usage to `/api/v1/cc/backfill`. The `daemon` `TestMain` stubs `fetchAntigravityQuotaFunc`, so no test runs the machine's agy - **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 cf4a667..a69bed6 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ shelltime agy backfill # upload Antigravity token usage - 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. +- 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, and reads Antigravity's quota (5-hour and weekly windows per model group) with `agy usage --json` when the Antigravity CLI is installed. - 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. diff --git a/daemon/antigravity_usage_sync.go b/daemon/antigravity_usage_sync.go index 4799c0b..c107279 100644 --- a/daemon/antigravity_usage_sync.go +++ b/daemon/antigravity_usage_sync.go @@ -16,10 +16,12 @@ var ( collectAntigravityDBFilesFunc = model.CollectAntigravityDBFiles parseAntigravityDBFilesFunc = model.ParseAntigravityDBFiles antigravityDBFingerprintFunc = model.AntigravityDBFingerprint + fetchAntigravityQuotaFunc = model.FetchAntigravityQuota ) -// AntigravityUsageSyncService periodically scans local Antigravity SQLite conversation DBs -// and syncs newly updated token usage to the ShellTime server while Antigravity is running. +// AntigravityUsageSyncService syncs Antigravity usage to the ShellTime server while Antigravity +// is running: its quota, read from `agy usage --json` (the Antigravity CLI), and the token usage +// of its local SQLite conversation DBs, which agy doesn't report. type AntigravityUsageSyncService struct { config model.ShellTimeConfig interval time.Duration @@ -82,11 +84,12 @@ func (s *AntigravityUsageSyncService) sync(parentCtx context.Context) { return } + running := isAntigravityRunning() s.mu.Lock() pending := s.hasPending s.mu.Unlock() - if !isAntigravityRunning() && !pending { + if !running && !pending { slog.Debug("Skipping antigravity usage sync", slog.String("reason", "antigravity_not_running")) return } @@ -94,6 +97,17 @@ func (s *AntigravityUsageSyncService) sync(parentCtx context.Context) { if parentCtx == nil { parentCtx = context.Background() } + + if running { + if err := syncAntigravityQuota(parentCtx, s.config); err != nil { + if reason, ok := model.AntigravityQuotaSkipReason(err); ok { + slog.Debug("Skipping antigravity quota sync", slog.String("reason", reason), slog.Any("err", err)) + } else { + slog.Warn("Failed to sync antigravity quota", slog.Any("err", err)) + } + } + } + ctx, cancel := context.WithTimeout(parentCtx, 30*time.Second) defer cancel() @@ -102,6 +116,71 @@ func (s *AntigravityUsageSyncService) sync(parentCtx context.Context) { } } +// syncAntigravityQuota reads Antigravity's quota with `agy usage --json` and sends it to the +// server, which shows it on the agent pages and notifies when a window resets. +func syncAntigravityQuota(ctx context.Context, config model.ShellTimeConfig) error { + if config.Token == "" { + return nil + } + windows, err := fetchAntigravityQuotaFunc(ctx) + if err != nil { + return err + } + if len(windows) == 0 { + return nil + } + return sendAntigravityUsageToServer(ctx, config, windows) +} + +func sendAntigravityUsageToServer(ctx context.Context, config model.ShellTimeConfig, windows []model.AntigravityQuotaWindow) error { + if config.Token == "" || len(windows) == 0 { + return nil + } + + type usageWindow struct { + LimitID string `json:"limit_id"` + LimitName string `json:"limit_name"` + GroupName string `json:"group_name"` + GroupDescription string `json:"group_description"` + UsagePercentage float64 `json:"usage_percentage"` + ResetsAt string `json:"resets_at"` // empty while the window has not started + WindowDurationMinutes int `json:"window_duration_minutes"` + } + type usagePayload struct { + SchemaVersion int `json:"schema_version"` + Windows []usageWindow `json:"windows"` + } + + payload := usagePayload{SchemaVersion: 1, Windows: make([]usageWindow, len(windows))} + for i, w := range windows { + resetsAt := "" + if !w.ResetAt.IsZero() { + resetsAt = w.ResetAt.UTC().Format(time.RFC3339) + } + payload.Windows[i] = usageWindow{ + LimitID: w.LimitID, + LimitName: w.LimitName, + GroupName: w.GroupName, + GroupDescription: w.GroupDescription, + UsagePercentage: w.UsagePercentage(), + ResetsAt: resetsAt, + WindowDurationMinutes: w.WindowDurationMinutes, + } + } + + return model.SendHTTPRequestJSON(model.HTTPRequestOptions[usagePayload, any]{ + Context: ctx, + Endpoint: model.Endpoint{ + Token: config.Token, + APIEndpoint: config.APIEndpoint, + }, + Method: "POST", + Path: "/api/v1/antigravity-usage", + Payload: payload, + Timeout: 5 * time.Second, + }) +} + func (s *AntigravityUsageSyncService) syncOnce(ctx context.Context) error { now := time.Now() since := now.Add(-antigravityUsageInitialLookback) diff --git a/daemon/antigravity_usage_sync_test.go b/daemon/antigravity_usage_sync_test.go index 95993b1..b2b0c22 100644 --- a/daemon/antigravity_usage_sync_test.go +++ b/daemon/antigravity_usage_sync_test.go @@ -97,3 +97,92 @@ func TestAntigravityUsageSyncService_SkipsUnchangedDBs(t *testing.T) { assert.Equal(t, int32(2), parseCalls.Load()) assert.Equal(t, int32(2), backfillHits.Load()) } + +func TestAntigravityUsageSyncService_SendsQuotaFromAgyUsage(t *testing.T) { + origList := listProcessNamesFunc + origRoots := antigravityDataRootsFunc + origCollect := collectAntigravityDBFilesFunc + origQuota := fetchAntigravityQuotaFunc + t.Cleanup(func() { + listProcessNamesFunc = origList + antigravityDataRootsFunc = origRoots + collectAntigravityDBFilesFunc = origCollect + fetchAntigravityQuotaFunc = origQuota + }) + + type window struct { + LimitID string `json:"limit_id"` + LimitName string `json:"limit_name"` + GroupName string `json:"group_name"` + GroupDescription string `json:"group_description"` + UsagePercentage float64 `json:"usage_percentage"` + ResetsAt string `json:"resets_at"` + WindowDurationMinutes int `json:"window_duration_minutes"` + } + var got struct { + SchemaVersion int `json:"schema_version"` + Windows []window `json:"windows"` + } + var quotaHits atomic.Int32 + var auth string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/antigravity-usage" { + w.WriteHeader(http.StatusNotFound) + return + } + quotaHits.Add(1) + auth = r.Header.Get("Authorization") + _ = json.NewDecoder(r.Body).Decode(&got) + w.WriteHeader(http.StatusNoContent) + })) + defer srv.Close() + + running := true + listProcessNamesFunc = func() ([]string, error) { + if running { + return []string{"/Applications/Antigravity.app/Contents/MacOS/Antigravity"}, nil + } + return []string{"zsh"}, nil + } + antigravityDataRootsFunc = func() []string { return nil } + collectAntigravityDBFilesFunc = func([]string, time.Time) ([]string, error) { return nil, nil } + + var quotaCalls atomic.Int32 + reset := time.Date(2026, 12, 8, 15, 18, 15, 0, time.UTC) + fetchAntigravityQuotaFunc = func(context.Context) ([]model.AntigravityQuotaWindow, error) { + quotaCalls.Add(1) + return []model.AntigravityQuotaWindow{ + {LimitID: "gemini-weekly", LimitName: "Weekly Limit Remaining", GroupName: "Gemini Models", GroupDescription: "Models within this group: Gemini 4 Neon", RemainingFraction: 0.75, ResetAt: reset, WindowDurationMinutes: 10080}, + {LimitID: "3p-5h", LimitName: "Five Hour Limit Remaining", GroupName: "Claude and GPT models", RemainingFraction: 1, WindowDurationMinutes: 300}, + }, nil + } + + svc := NewAntigravityUsageSyncService(model.ShellTimeConfig{Token: "st_test", APIEndpoint: srv.URL}) + svc.sync(context.Background()) + + assert.Equal(t, int32(1), quotaHits.Load()) + assert.Equal(t, "CLI st_test", auth) + assert.Equal(t, 1, got.SchemaVersion) + if assert.Len(t, got.Windows, 2) { + assert.Equal(t, window{ + LimitID: "gemini-weekly", LimitName: "Weekly Limit Remaining", GroupName: "Gemini Models", + GroupDescription: "Models within this group: Gemini 4 Neon", UsagePercentage: 25, + ResetsAt: "2026-12-08T15:18:15Z", WindowDurationMinutes: 10080, + }, got.Windows[0]) + assert.Equal(t, "", got.Windows[1].ResetsAt, "a window that has not started has no reset time") + assert.Zero(t, got.Windows[1].UsagePercentage) + } + + // Without Antigravity running, agy is not asked. + running = false + svc.sync(context.Background()) + assert.Equal(t, int32(1), quotaCalls.Load()) + + // agy missing is skipped quietly and nothing is sent. + running = true + fetchAntigravityQuotaFunc = func(context.Context) ([]model.AntigravityQuotaWindow, error) { + return nil, model.ErrAgyNotInstalled + } + svc.sync(context.Background()) + assert.Equal(t, int32(1), quotaHits.Load()) +} diff --git a/daemon/main_test.go b/daemon/main_test.go index cecb185..d560873 100644 --- a/daemon/main_test.go +++ b/daemon/main_test.go @@ -1,11 +1,13 @@ package daemon import ( + "context" "fmt" "os" "testing" "github.com/malamtime/cli/agenthook" + "github.com/malamtime/cli/model" ) // TestMain clears the cloud environment variables, so the suite gives the same results inside a @@ -22,6 +24,10 @@ func TestMain(m *testing.M) { os.Unsetenv("SHELLTIME_CLOUD") // An Antigravity sandbox runs as the OS user antigravity, which counts as a cloud VM agenthook.OSUserLookup = func() (string, error) { return "shelltime-test", nil } + // Never run the machine's agy: tests that read Antigravity's quota stub it themselves + fetchAntigravityQuotaFunc = func(context.Context) ([]model.AntigravityQuotaWindow, error) { + return nil, model.ErrAgyNotInstalled + } os.Exit(runInTempHome(m)) } diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 62227a0..5344e8b 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -356,17 +356,17 @@ agentHooks: ### 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: +In addition to hooks, `shelltime-daemon` collects token usage and the agent's 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`). +- **Antigravity (`agy`)**: Reads its quota (a 5-hour and a weekly window for each model group, such as Gemini Models and Claude and GPT models) by running `agy usage --json`, the [Antigravity CLI](https://antigravity.google/docs/cli/install), found on `PATH` or in `~/.local/bin`, where its installer puts it; without `agy` the quota is skipped. Only the windows' used share, reset time and group names are sent (`/api/v1/antigravity-usage`). Token usage, which `agy usage` doesn't report, still comes from the 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 | +| `antigravity.enabled` | boolean | follows `aiCodeOtel.enabled` | Enable or disable periodic Antigravity quota (`agy usage --json`) & token usage sync in the daemon | ```yaml cursor: diff --git a/model/antigravity_quota.go b/model/antigravity_quota.go new file mode 100644 index 0000000..c058356 --- /dev/null +++ b/model/antigravity_quota.go @@ -0,0 +1,275 @@ +package model + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "math" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "time" +) + +// AntigravityQuotaWindow is one quota window of Google Antigravity, read from +// `agy usage --json`: a bucket of a model group, such as Gemini Models' 5-hour limit. +type AntigravityQuotaWindow struct { + // LimitID is Antigravity's bucket id, e.g. "gemini-5h" or "3p-weekly". + LimitID string + // LimitName is Antigravity's bucket name, e.g. "Five Hour Limit Remaining". + LimitName string + // GroupName is the model group sharing the window, e.g. "Gemini Models". + GroupName string + // GroupDescription lists the group's models, as Antigravity words it. + GroupDescription string + // Window is Antigravity's window name: "5h", "weekly", ... + Window string + // RemainingFraction is the share of the window left, 0 to 1. + RemainingFraction float64 + // ResetAt is when the window is full again; zero while it has not started + // (Antigravity reports the Unix epoch then, and the window is full). + ResetAt time.Time + // WindowDurationMinutes is the window's length (300 for "5h", 10080 for + // "weekly"), 0 when Antigravity names a length this doesn't know. + WindowDurationMinutes int +} + +// UsagePercentage is the share of the window used, 0 to 100. +func (w AntigravityQuotaWindow) UsagePercentage() float64 { + used := (1 - w.RemainingFraction) * 100 + return math.Min(100, math.Max(0, used)) +} + +var ( + // ErrAgyNotInstalled means no `agy` binary was found: the Antigravity CLI + // (https://antigravity.google/docs/cli/install) is not installed, or not + // where the daemon looks. + ErrAgyNotInstalled = errors.New("agy (Antigravity CLI) not installed") + // ErrAgyUsageUnavailable means `agy usage --json` ran but gave no quota. + ErrAgyUsageUnavailable = errors.New("agy usage reported no quota") +) + +// AntigravityQuotaSkipReason names an expected reason a quota reading can't be +// taken (agy missing, signed out), which the daemon logs quietly. +func AntigravityQuotaSkipReason(err error) (string, bool) { + switch { + case errors.Is(err, ErrAgyNotInstalled): + return "agy_not_installed", true + case errors.Is(err, ErrAgyUsageUnavailable): + return "agy_usage_unavailable", true + } + return "", false +} + +// agyUsageTimeout bounds one `agy usage --json` run: it asks Google's servers. +const agyUsageTimeout = 20 * time.Second + +// agyEpochFloor: a reset time this early is Antigravity's "not started", not a date. +var agyEpochFloor = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + +// agyLookPathFunc finds the agy binary. It is a var so tests can stub it. +var agyLookPathFunc = lookupAgy + +// agyRunUsageFunc runs `agy usage --json` and returns its stdout. It is a var so +// tests never start a real agy. +var agyRunUsageFunc = runAgyUsage + +// AntigravityCLISearchPaths are the places the daemon looks for agy beyond PATH: +// the official installer puts it in ~/.local/bin, which a daemon's PATH lacks. +func AntigravityCLISearchPaths() []string { + home, _ := os.UserHomeDir() + if runtime.GOOS == "windows" { + var paths []string + if local := os.Getenv("LOCALAPPDATA"); local != "" { + paths = append(paths, filepath.Join(local, "agy", "bin", "agy.exe")) + } + return paths + } + paths := []string{} + if home != "" { + paths = append(paths, filepath.Join(home, ".local", "bin", "agy")) + } + return append(paths, "/opt/homebrew/bin/agy", "/usr/local/bin/agy") +} + +func lookupAgy() (string, error) { + if path, err := exec.LookPath("agy"); err == nil { + return path, nil + } + for _, path := range AntigravityCLISearchPaths() { + info, err := os.Stat(path) + if err != nil || info.IsDir() { + continue + } + if runtime.GOOS != "windows" && info.Mode()&0o111 == 0 { + continue + } + return path, nil + } + return "", ErrAgyNotInstalled +} + +func runAgyUsage(ctx context.Context, path string) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, agyUsageTimeout) + defer cancel() + + cmd := exec.CommandContext(ctx, path, "usage", "--json") + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + // A child that agy leaves holding the pipes must not keep the daemon waiting. + cmd.WaitDelay = 2 * time.Second + err := cmd.Run() + if ctx.Err() != nil { + return nil, fmt.Errorf("agy usage --json: %w", ctx.Err()) + } + if err != nil { + // agy may still have printed its JSON envelope with a failure status. + if stdout.Len() > 0 { + return stdout.Bytes(), nil + } + msg := strings.TrimSpace(stderr.String()) + if len(msg) > 300 { + msg = msg[:300] + } + if msg != "" { + return nil, fmt.Errorf("agy usage --json: %w: %s", err, msg) + } + return nil, fmt.Errorf("agy usage --json: %w", err) + } + return stdout.Bytes(), nil +} + +// FetchAntigravityQuota runs `agy usage --json` and returns Antigravity's quota windows. +func FetchAntigravityQuota(ctx context.Context) ([]AntigravityQuotaWindow, error) { + path, err := agyLookPathFunc() + if err != nil { + return nil, err + } + out, err := agyRunUsageFunc(ctx, path) + if err != nil { + return nil, err + } + return ParseAntigravityUsage(out) +} + +type agyUsageEnvelope struct { + Status string `json:"status"` + Response string `json:"response"` + Command *struct { + Name string `json:"name"` + Data *struct { + Groups []agyUsageGroup `json:"groups"` + } `json:"data"` + } `json:"command"` +} + +type agyUsageGroup struct { + Name string `json:"name"` + Description string `json:"description"` + Buckets []agyUsageBucket `json:"buckets"` +} + +type agyUsageBucket struct { + ID string `json:"id"` + Name string `json:"name"` + Window string `json:"window"` + RemainingFraction *float64 `json:"remaining_fraction"` + ResetTime string `json:"reset_time"` +} + +// ParseAntigravityUsage reads the output of `agy usage --json`: a JSON envelope +// whose command.data.groups hold the model groups and their quota buckets. Text +// agy prints before the envelope (an update notice) is skipped. +func ParseAntigravityUsage(raw []byte) ([]AntigravityQuotaWindow, error) { + start := bytes.IndexByte(raw, '{') + if start < 0 { + return nil, fmt.Errorf("%w: no JSON in agy output", ErrAgyUsageUnavailable) + } + var env agyUsageEnvelope + if err := json.NewDecoder(bytes.NewReader(raw[start:])).Decode(&env); err != nil { + return nil, fmt.Errorf("parse agy usage output: %w", err) + } + if status := strings.TrimSpace(env.Status); status != "" && !strings.EqualFold(status, "SUCCESS") { + detail := strings.TrimSpace(env.Response) + if len(detail) > 200 { + detail = detail[:200] + } + return nil, fmt.Errorf("%w: status %s: %s", ErrAgyUsageUnavailable, status, detail) + } + if env.Command == nil || env.Command.Data == nil { + return nil, fmt.Errorf("%w: no usage data", ErrAgyUsageUnavailable) + } + + var windows []AntigravityQuotaWindow + seen := map[string]bool{} + for _, g := range env.Command.Data.Groups { + for _, b := range g.Buckets { + id := strings.TrimSpace(b.ID) + if id == "" || b.RemainingFraction == nil || seen[id] { + continue + } + remaining := *b.RemainingFraction + if math.IsNaN(remaining) || math.IsInf(remaining, 0) { + continue + } + seen[id] = true + w := AntigravityQuotaWindow{ + LimitID: id, + LimitName: strings.TrimSpace(b.Name), + GroupName: strings.TrimSpace(g.Name), + GroupDescription: strings.TrimSpace(g.Description), + Window: strings.TrimSpace(b.Window), + RemainingFraction: math.Min(1, math.Max(0, remaining)), + WindowDurationMinutes: agyWindowMinutes(b.Window), + } + if t, err := time.Parse(time.RFC3339, strings.TrimSpace(b.ResetTime)); err == nil && !t.Before(agyEpochFloor) { + w.ResetAt = t.UTC() + } + windows = append(windows, w) + } + } + if len(windows) == 0 { + return nil, fmt.Errorf("%w: no quota buckets", ErrAgyUsageUnavailable) + } + return windows, nil +} + +var agyWindowRe = regexp.MustCompile(`^(\d+)\s*(m|min|h|hr|hour|d|day|w|wk|week)s?$`) + +// agyWindowMinutes turns Antigravity's window name ("5h", "weekly") into minutes. +func agyWindowMinutes(window string) int { + w := strings.ToLower(strings.TrimSpace(window)) + switch w { + case "hourly": + return 60 + case "daily": + return 24 * 60 + case "weekly": + return 7 * 24 * 60 + } + m := agyWindowRe.FindStringSubmatch(w) + if m == nil { + return 0 + } + n, err := strconv.Atoi(m[1]) + if err != nil { + return 0 + } + switch m[2] { + case "m", "min": + return n + case "h", "hr", "hour": + return n * 60 + case "d", "day": + return n * 24 * 60 + default: + return n * 7 * 24 * 60 + } +} diff --git a/model/antigravity_quota_test.go b/model/antigravity_quota_test.go new file mode 100644 index 0000000..b7ebcfa --- /dev/null +++ b/model/antigravity_quota_test.go @@ -0,0 +1,179 @@ +package model + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// agyUsageSample is `agy usage --json` as Antigravity CLI prints it. +const agyUsageSample = `{"conversation_id":"","status":"SUCCESS","response":"Gemini Models\tWeekly Limit Remaining\t84%\t2026-12-08T15:18:15Z\n","duration_seconds":0,"num_turns":0,"usage":{"input_tokens":0,"output_tokens":0,"thinking_tokens":0,"cache_read_tokens":0,"total_tokens":0},"command":{"name":"usage","data":{"description":"Within each group, models share a weekly limit and a 5-hour limit.","groups":[{"name":"Gemini Models","description":"Models within this group: Gemini 4 Neon, Gemini 4 Carbon","buckets":[{"id":"gemini-weekly","name":"Weekly Limit Remaining","description":"You have used some of your weekly limit, it will fully refresh in 6 days, 5 hours.","window":"weekly","remaining_fraction":0.8413210511207581,"reset_time":"2026-12-08T15:18:15Z"},{"id":"gemini-5h","name":"Five Hour Limit Remaining","window":"5h","remaining_fraction":1,"reset_time":"2026-12-02T14:52:39Z"}]},{"name":"Claude and GPT models","description":"Models within this group: Claude Opus 5.5, Claude Sonnet 5.5","buckets":[{"id":"3p-weekly","name":"Weekly Limit Remaining","window":"weekly","remaining_fraction":0.5,"reset_time":"2026-12-05T13:59:49Z"},{"id":"3p-5h","name":"Five Hour Limit Remaining","window":"5h","remaining_fraction":1,"reset_time":"1970-01-01T00:00:00Z"}]}]}}}` + +func TestParseAntigravityUsage(t *testing.T) { + windows, err := ParseAntigravityUsage([]byte(agyUsageSample)) + require.NoError(t, err) + require.Len(t, windows, 4) + + assert.Equal(t, "gemini-weekly", windows[0].LimitID) + assert.Equal(t, "Weekly Limit Remaining", windows[0].LimitName) + assert.Equal(t, "Gemini Models", windows[0].GroupName) + assert.Equal(t, "Models within this group: Gemini 4 Neon, Gemini 4 Carbon", windows[0].GroupDescription) + assert.Equal(t, 10080, windows[0].WindowDurationMinutes) + assert.InDelta(t, 15.87, windows[0].UsagePercentage(), 0.01) + assert.Equal(t, time.Date(2026, 12, 8, 15, 18, 15, 0, time.UTC), windows[0].ResetAt) + + assert.Equal(t, "gemini-5h", windows[1].LimitID) + assert.Equal(t, 300, windows[1].WindowDurationMinutes) + assert.Zero(t, windows[1].UsagePercentage()) + + assert.Equal(t, "3p-weekly", windows[2].LimitID) + assert.Equal(t, "Claude and GPT models", windows[2].GroupName) + assert.InDelta(t, 50, windows[2].UsagePercentage(), 0.001) + + assert.Equal(t, "3p-5h", windows[3].LimitID) + assert.True(t, windows[3].ResetAt.IsZero(), "the epoch means the window has not started") +} + +func TestParseAntigravityUsage_SkipsNoiseAndBadBuckets(t *testing.T) { + out := "A new version of agy is available.\n" + `{"status":"SUCCESS","command":{"name":"usage","data":{"groups":[{"name":"G","buckets":[` + + `{"id":"","window":"5h","remaining_fraction":1},` + + `{"id":"no-fraction","window":"5h"},` + + `{"id":"over","window":"2d","remaining_fraction":1.5,"reset_time":"not a time"},` + + `{"id":"over","window":"5h","remaining_fraction":0}]}]}}}` + "\ntrailing" + windows, err := ParseAntigravityUsage([]byte(out)) + require.NoError(t, err) + require.Len(t, windows, 1) + assert.Equal(t, "over", windows[0].LimitID) + assert.Equal(t, 2*24*60, windows[0].WindowDurationMinutes) + assert.Equal(t, 1.0, windows[0].RemainingFraction, "clamped to 1") + assert.Zero(t, windows[0].UsagePercentage()) + assert.True(t, windows[0].ResetAt.IsZero()) +} + +func TestParseAntigravityUsage_Failures(t *testing.T) { + for name, out := range map[string]string{ + "not json": "agy: command not found", + "signed out": `{"status":"ERROR","response":"Please sign in with agy login"}`, + "no data": `{"status":"SUCCESS","command":{"name":"usage"}}`, + "no buckets": `{"status":"SUCCESS","command":{"name":"usage","data":{"groups":[{"name":"G","buckets":[]}]}}}`, + } { + t.Run(name, func(t *testing.T) { + _, err := ParseAntigravityUsage([]byte(out)) + require.Error(t, err) + reason, ok := AntigravityQuotaSkipReason(err) + assert.True(t, ok) + assert.Equal(t, "agy_usage_unavailable", reason) + }) + } + + _, err := ParseAntigravityUsage([]byte(`{"status":`)) + require.Error(t, err) + _, ok := AntigravityQuotaSkipReason(err) + assert.False(t, ok, "broken JSON is not an expected state") +} + +func TestAgyWindowMinutes(t *testing.T) { + for in, want := range map[string]int{ + "5h": 300, "weekly": 10080, "daily": 1440, "hourly": 60, "30m": 30, "7d": 10080, + "1w": 10080, "2 hours": 120, "monthly": 0, "": 0, + } { + assert.Equal(t, want, agyWindowMinutes(in), in) + } +} + +func TestFetchAntigravityQuota(t *testing.T) { + origLook, origRun := agyLookPathFunc, agyRunUsageFunc + t.Cleanup(func() { agyLookPathFunc, agyRunUsageFunc = origLook, origRun }) + + agyLookPathFunc = func() (string, error) { return "", ErrAgyNotInstalled } + _, err := FetchAntigravityQuota(context.Background()) + reason, ok := AntigravityQuotaSkipReason(err) + assert.True(t, ok) + assert.Equal(t, "agy_not_installed", reason) + + var ranWith string + agyLookPathFunc = func() (string, error) { return "/fake/agy", nil } + agyRunUsageFunc = func(_ context.Context, path string) ([]byte, error) { + ranWith = path + return []byte(agyUsageSample), nil + } + windows, err := FetchAntigravityQuota(context.Background()) + require.NoError(t, err) + assert.Len(t, windows, 4) + assert.Equal(t, "/fake/agy", ranWith) + + agyRunUsageFunc = func(context.Context, string) ([]byte, error) { return nil, errors.New("boom") } + _, err = FetchAntigravityQuota(context.Background()) + require.EqualError(t, err, "boom") +} + +func TestRunAgyUsage(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("uses a shell script as agy") + } + dir := t.TempDir() + write := func(name, script string) string { + path := filepath.Join(dir, name) + require.NoError(t, os.WriteFile(path, []byte("#!/bin/sh\n"+script), 0o755)) + return path + } + + // Called as `agy usage --json` + ok := write("agy-ok", `[ "$1 $2" = "usage --json" ] || exit 9 +echo '{"status":"SUCCESS"}'`) + out, err := runAgyUsage(context.Background(), ok) + require.NoError(t, err) + assert.JSONEq(t, `{"status":"SUCCESS"}`, string(out)) + + // A failing run that still printed its envelope is read for its status + failedEnvelope := write("agy-envelope", `echo '{"status":"ERROR","response":"not signed in"}'; exit 1`) + out, err = runAgyUsage(context.Background(), failedEnvelope) + require.NoError(t, err) + _, err = ParseAntigravityUsage(out) + assert.ErrorIs(t, err, ErrAgyUsageUnavailable) + + failed := write("agy-fail", `echo 'unknown command' >&2; exit 2`) + _, err = runAgyUsage(context.Background(), failed) + require.Error(t, err) + assert.Contains(t, err.Error(), "unknown command") + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + slow := write("agy-slow", `sleep 10`) + start := time.Now() + _, err = runAgyUsage(ctx, slow) + require.Error(t, err) + assert.Less(t, time.Since(start), 5*time.Second) +} + +func TestLookupAgyFindsTheInstallersFolder(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("unix install path") + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("PATH", t.TempDir()) + _, err := lookupAgy() + if err == nil { + t.Skip("an agy is installed system-wide on this machine") + } + require.ErrorIs(t, err, ErrAgyNotInstalled) + + bin := filepath.Join(home, ".local", "bin") + require.NoError(t, os.MkdirAll(bin, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(bin, "agy"), []byte("#!/bin/sh\n"), 0o644)) + _, err = lookupAgy() + require.ErrorIs(t, err, ErrAgyNotInstalled, "not executable") + + require.NoError(t, os.Chmod(filepath.Join(bin, "agy"), 0o755)) + path, err := lookupAgy() + require.NoError(t, err) + assert.Equal(t, filepath.Join(bin, "agy"), path) +}