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: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<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
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions cmd/daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions commands/agy.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ var AgyCommand = &cli.Command{
Subcommands: []*cli.Command{
AgyInstallCommand,
AgyUninstallCommand,
AgyBackfillCommand,
},
}

Expand Down
60 changes: 54 additions & 6 deletions commands/aicode_backfill.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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{
Expand Down Expand Up @@ -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)

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 messages after this scan still assume transcript files. parsed.Files is the number of API scopes for Cursor, so a Cursor user with no sessions sees "No finished Cursor sessions found in 1 files." The slog.Warn("skipped unreadable transcript lines") also reads wrongly for DB rows and API events, and the new parsed.FailedFiles is never reported by the CLI. Fix: use wording that fits all sources, such as "in N sources", and log FailedFiles.

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)))
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
}
Expand Down
49 changes: 49 additions & 0 deletions commands/aicode_backfill_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
1 change: 1 addition & 0 deletions commands/cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ var CursorCommand = &cli.Command{
Subcommands: []*cli.Command{
CursorInstallCommand,
CursorUninstallCommand,
CursorBackfillCommand,
},
}

Expand Down
Loading
Loading