The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
endpoint: add `beacon endpoint cursor usage sync|status`
Claude2ee58a724f98
diff --git a/cli/beacon/cmd/endpoint_cursor.go b/cli/beacon/cmd/endpoint_cursor.goindex a360425a..9d881c25 100644--- a/cli/beacon/cmd/endpoint_cursor.go+++ b/cli/beacon/cmd/endpoint_cursor.go@@ -27,7 +27,11 @@ agent transcripts under ~/.cursor/projects. Beacon reads those committed localrecords and converts them into endpoint events marked harness.collection_method=poll.Reading is local and offline. Run 'sync' on a schedule, or with --watch, to keep-the runtime log current.`,+the runtime log current.++Cursor's local records carry no token counts. 'usage sync' collects Cursor's token+usage and charges from the Cursor Admin API instead; it is the one Cursor command+that uses the network, and only when you run it.`,}var endpointCursorSyncCmd = &cobra.Command{diff --git a/cli/beacon/cmd/endpoint_cursor_usage.go b/cli/beacon/cmd/endpoint_cursor_usage.gonew file mode 100644index 00000000..57e0a841--- /dev/null+++ b/cli/beacon/cmd/endpoint_cursor_usage.go@@ -0,0 +1,366 @@+package cmd++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/cursorsession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/cursorusage"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+ "github.com/spf13/cobra"+)++// defaultCursorAdminKeyEnv is the environment variable the Cursor Admin API key is read from.+//+// An environment variable and nothing else, on purpose. Beacon does not store third-party service+// credentials, and an admin key is a team-wide credential: it can read every member's usage. So it+// is never written to Beacon's config, state, or log, never accepted as a flag value (where it+// would land in shell history and the process table), and never printed. Whoever runs the sync+// supplies it for that run.+const defaultCursorAdminKeyEnv = "CURSOR_ADMIN_API_KEY"++// `beacon endpoint cursor usage` collects Cursor's token usage from the Cursor Admin API.+//+// It is the one Cursor path that reaches the network, and only when someone runs it. Cursor's hooks+// and local session records carry no token counts, so without it Cursor contributes nothing to+// `beacon token-usage`; with it, each model request Cursor reports becomes a token.usage event in+// the runtime log, beside everything else Beacon recorded.+var endpointCursorUsageCmd = &cobra.Command{+ Use: "usage",+ Short: "Collect Cursor token usage from the Cursor Admin API",+ Long: `Collect Cursor token usage and charges from the Cursor Admin API.++Cursor's hooks and local session records carry no token counts. The Cursor Admin+API does: it reports every model request with its input, output, and cache tokens+and what Cursor charged for it. 'sync' reads those events and writes one+token.usage event per request to the runtime log, so 'beacon token-usage' and the+dashboard token view include Cursor.++This is the one Cursor command that uses the network. It calls+https://api.cursor.com only when you run it; hooks never do.++Set the key in your environment before running it. Create one in the Cursor+dashboard under Settings > Advanced > Admin API Keys (team admins only):++ export CURSOR_ADMIN_API_KEY=key_...+ beacon endpoint cursor usage sync++The key is read from the environment for that run only. Beacon never writes it to+its config, state, or logs, and never prints it.++By default the sync collects only the usage of the Cursor account signed in on+this machine, read from Cursor's local storage. Use --email or --user-id to choose+a member, or --team for the whole team.`,+}++var endpointCursorUsageSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Cursor Admin API usage events into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointCursorUsageSync,+}++var endpointCursorUsageStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show the Cursor usage collector's progress and configuration",+ SilenceUsage: true,+ RunE: runEndpointCursorUsageStatus,+}++var endpointCursorUsageOpts struct {+ apiKeyEnv string+ baseURL string+ email string+ userID string+ team bool+ since string+ lookback time.Duration+ pageSize int+ statePath string+ logPath string+ globalDB string+ print bool+}++// Seams for tests: the client the sync talks to and the clock it reads.+var (+ newCursorUsageFetcher = func(apiKey, baseURL string) (cursorusage.Fetcher, error) {+ base, err := cursorusage.ValidateBaseURL(baseURL)+ if err != nil {+ return nil, err+ }+ client := cursorusage.NewClient(apiKey)+ client.BaseURL = base+ client.UserAgent = "beacon/" + version.GetVersion()+ return client, nil+ }+ cursorUsageNow = time.Now+)++func init() {+ endpointCursorCmd.AddCommand(endpointCursorUsageCmd)+ endpointCursorUsageCmd.AddCommand(endpointCursorUsageSyncCmd)+ endpointCursorUsageCmd.AddCommand(endpointCursorUsageStatusCmd)++ for _, c := range []*cobra.Command{endpointCursorUsageSyncCmd, endpointCursorUsageStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointCursorUsageOpts.apiKeyEnv, "api-key-env", defaultCursorAdminKeyEnv, "Environment variable holding the Cursor Admin API key")+ f.StringVar(&endpointCursorUsageOpts.email, "email", "", "Collect usage for this team member (default: the Cursor account signed in on this machine)")+ f.StringVar(&endpointCursorUsageOpts.userID, "user-id", "", "Collect usage for this numeric Cursor user ID")+ f.BoolVar(&endpointCursorUsageOpts.team, "team", false, "Collect usage for every member of the team")+ f.StringVar(&endpointCursorUsageOpts.globalDB, "global-db", "", "Cursor global storage DB the signed-in account is read from (default OS-specific Cursor state.vscdb)")+ f.StringVar(&endpointCursorUsageOpts.statePath, "state", "", "Collector state file (default ~/.beacon/endpoint/state/cursor-usage.json)")+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")+ }++ sync := endpointCursorUsageSyncCmd.Flags()+ sync.StringVar(&endpointCursorUsageOpts.since, "since", "", "Collect from this date (YYYY-MM-DD or RFC 3339); default: 7 days back on the first sync, then from the last sync")+ sync.DurationVar(&endpointCursorUsageOpts.lookback, "lookback", cursorusage.DefaultLookback, "How far behind the last sync each sync re-reads, to catch late-posted events")+ sync.IntVar(&endpointCursorUsageOpts.pageSize, "page-size", 100, "Events per Admin API request")+ sync.StringVar(&endpointCursorUsageOpts.baseURL, "base-url", cursorusage.DefaultBaseURL, "Cursor Admin API base URL (https; plain http only to a loopback address)")+ sync.StringVar(&endpointCursorUsageOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointCursorUsageOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the collector state (dry run)")+}++func runEndpointCursorUsageSync(cmd *cobra.Command, args []string) error {+ opts := endpointCursorUsageOpts+ keyEnv := strings.TrimSpace(opts.apiKeyEnv)+ if keyEnv == "" {+ return errors.New("--api-key-env must name an environment variable")+ }+ apiKey := strings.TrimSpace(os.Getenv(keyEnv))+ if apiKey == "" {+ return fmt.Errorf("no Cursor Admin API key: set %s in your environment (create a key in the Cursor dashboard under Settings > Advanced > Admin API Keys)", keyEnv)+ }++ query, err := resolveCursorUsageQuery(opts.email, opts.userID, opts.team, opts.globalDB)+ if err != nil {+ return err+ }+ query.PageSize = opts.pageSize++ since, err := parseCursorUsageSince(opts.since)+ if err != nil {+ return err+ }+ if opts.lookback <= 0 {+ return errors.New("--lookback must be positive")+ }++ fetcher, err := newCursorUsageFetcher(apiKey, opts.baseURL)+ if err != nil {+ return err+ }++ userMode := endpointUserMode()+ collect := cursorusage.CollectOptions{+ Fetcher: fetcher,+ Query: query,+ Since: since,+ Lookback: opts.lookback,+ Now: cursorUsageNow,+ Print: opts.print,+ Out: cmd.OutOrStdout(),+ Write: !opts.print,+ UserMode: userMode,+ }+ // --print is a dry run in both directions, like the other sync commands: no log write and no+ // state advance, so running it twice shows the same events.+ if !opts.print {+ collect.StatePath = resolveCursorUsageStatePath(opts.statePath, userMode)+ collect.LogPath = lifecycle.ResolveRuntimeLog(userMode, opts.logPath).EffectiveLogPath+ }++ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ summary, err := cursorusage.CollectOnce(ctx, collect)+ if !opts.print {+ reportCursorUsageSync(cmd.OutOrStdout(), summary)+ }+ return err+}++func reportCursorUsageSync(out io.Writer, summary cursorusage.Summary) {+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(out).Encode(summary)+ return+ }+ fmt.Fprintf(out, "cursor usage sync (%s): %d fetched, %d written, %d already collected, %d without usage\n",+ summary.Scope, summary.Fetched, summary.Emitted, summary.Duplicates, summary.NoUsage)+ if summary.WindowStart != "" {+ fmt.Fprintf(out, " window %s .. %s\n", summary.WindowStart, summary.WindowEnd)+ }+}++// resolveCursorUsageQuery picks whose usage to collect. Exactly one of the explicit choices may be+// given; with none, it is the account signed in to Cursor on this machine.+//+// The default matters because an admin key reads the whole team. A sync on one person's laptop+// that silently collected everyone's usage would put every colleague's spend in that laptop's log,+// so the whole team is something you ask for with --team, never what you get by omission.+func resolveCursorUsageQuery(email, userID string, team bool, globalDB string) (cursorusage.Query, error) {+ email = strings.TrimSpace(email)+ userID = strings.TrimSpace(userID)+ chosen := 0+ for _, set := range []bool{email != "", userID != "", team} {+ if set {+ chosen+++ }+ }+ if chosen > 1 {+ return cursorusage.Query{}, errors.New("choose one of --email, --user-id, or --team")+ }+ switch {+ case email != "":+ return cursorusage.Query{Email: email}, nil+ case userID != "":+ return cursorusage.Query{UserID: userID}, nil+ case team:+ return cursorusage.Query{}, nil+ }+ signedIn, err := cursorsession.CachedAccountEmail(globalDB)+ if err != nil {+ return cursorusage.Query{}, fmt.Errorf("find the Cursor account signed in on this machine: %w (pass --email, --user-id, or --team)", err)+ }+ if signedIn == "" {+ return cursorusage.Query{}, errors.New("no Cursor account is signed in on this machine: pass --email, --user-id, or --team to choose whose usage to collect")+ }+ return cursorusage.Query{Email: signedIn}, nil+}++func parseCursorUsageSince(raw string) (time.Time, error) {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return time.Time{}, nil+ }+ if t, err := time.Parse(time.RFC3339, raw); err == nil {+ return t.UTC(), nil+ }+ if t, err := time.ParseInLocation("2006-01-02", raw, time.Local); err == nil {+ return t.UTC(), nil+ }+ return time.Time{}, fmt.Errorf("invalid --since %q: use YYYY-MM-DD or RFC 3339", raw)+}++// resolveCursorUsageStatePath mirrors the other collectors: a system-mode sync keeps its state+// beside the system runtime log, everything else uses the per-user default.+func resolveCursorUsageStatePath(override string, userMode bool) string {+ if strings.TrimSpace(override) != "" {+ return override+ }+ if !userMode {+ if dir := filepath.Dir(lifecycle.ResolveRuntimeLog(false, "").EffectiveLogPath); dir != "" && dir != "." {+ return filepath.Join(dir, "cursor-usage-state.json")+ }+ }+ return cursorusage.DefaultStatePath()+}++type cursorUsageScopeStatus struct {+ Scope string `json:"scope"`+ CoveredFrom string `json:"covered_from,omitempty"`+ CollectedTo string `json:"collected_to,omitempty"`+ LastSync string `json:"last_sync,omitempty"`+ TrackedKeys int `json:"tracked_keys"`+}++type cursorUsageStatusReport struct {+ APIKeyEnv string `json:"api_key_env"`+ // APIKeySet says whether the variable is set. The value itself is never read into the report.+ APIKeySet bool `json:"api_key_set"`+ // DefaultScope is the scope a sync with the same flags would use, or empty when none resolves.+ DefaultScope string `json:"default_scope,omitempty"`+ ScopeError string `json:"scope_error,omitempty"`+ StatePath string `json:"state_path"`+ Scopes []cursorUsageScopeStatus `json:"scopes"`+}++func runEndpointCursorUsageStatus(cmd *cobra.Command, args []string) error {+ opts := endpointCursorUsageOpts+ keyEnv := strings.TrimSpace(opts.apiKeyEnv)+ if keyEnv == "" {+ keyEnv = defaultCursorAdminKeyEnv+ }+ statePath := resolveCursorUsageStatePath(opts.statePath, endpointUserMode())+ state, err := cursorusage.LoadState(statePath)+ if err != nil {+ return err+ }+ report := cursorUsageStatusReport{+ APIKeyEnv: keyEnv,+ APIKeySet: strings.TrimSpace(os.Getenv(keyEnv)) != "",+ StatePath: statePath,+ Scopes: []cursorUsageScopeStatus{},+ }+ if query, err := resolveCursorUsageQuery(opts.email, opts.userID, opts.team, opts.globalDB); err != nil {+ report.ScopeError = err.Error()+ } else {+ report.DefaultScope = cursorusage.ScopeKey(query)+ }+ names := make([]string, 0, len(state.Scopes))+ for name := range state.Scopes {+ names = append(names, name)+ }+ sort.Strings(names)+ for _, name := range names {+ c := state.Scopes[name]+ report.Scopes = append(report.Scopes, cursorUsageScopeStatus{+ Scope: name,+ CoveredFrom: cursorUsageTime(c.CoveredFromMS),+ CollectedTo: cursorUsageTime(c.HighWaterMS),+ LastSync: cursorUsageTime(c.LastSyncMS),+ TrackedKeys: len(c.Seen),+ })+ }++ out := cmd.OutOrStdout()+ if endpointOpts.jsonOutput {+ return json.NewEncoder(out).Encode(report)+ }+ keyState := "not set"+ if report.APIKeySet {+ keyState = "set"+ }+ fmt.Fprintf(out, "Cursor Admin API key: %s is %s\n", report.APIKeyEnv, keyState)+ if report.DefaultScope != "" {+ fmt.Fprintf(out, "Scope: %s\n", report.DefaultScope)+ } else {+ fmt.Fprintf(out, "Scope: none (%s)\n", report.ScopeError)+ }+ fmt.Fprintf(out, "State: %s\n", report.StatePath)+ if len(report.Scopes) == 0 {+ fmt.Fprintln(out, "No Cursor usage collected yet.")+ return nil+ }+ for _, s := range report.Scopes {+ fmt.Fprintf(out, " %s collected %s .. %s last sync %s\n", s.Scope, cursorUsageOrDash(s.CoveredFrom), cursorUsageOrDash(s.CollectedTo), cursorUsageOrDash(s.LastSync))+ }+ return nil+}++func cursorUsageTime(ms int64) string {+ if ms <= 0 {+ return ""+ }+ return time.UnixMilli(ms).UTC().Format(time.RFC3339)+}++func cursorUsageOrDash(s string) string {+ if s == "" {+ return "-"+ }+ return s+}diff --git a/cli/beacon/cmd/endpoint_cursor_usage_test.go b/cli/beacon/cmd/endpoint_cursor_usage_test.gonew file mode 100644index 00000000..41d283f1--- /dev/null+++ b/cli/beacon/cmd/endpoint_cursor_usage_test.go@@ -0,0 +1,411 @@+package cmd++import (+ "bufio"+ "bytes"+ "database/sql"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/spf13/cobra"+ "github.com/spf13/pflag"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// testCursorAdminKey is distinctive so a test can prove it never lands in any output or file.+const testCursorAdminKey = "key_beacon_test_7f3a9c1e5b"++var cursorUsageTestNow = time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)++// fakeCursorAdminAPI serves /teams/filtered-usage-events from a fixed list, honoring the window.+type fakeCursorAdminAPI struct {+ mu sync.Mutex+ events []map[string]any+ requests []map[string]any+ auth []string+}++func (f *fakeCursorAdminAPI) handler(t *testing.T) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/teams/filtered-usage-events" || r.Method != http.MethodPost {+ http.NotFound(w, r)+ return+ }+ user, _, _ := r.BasicAuth()+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("bad request body: %v", err)+ }+ f.mu.Lock()+ f.requests = append(f.requests, body)+ f.auth = append(f.auth, user)+ start, _ := body["startDate"].(float64)+ end, _ := body["endDate"].(float64)+ var page []map[string]any+ for _, ev := range f.events {+ ts := ev["timestamp"].(int64)+ if float64(ts) >= start && float64(ts) <= end {+ page = append(page, ev)+ }+ }+ f.mu.Unlock()+ _ = json.NewEncoder(w).Encode(map[string]any{+ "totalUsageEventsCount": len(page),+ "pagination": map[string]any{"hasNextPage": false},+ "usageEventsDisplay": page,+ })+ })+}++type cursorUsageFixture struct {+ api *fakeCursorAdminAPI+ url string+ root string+ state string+ log string+ globalDB string+}++func newCursorUsageFixture(t *testing.T, signedInEmail string) *cursorUsageFixture {+ t.Helper()+ root := t.TempDir()+ testenv.SetHome(t, root)+ f := &cursorUsageFixture{+ api: &fakeCursorAdminAPI{},+ root: root,+ state: filepath.Join(root, "state", "cursor-usage.json"),+ log: filepath.Join(root, "logs", "runtime.jsonl"),+ globalDB: filepath.Join(root, "state.vscdb"),+ }+ f.api.events = []map[string]any{+ cursorAdminEvent(cursorUsageTestNow.Add(-2*time.Hour), 1000, 4.5),+ cursorAdminEvent(cursorUsageTestNow.Add(-time.Hour), 2000, 0),+ }+ srv := httptest.NewServer(f.api.handler(t))+ t.Cleanup(srv.Close)+ f.url = srv.URL++ db, err := sql.Open("sqlite", f.globalDB)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)`); err != nil {+ t.Fatal(err)+ }+ if signedInEmail != "" {+ if _, err := db.Exec(`INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/cachedEmail', ?)`, signedInEmail); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := db.Exec(`INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', 'cursor-session-token')`); err != nil {+ t.Fatal(err)+ }+ db.Close()++ t.Setenv(defaultCursorAdminKeyEnv, testCursorAdminKey)+ previousNow := cursorUsageNow+ cursorUsageNow = func() time.Time { return cursorUsageTestNow }+ t.Cleanup(func() { cursorUsageNow = previousNow })+ return f+}++func cursorAdminEvent(ts time.Time, input int, chargedCents float64) map[string]any {+ return map[string]any{+ "timestamp": ts.UnixMilli(),+ "model": "claude-4.5-sonnet",+ "kind": "USAGE_EVENT_KIND_USAGE_BASED",+ "isTokenBasedCall": true,+ "tokenUsage": map[string]any{+ "inputTokens": input, "outputTokens": 50, "cacheReadTokens": 300, "cacheWriteTokens": 7, "totalCents": 1.25,+ },+ "chargedCents": chargedCents,+ "userEmail": "[email protected]",+ "userId": 42,+ }+}++// run executes `beacon endpoint cursor usage <args>` through the real command tree, with every flag+// in the subtree reset first because this CLI keeps flag values in package variables.+func (f *cursorUsageFixture) run(t *testing.T, args ...string) (string, error) {+ t.Helper()+ var reset func(*cobra.Command)+ reset = func(c *cobra.Command) {+ c.Flags().VisitAll(func(fl *pflag.Flag) {+ _ = fl.Value.Set(fl.DefValue)+ fl.Changed = false+ })+ for _, sub := range c.Commands() {+ reset(sub)+ }+ }+ reset(endpointCursorUsageCmd)+ var stdout, stderr bytes.Buffer+ rootCmd.SetOut(&stdout)+ rootCmd.SetErr(&stderr)+ full := append([]string{"endpoint", "cursor", "usage"}, args...)+ if len(args) > 0 && (args[0] == "sync" || args[0] == "status") {+ full = append(full, "--state", f.state, "--global-db", f.globalDB)+ if args[0] == "sync" {+ full = append(full, "--log-path", f.log, "--base-url", f.url)+ }+ }+ rootCmd.SetArgs(full)+ t.Cleanup(func() {+ rootCmd.SetOut(nil)+ rootCmd.SetErr(nil)+ rootCmd.SetArgs(nil)+ })+ err := rootCmd.Execute()+ out := stdout.String() + stderr.String()+ if strings.Contains(out, testCursorAdminKey) {+ t.Fatalf("command output contains the admin key:\n%s", out)+ }+ if err != nil && strings.Contains(err.Error(), testCursorAdminKey) {+ t.Fatalf("error contains the admin key: %v", err)+ }+ return stdout.String(), err+}++func (f *cursorUsageFixture) logged(t *testing.T) []schema.Event {+ t.Helper()+ file, err := os.Open(f.log)+ if os.IsNotExist(err) {+ return nil+ }+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ var out []schema.Event+ scanner := bufio.NewScanner(file)+ for scanner.Scan() {+ var ev schema.Event+ if err := json.Unmarshal(scanner.Bytes(), &ev); err != nil {+ t.Fatal(err)+ }+ out = append(out, ev)+ }+ return out+}++// assertKeyNowhereOnDisk walks everything the command could have written.+func (f *cursorUsageFixture) assertKeyNowhereOnDisk(t *testing.T) {+ t.Helper()+ _ = filepath.Walk(f.root, func(path string, info os.FileInfo, err error) error {+ if err != nil || info.IsDir() {+ return nil+ }+ data, readErr := os.ReadFile(path)+ if readErr == nil && bytes.Contains(data, []byte(testCursorAdminKey)) {+ t.Errorf("%s contains the admin key", path)+ }+ return nil+ })+}++func TestCursorUsageSyncWritesTokenUsageForTheSignedInAccount(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ out, err := f.run(t, "sync")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(out, "cursor usage sync (email:[email protected]): 2 fetched, 2 written") {+ t.Fatalf("output = %q", out)+ }+ if len(f.api.requests) != 1 {+ t.Fatalf("requests = %d", len(f.api.requests))+ }+ if f.api.requests[0]["email"] != "[email protected]" {+ t.Fatalf("the default scope must be the signed-in account: %v", f.api.requests[0])+ }+ if f.api.auth[0] != testCursorAdminKey {+ t.Fatalf("basic auth user = %q", f.api.auth[0])+ }++ events := f.logged(t)+ if len(events) != 2 {+ t.Fatalf("logged %d events", len(events))+ }+ for _, ev := range events {+ if ev.Event.Action != "token.usage" || ev.Harness.Name != "cursor" || ev.Harness.CollectionMethod != schema.CollectionMethodPoll {+ t.Fatalf("event = %+v %+v", ev.Event, ev.Harness)+ }+ }+ if *events[0].GenAI.Usage.InputTokens != 1000 || *events[0].GenAI.Usage.CostUSD != 0.045 {+ t.Fatalf("usage = %+v", events[0].GenAI.Usage)+ }++ // A second run writes nothing new.+ out, err = f.run(t, "sync")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(out, "0 written, 2 already collected") || len(f.logged(t)) != 2 {+ t.Fatalf("repeat sync: %q", out)+ }+ f.assertKeyNowhereOnDisk(t)+}++func TestCursorUsageSyncRequiresTheKeyInTheEnvironment(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ t.Setenv(defaultCursorAdminKeyEnv, "")+ _, err := f.run(t, "sync")+ if err == nil || !strings.Contains(err.Error(), "set CURSOR_ADMIN_API_KEY") {+ t.Fatalf("err = %v", err)+ }+ if len(f.api.requests) != 0 {+ t.Fatal("a request was made without a key")+ }+}++func TestCursorUsageSyncReadsACustomKeyVariable(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ t.Setenv(defaultCursorAdminKeyEnv, "")+ t.Setenv("ACME_CURSOR_KEY", testCursorAdminKey)+ if _, err := f.run(t, "sync", "--api-key-env", "ACME_CURSOR_KEY"); err != nil {+ t.Fatal(err)+ }+ if len(f.api.auth) != 1 || f.api.auth[0] != testCursorAdminKey {+ t.Fatalf("auth = %v", f.api.auth)+ }+}++func TestCursorUsageSyncWithoutASignedInAccountAsksWhoseUsage(t *testing.T) {+ f := newCursorUsageFixture(t, "")+ _, err := f.run(t, "sync")+ if err == nil || !strings.Contains(err.Error(), "--team") {+ t.Fatalf("err = %v", err)+ }+ if len(f.api.requests) != 0 {+ t.Fatal("collected without a scope")+ }+}++func TestCursorUsageSyncScopes(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ if _, err := f.run(t, "sync", "--team"); err != nil {+ t.Fatal(err)+ }+ if _, ok := f.api.requests[0]["email"]; ok {+ t.Fatalf("--team must not filter by email: %v", f.api.requests[0])+ }+ if _, err := f.run(t, "sync", "--user-id", "42"); err != nil {+ t.Fatal(err)+ }+ if f.api.requests[1]["userId"] != float64(42) {+ t.Fatalf("--user-id body = %v", f.api.requests[1])+ }+ if _, err := f.run(t, "sync", "--email", "[email protected]"); err != nil {+ t.Fatal(err)+ }+ if f.api.requests[2]["email"] != "[email protected]" {+ t.Fatalf("--email body = %v", f.api.requests[2])+ }+ if _, err := f.run(t, "sync", "--team", "--email", "[email protected]"); err == nil || !strings.Contains(err.Error(), "choose one") {+ t.Fatalf("conflicting scopes err = %v", err)+ }+ if _, err := f.run(t, "sync", "--user-id", "abc"); err == nil || !strings.Contains(err.Error(), "numeric") {+ t.Fatalf("non-numeric user id err = %v", err)+ }+}++func TestCursorUsageSyncPrintIsADryRun(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ out, err := f.run(t, "sync", "--print")+ if err != nil {+ t.Fatal(err)+ }+ if lines := strings.Count(strings.TrimSpace(out), "\n") + 1; lines != 2 || !strings.Contains(out, `"token.usage"`) {+ t.Fatalf("print output = %q", out)+ }+ if len(f.logged(t)) != 0 {+ t.Fatal("--print wrote the log")+ }+ if _, err := os.Stat(f.state); !os.IsNotExist(err) {+ t.Fatal("--print wrote state")+ }+}++func TestCursorUsageSyncJSONAndSince(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ f.api.events = append(f.api.events, cursorAdminEvent(cursorUsageTestNow.Add(-20*24*time.Hour), 5, 1))+ out, err := f.run(t, "sync", "--json", "--since", "2026-09-01")+ if err != nil {+ t.Fatal(err)+ }+ var summary struct {+ Emitted int `json:"emitted"`+ WindowStart string `json:"window_start"`+ }+ if err := json.Unmarshal([]byte(out), &summary); err != nil {+ t.Fatalf("json output %q: %v", out, err)+ }+ if summary.Emitted != 3 {+ t.Fatalf("summary = %+v", summary)+ }+ if _, err := f.run(t, "sync", "--since", "last tuesday"); err == nil || !strings.Contains(err.Error(), "--since") {+ t.Fatalf("bad since err = %v", err)+ }+}++func TestCursorUsageSyncRefusesPlainHTTPToARemoteHost(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ f.url = "http://api.cursor.com"+ if _, err := f.run(t, "sync"); err == nil || !strings.Contains(err.Error(), "https") {+ t.Fatalf("err = %v", err)+ }+}++func TestCursorUsageStatus(t *testing.T) {+ f := newCursorUsageFixture(t, "[email protected]")+ out, err := f.run(t, "status")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(out, "CURSOR_ADMIN_API_KEY is set") || !strings.Contains(out, "Scope: email:[email protected]") || !strings.Contains(out, "No Cursor usage collected yet") {+ t.Fatalf("status = %q", out)+ }+ if _, err := f.run(t, "sync"); err != nil {+ t.Fatal(err)+ }+ t.Setenv(defaultCursorAdminKeyEnv, "")+ out, err = f.run(t, "status", "--json")+ if err != nil {+ t.Fatal(err)+ }+ var report cursorUsageStatusReport+ if err := json.Unmarshal([]byte(out), &report); err != nil {+ t.Fatal(err)+ }+ if report.APIKeySet || report.DefaultScope != "email:[email protected]" || len(report.Scopes) != 1 {+ t.Fatalf("report = %+v", report)+ }+ if report.Scopes[0].CollectedTo != cursorUsageTestNow.Format(time.RFC3339) {+ t.Fatalf("collected_to = %q", report.Scopes[0].CollectedTo)+ }+ // The signed-in lookup reads the email row only; the access token in the same table never+ // reaches any output.+ if strings.Contains(out, "cursor-session-token") {+ t.Fatal("status leaked Cursor's access token")+ }+}++func TestCursorUsageStatusWithoutAScope(t *testing.T) {+ f := newCursorUsageFixture(t, "")+ out, err := f.run(t, "status")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(out, "Scope: none") {+ t.Fatalf("status = %q", out)+ }+}diff --git a/cli/beacon/internal/cursorsession/account.go b/cli/beacon/internal/cursorsession/account.gonew file mode 100644index 00000000..f677fdf8--- /dev/null+++ b/cli/beacon/internal/cursorsession/account.go@@ -0,0 +1,56 @@+package cursorsession++import (+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+)++// cachedEmailKey is the ItemTable row where Cursor keeps the email of the account signed in to+// this install. The same table holds Cursor's access and refresh tokens under neighbouring+// cursorAuth/ keys; this reads exactly one key by equality and nothing else, so no credential is+// ever loaded.+const cachedEmailKey = "cursorAuth/cachedEmail"++// CachedAccountEmail returns the email of the Cursor account signed in on this machine, read from+// Cursor's global state.vscdb. It returns "" with no error when the database or the row does not+// exist, which is what a machine without Cursor or with Cursor signed out looks like.+func CachedAccountEmail(globalDBPath string) (string, error) {+ if strings.TrimSpace(globalDBPath) == "" {+ globalDBPath = DefaultGlobalDBPath()+ }+ if !fileExists(globalDBPath) {+ return "", nil+ }+ db, err := openSQLiteReadOnly(globalDBPath)+ if err != nil {+ return "", fmt.Errorf("open Cursor global storage: %w", err)+ }+ defer db.Close()++ var value []byte+ err = db.QueryRow(`SELECT value FROM ItemTable WHERE key = ?`, cachedEmailKey).Scan(&value)+ if errors.Is(err, sql.ErrNoRows) {+ return "", nil+ }+ if err != nil {+ if strings.Contains(err.Error(), "no such table") {+ return "", nil+ }+ return "", fmt.Errorf("read Cursor account email: %w", err)+ }+ email := strings.TrimSpace(string(value))+ // Some VS Code storage writers JSON-encode string values.+ if strings.HasPrefix(email, `"`) {+ var decoded string+ if json.Unmarshal([]byte(email), &decoded) == nil {+ email = strings.TrimSpace(decoded)+ }+ }+ if !strings.Contains(email, "@") || strings.ContainsAny(email, " \t\r\n") {+ return "", nil+ }+ return email, nil+}diff --git a/cli/beacon/internal/cursorsession/account_test.go b/cli/beacon/internal/cursorsession/account_test.gonew file mode 100644index 00000000..4b26c58d--- /dev/null+++ b/cli/beacon/internal/cursorsession/account_test.go@@ -0,0 +1,74 @@+package cursorsession++import (+ "database/sql"+ "path/filepath"+ "testing"+)++func writeItemTable(t *testing.T, rows map[string]string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "state.vscdb")+ db, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ defer db.Close()+ if _, err := db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)`); err != nil {+ t.Fatal(err)+ }+ for k, v := range rows {+ if _, err := db.Exec(`INSERT INTO ItemTable (key, value) VALUES (?, ?)`, k, v); err != nil {+ t.Fatal(err)+ }+ }+ return path+}++func TestCachedAccountEmail(t *testing.T) {+ path := writeItemTable(t, map[string]string{+ "cursorAuth/cachedEmail": " [email protected] ",+ "cursorAuth/accessToken": "secret-token",+ })+ got, err := CachedAccountEmail(path)+ if err != nil || got != "[email protected]" {+ t.Fatalf("got %q, %v", got, err)+ }+}++func TestCachedAccountEmailJSONEncoded(t *testing.T) {+ path := writeItemTable(t, map[string]string{"cursorAuth/cachedEmail": `"[email protected]"`})+ if got, _ := CachedAccountEmail(path); got != "[email protected]" {+ t.Fatalf("got %q", got)+ }+}++func TestCachedAccountEmailAbsentOrInvalid(t *testing.T) {+ cases := map[string]string{+ "missing db": filepath.Join(t.TempDir(), "nope.vscdb"),+ "no row": writeItemTable(t, map[string]string{"cursorAuth/accessToken": "x"}),+ "not an email": writeItemTable(t, map[string]string{"cursorAuth/cachedEmail": "signed out"}),+ "empty": writeItemTable(t, map[string]string{"cursorAuth/cachedEmail": ""}),+ }+ for name, path := range cases {+ got, err := CachedAccountEmail(path)+ if err != nil || got != "" {+ t.Errorf("%s: got %q, %v", name, got, err)+ }+ }+}++func TestCachedAccountEmailWithoutItemTable(t *testing.T) {+ path := filepath.Join(t.TempDir(), "state.vscdb")+ db, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := db.Exec(`CREATE TABLE cursorDiskKV (key TEXT, value BLOB)`); err != nil {+ t.Fatal(err)+ }+ db.Close()+ if got, err := CachedAccountEmail(path); err != nil || got != "" {+ t.Fatalf("got %q, %v", got, err)+ }+}