Files
magpie/internal/provider/cursor_usage.go
T
yetone cb7f442785 gateway: Codex's /models builds magpie's providers once, and cursor-agent's Keychain token is read once a while (#746, sperwe: /backend-api/codex/models called All() over and over, rescanning accounts and running /usr/bin/security some 200 times, 5.3–5.6 s against about 1 s straight to the backend, past Codex's 5 s model refresh, so Codex fell back to the official list) — after the ChatGPT backend's list, codexModels read magpie's: CodexListed (CatalogFor's catalog, and AutoVision through codexListed's descriptions), CodexNativeWindow, CodexNativePicked and CodexListTag (CodexListed again, codexWindowsTag), seven builds of All() in a test with one provider, each going through Accounts() and every agent's sign-in; a plugin's accounts ask pluginOwnUser, and for a Cursor moved onto its plugin that is cursorSignedOut, a security find-generic-password each time. All() now goes through the hold the GUI's reads use (heldOf, dff14ff4): while a request holds the catalog it is built once (a clone each call, so a caller's change stays its own; resolveIn's own heldOf("all", All) is plain All() now), and codexModels takes the hold (provider.Hold) for what follows the backend's answer. A hold is dropped by a write, as before (store → catalog.Touched → Changed, a plugin's sign-in), and now also by writeLogins and forgetAccountCaches, so an account signed in, switched or removed while one is held is seen at once; a sign-in changed outside magpie shows within the hold's second (heldFor). cursor-agent's Keychain token (readCursorToken, cursorToken) is read at most once in 10 s (cursorTokenTTL, as claudeCacheTTL); forgetCursorStatus, which a sign-in or out in magpie calls, drops it, and CursorToken reads it afresh after asking cursor-agent to renew it, so a renewed or new token isn't missed. AllBuilt counts builds for tests. TestCodexModelListBuildsProvidersOnce counts one build for one /models request (7 on the old code), TestHoldBuildsProvidersOnce one build for two All() calls under a hold, a caller's change not leaking, a provider saved and logins written while held being seen, and TestCursorKeychainReadOnce, with a fake security on PATH, one run for three reads, a fresh one after forgetCursorStatus and after a fresh read. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not timed with the reporter's accounts: here the request built the providers 7 times and builds them once, so their ~200 security runs should come to about a seventh, Cursor's from one a build to one in 10 s; the GUI's held reads (GET /api/*) now share one All() too.
2026-10-04 12:15:40 +08:00

176 lines
5.8 KiB
Go

package provider
// PLUGIN-SERVED (see AGENTS.md): Cursor ("cursor") is a deprecated built-in
// subscription served by its plugin, @magpie-community/opencode-cursor-auth,
// once moved onto it (provider.Moved; the default for a new sign-in). A
// moved one's sign-ins, models, requests and usage are all the plugin's,
// never this code's (only the move, in migrate*.go, still reads its
// accounts). A fix here alone doesn't reach those users; fix the plugin
// (github.com/magpie-community/plugins, packages/cursor) and raise the
// mover's min in internal/provider/migrate_side.go.
// How much of a Cursor plan's included usage is gone, as the CLI's own
// usage view reads it: the dashboard's current period, split into the
// Cursor Models and Other Models pools.
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
)
// cursorBase is Cursor's API; a var so tests can point it elsewhere.
var cursorBase = "https://api2.cursor.sh"
// cursorKeychain reads cursor-agent's token from the macOS Keychain; a var
// so tests stay off the real one.
var cursorKeychain = runtime.GOOS == "darwin"
// cursorToken is the access token cursor-agent signed in with: in the
// Keychain on a Mac, in its auth.json elsewhere.
func cursorToken() (string, error) {
if cursorKeychain {
if tok := cursorKeychainToken(false); tok != "" {
return tok, nil
}
}
var auth struct {
AccessToken string `json:"accessToken"`
}
if path := cursorAuthPath(); path != "" && readJSON(path, &auth) && auth.AccessToken != "" {
return auth.AccessToken, nil
}
return "", errorf("cursor-agent is not signed in")
}
// cursorAuthPath is where cursor-agent keeps its sign-in outside the Keychain.
func cursorAuthPath() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
switch runtime.GOOS {
case "windows":
dir := os.Getenv("APPDATA")
if dir == "" {
dir = filepath.Join(home, "AppData", "Roaming")
}
return filepath.Join(dir, "Cursor", "auth.json")
case "darwin":
return filepath.Join(home, ".cursor", "auth.json")
}
dir := os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
dir = filepath.Join(home, ".config")
}
return filepath.Join(dir, "cursor", "auth.json")
}
func cursorSubscriptionUsage(ctx context.Context, plan string) SubscriptionQuota {
q := SubscriptionQuota{Provider: "cursor", Name: "Cursor", Icon: "cursor", Plan: plan, Windows: []QuotaWindow{}}
tok, err := cursorToken()
if err == nil {
q.Windows, err = cursorWindows(ctx, tok)
}
if err != nil {
q.Error = err.Error()
}
return q
}
// cursorWindows: the plan's included usage this billing period. An
// enterprise plan reports spend instead, and gets no windows.
func cursorWindows(ctx context.Context, token string) ([]QuotaWindow, error) {
var data struct {
BillingCycleEnd string `json:"billingCycleEnd"` // epoch millis
AutoBucketModels []string `json:"autoBucketModels"`
PlanUsage *struct {
Auto float64 `json:"autoPercentUsed"`
API float64 `json:"apiPercentUsed"`
Total float64 `json:"totalPercentUsed"`
} `json:"planUsage"`
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cursorBase+"/aiserver.v1.DashboardService/GetCurrentPeriodUsage", bytes.NewReader([]byte("{}")))
if err != nil {
return []QuotaWindow{}, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Connect-Protocol-Version", "1")
res, err := http.DefaultClient.Do(req)
if err != nil {
return []QuotaWindow{}, err
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if res.StatusCode < 200 || res.StatusCode >= 300 {
return []QuotaWindow{}, &accountStatusError{status: res.StatusCode}
}
if err := json.Unmarshal(b, &data); err != nil {
return []QuotaWindow{}, err
}
if data.PlanUsage == nil {
return []QuotaWindow{}, nil
}
var resets *time.Time
if ms, err := strconv.ParseInt(data.BillingCycleEnd, 10, 64); err == nil && ms > 0 {
t := time.UnixMilli(ms)
resets = &t
}
u := data.PlanUsage
inCursorPool := func(model string) bool {
model = cursorPoolBase(model)
if model == "auto" {
model = "default" // the CLI's Auto is default in Cursor's API
}
// the server names a family (grok-4.8); the CLI asks for one at an
// effort or speed (grok-4.8-high-fast)
return slices.ContainsFunc(data.AutoBucketModels, func(m string) bool { return cursorPoolBase(m) == model }) || cursorFirstPartyModel(model)
}
// the two pools fit the line; the total goes in its tooltip
return []QuotaWindow{
{Name: "Cursor Models", Used: u.Auto, ResetsAt: resets, matches: inCursorPool},
{Name: "Other Models", Used: u.API, ResetsAt: resets, matches: func(model string) bool { return !inCursorPool(model) }},
{Name: "Total", Used: u.Total, ResetsAt: resets, Aside: true},
}, nil
}
// cursorPoolBase names a model's family: lower case, without cursor- and
// the effort and speed the CLI adds to it.
func cursorPoolBase(model string) string {
model = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "cursor-")
for {
b := cursorVariant.ReplaceAllString(model, "")
if b == model {
return model
}
model = b
}
}
// Cursor's autoBucketModels can lag model releases: it still omitted Grok
// 4.6/4.7 when the published Cursor Models pool already included them.
// Keep those documented families alongside the server's exact model list.
// See https://cursor.com/docs/models-and-pricing.
func cursorFirstPartyModel(model string) bool {
model = strings.TrimPrefix(model, "cursor-")
if model == "default" || model == "composer" || strings.HasPrefix(model, "composer-") {
return true
}
for _, base := range []string{"grok-4.5", "grok-4.6", "grok-4.7"} {
if model == base || strings.HasPrefix(model, base+"-") {
return true
}
}
return false
}