Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<host>/<path>` 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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
85 changes: 82 additions & 3 deletions daemon/antigravity_usage_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -82,18 +84,30 @@ 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
}

if parentCtx == nil {
parentCtx = context.Background()
}

if running {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): the quota pass runs inline in sync, before the token sync, and nothing in it watches stopChan. agy usage --json can take up to 20 s and the POST 5 s. Stop() (which calls wg.Wait()) can therefore block about 25 s if the daemon context is not cancelled first, and a hung agy delays the token backfill by the same time on every tick. A failed quota call also logs Warn on every cycle, and an older server answering 404 on /api/v1/antigravity-usage makes SendHTTPRequestJSON log Error plus Warn every 10 minutes (the Cursor sync behaves the same). Fix: run the quota pass after the token sync, or in its own goroutine tied to stopChan, and treat HTTPStatusError 404/405 as a quiet skip.

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()

Expand All @@ -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)
Expand Down
89 changes: 89 additions & 0 deletions daemon/antigravity_usage_sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): auth and got are written by the httptest handler goroutine and read by the test goroutine without synchronization, while quotaHits is atomic. Nothing orders the plain writes before the reads, so go test -race can report a race. Fix: guard auth and got with a mutex, or pass them through a channel.

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())
}
6 changes: 6 additions & 0 deletions daemon/main_test.go
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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))
}

Expand Down
6 changes: 3 additions & 3 deletions docs/CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading