diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 48e7eec9f..d322d5c05 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -126,7 +126,7 @@ A signed-in account's model list exists only at its vendor (the ChatGPT backend' 1. **Add.** The Providers page adds a key provider through `Add` or `Save`, or an account through `StartSignIn`. An agent signed in on its own is found by `Accounts` with no step from the user. 2. **Resolve.** The gateway calls `provider.Resolve` or `GroupFor` with the model name, then plans candidates over the provider's keys or accounts. 3. **Sign.** For each try, `Sign` gives the request its auth. A token about to expire is refreshed first, and the rotated tokens go back to their one holder: the agent's store, or `logins.json` for an account standing behind it. -4. **Allowance.** Usage endpoints are rate limited, so `SubscriptionUsage` caches its results: a cached copy comes back at once and a stale one is refreshed in the background. When an account's windows start again, `OnRenewed` tells the gateway so a resting account can come back: a Codex reset spent (`renewedNow`), or a reading routing takes (`Allowances`, as the agent the account's usage is read under, `claude` or `plugin:`) that finds the account full till sooner than the last did (`renewedFrom`, the rule a key's reading goes by): the whole account, or a pool of some models with the whole account's windows over it. A window used below `SpentShareOf` its routing, or whose reset passed, is full no more; one full with its reset not known is full for good. A Claude account is back as soon as a new `/usage` or the reset passing shows the window it was out of started again, not when the time Claude Code's refusal named comes; its five hours started again in a week used up tells nothing. A first reading, a failed one, one read alike, or one leaving the full window out tells nothing, and a reset spent is told once, by `renewedNow`. A key's reading that finds a window it was full in (at `SpentShareOf` its routing) full no more, or full till sooner, tells it too, as agent `""` and the key's `KeyAllowanceID`, so a key out of its limit is back once the limit is raised or its usage reset; a first reading, a failed one, or one that finds it fuller tells nothing. An account refused for its quota has its agent's allowances read again at the next ask (`StaleAllowance`). A reading already out then was asked before the refusal: what it read is kept, as not read, so the ask after it lands reads again, as `StaleKeyAllowance` does for a key. Built-in Grok's own per-account cache (`grokLoginUsage`) doesn't keep such a reading at all: it goes to its caller only, so that next ask reaches xAI. +4. **Allowance.** Usage endpoints are rate limited, so `SubscriptionUsage` caches its results: a cached copy comes back at once and a stale one is refreshed in the background. When an account's windows start again, `OnRenewed` tells the gateway so a resting account can come back: a Codex reset spent (`renewedNow`), or a reading routing takes (`Allowances`, as the agent the account's usage is read under, `claude` or `plugin:`) that finds the account full till sooner than the last did (`renewedFrom`, the rule a key's reading goes by): the whole account, or a pool of some models with the whole account's windows over it. A window used below `SpentShareOf` its routing, or whose reset passed, is full no more; one full with its reset not known is full for good. A Claude account is back as soon as a new `/usage` or the reset passing shows the window it was out of started again, not when the time Claude Code's refusal named comes; its five hours started again in a week used up tells nothing. A first reading, a failed one, one read alike, or one leaving the full window out tells nothing, and a reset spent is told once, by `renewedNow`. A key's reading that finds a window it was full in (at `SpentShareOf` its routing) full no more, or full till sooner, tells it too, as agent `""` and the key's `KeyAllowanceID`, so a key out of its limit is back once the limit is raised or its usage reset; a first reading, a failed one, or one that finds it fuller tells nothing. An account refused for its quota has its agent's allowances read again at the next ask (`StaleAllowance`). A reading already out then was asked before the refusal: what it read is kept, as not read, so the ask after it lands reads again, as `StaleKeyAllowance` does for a key. A provider's fetched model list keeps the upstream ids and order. Display names prefer `magpie_label`, then `display_name`, then a `name` without a diff --git a/internal/agent/grok_test.go b/internal/agent/grok_test.go index 5846ee004..8d32cb122 100644 --- a/internal/agent/grok_test.go +++ b/internal/agent/grok_test.go @@ -1,6 +1,7 @@ package agent import ( + "encoding/json" "os" "path/filepath" "slices" @@ -8,7 +9,9 @@ import ( "testing" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) func TestGrok(t *testing.T) { @@ -208,6 +211,23 @@ func TestGrokFoldsItsOwnAccount(t *testing.T) { t.Cleanup(provider.ForgetAccounts) os.MkdirAll(filepath.Join(home, "grok"), 0o755) os.WriteFile(filepath.Join(home, "grok", "auth.json"), []byte(`{"x":{"key":"k","email":"me@x.ai"}}`), 0o600) + // the Grok plugin serves the account, taken from Grok Build's own + spec := "@magpie-community/opencode-grok-auth" + write := func(name string, v any) { + t.Helper() + b, _ := json.Marshal(v) + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil { + t.Fatal(err) + } + } + write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": spec}}}) + write("plugin-auth.json", map[string]map[string]any{"grok": {"type": "oauth", "refresh": filepath.Join(home, "grok")}}) + plugin.UseCached([]plugin.Provider{{ID: "grok", Spec: spec, Name: "Grok", + Models: []plugin.Model{{ID: "grok-4.3", Name: "Grok 4.3"}}, Accounts: []plugin.Account{{Key: "grok", Type: "oauth"}}}}) + t.Cleanup(plugin.Settle) if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { t.Fatal(err) } diff --git a/internal/gateway/draw_test.go b/internal/gateway/draw_test.go index 5b206f0cb..fc29d8e9c 100644 --- a/internal/gateway/draw_test.go +++ b/internal/gateway/draw_test.go @@ -4,11 +4,12 @@ import ( "context" "encoding/base64" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" - "os" - "path/filepath" + "net/http/httputil" + "net/url" "slices" "strings" "sync" @@ -511,21 +512,31 @@ func TestCodexDrawMovesToNextAccount(t *testing.T) { } } -// grokSignedIn gives the test's HOME the Grok CLI's sign-in, and a CLI to find. +// grokSignedIn gives the test Grok served the way it is now that its built-in +// is retired: the fake plugin moved onto "grok", its requests sent on to +// provider.GrokBase as it is when each arrives, so a test points GrokBase at +// its upstream as it did for the built-in. func grokSignedIn(t *testing.T) { t.Helper() - home := t.TempDir() - t.Setenv("HOME", home) - t.Setenv("USERPROFILE", home) - t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) - t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) - t.Setenv("GROK_HOME", filepath.Join(home, ".grok")) - os.MkdirAll(filepath.Join(home, ".grok"), 0o755) - os.WriteFile(filepath.Join(home, ".grok", "auth.json"), mustJSON(map[string]any{ - "https://auth.x.ai": map[string]any{"key": "k-me", "email": "me@x.ai", "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339Nano)}}), 0o600) - was := provider.GrokExecutable - provider.GrokExecutable = func() string { return "/nonexistent/grok" } - t.Cleanup(func() { provider.GrokExecutable = was }) + t.Setenv("FAKE_RESPONSES", "1") + movedFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + to, err := url.Parse(provider.GrokBase + strings.TrimPrefix(r.URL.Path, "/v1")) + if err == nil && to.Hostname() != "127.0.0.1" { + err = fmt.Errorf("GrokBase %s isn't the test's: a test never reaches the network", provider.GrokBase) + } + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + to.RawQuery = r.URL.RawQuery + (&httputil.ReverseProxy{Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL, pr.Out.Host = to, to.Host + }}).ServeHTTP(w, r) + })) + // the vendor's own host was the built-in's, whose video it fetched from + // there; the plugin's host is the fake's, so the test's upstream on + // loopback is named as a user names a private host + allowPrivate(t, "127.0.0.1") } // A Grok subscription draws at the Imagine API of the backend Grok Build talks @@ -569,7 +580,9 @@ func TestGrokAccountDraws(t *testing.T) { !strings.Contains(bodies[0], `"response_format":"b64_json"`) || !strings.Contains(bodies[0], `"aspect_ratio":"16:9"`) || strings.Contains(bodies[0], `"size"`) { t.Fatalf("asked %v %v", paths, bodies) } - if head.Get("Authorization") != "Bearer k-me" || head.Get("x-grok-client-identifier") != "grok-shell" || !strings.HasPrefix(head.Get("User-Agent"), "grok-shell/") { + // the plugin signs the request (the fake with its own key); the real + // one's headers are the plugin's to test + if head.Get("Authorization") != "Bearer k1" { t.Fatalf("headers %v", head) } mu.Unlock() diff --git a/internal/gateway/grok_namespace.go b/internal/gateway/grok_namespace.go index 523a64fbb..f15a502ff 100644 --- a/internal/gateway/grok_namespace.go +++ b/internal/gateway/grok_namespace.go @@ -1,13 +1,14 @@ package gateway -// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-grok-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/grok) and raise the mover's -// min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-grok-auth (provider.BuiltinRetired). Its +// sign-in, models, requests and usage are the plugin's; what is left here +// reads the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and finds the Grok CLI the plugin signs in +// with, and shapes the plugin's request bodies (grokBody). A fix belongs in +// the plugin (github.com/magpie-community/plugins, packages/grok), with the +// mover's min raised in internal/provider/migrate_side.go. import ( "bytes" diff --git a/internal/gateway/key_models_test.go b/internal/gateway/key_models_test.go index cd40681fd..4afae64b4 100644 --- a/internal/gateway/key_models_test.go +++ b/internal/gateway/key_models_test.go @@ -402,15 +402,22 @@ func TestGatewayKeyModelsHoldTheImageAndVideoLists(t *testing.T) { func TestGatewayKeyAccountsHoldTheImageAndVideoLists(t *testing.T) { grokSignedIn(t) newGrokMedia(t) + // the plugin's one account, which grokSignedIn signs in, held to a + // chat model of its own + p, err := provider.Find("grok") + if err != nil || len(p.AccountRefs()) != 1 { + t.Fatalf("Grok's accounts: %v, %v", p.AccountRefs(), err) + } + ref := p.AccountRefs()[0] keys, secrets := newCaller(t, "Held", "Free") - if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"grok/me@x.ai"}}); err != nil { + if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"grok/" + ref}}); err != nil { t.Fatal(err) } - if err := provider.SetAccountModels("grok", "me@x.ai", []string{"grok-4"}); err != nil { + if err := provider.SetAccountModels("grok", ref, []string{"fake-1"}); err != nil { t.Fatal(err) } t.Cleanup(func() { - _ = provider.SetAccountModels("grok", "me@x.ai", nil) + _ = provider.SetAccountModels("grok", ref, nil) }) h := New().Handler() listed := func(secret string) (image, video []string) { diff --git a/internal/gateway/media_redact_test.go b/internal/gateway/media_redact_test.go index f80197417..06fce0a29 100644 --- a/internal/gateway/media_redact_test.go +++ b/internal/gateway/media_redact_test.go @@ -5,8 +5,10 @@ import ( "encoding/base64" "encoding/json" "io" + "maps" "mime/multipart" "net/http" + "net/http/httptest" "strings" "testing" @@ -229,6 +231,9 @@ func TestVideosRedacted(t *testing.T) { s := New() sent := make(chan mediaSent, 1) s.client = mediaEchoClient(t, sent, false) + if !remote { + grokEcho(t, s.client) + } ct, body, image := mediaInput(t, model, "input_reference", form) code, obj, raw, _ := request(t, s, "POST", "/v1/videos", ct, body) if code != 200 || obj["prompt"] != mediaPrompt { @@ -295,6 +300,9 @@ func TestMediaRedactedErrors(t *testing.T) { mediaRedactionOn(t) sent := make(chan mediaSent, 1) s.client = mediaEchoClient(t, sent, true) + if video { + grokEcho(t, s.client) + } ct, body, _ := mediaInput(t, model, "", false) code, obj, raw, _ := request(t, s, "POST", path, ct, body) if code != 400 || !strings.Contains(errorOf(obj), mediaPrompt) || strings.Contains(string(raw), "{{") { @@ -305,6 +313,28 @@ func TestMediaRedactedErrors(t *testing.T) { } } +// grokEcho points provider.GrokBase at a server that hands each request to +// c, as s.client took the retired built-in's: the Grok plugin (grokSignedIn) +// sends its requests through Bun, not through the gateway's client. +func grokEcho(t *testing.T, c *http.Client) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + res, err := c.Transport.RoundTrip(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer res.Body.Close() + maps.Copy(w.Header(), res.Header) + w.WriteHeader(res.StatusCode) + io.Copy(w, res.Body) + })) + t.Cleanup(srv.Close) + was := provider.GrokBase + provider.GrokBase = srv.URL + "/v1" + t.Cleanup(func() { provider.GrokBase = was }) +} + func TestGrokVideoPollRedacted(t *testing.T) { grokSignedIn(t) up := newGrokMedia(t) diff --git a/internal/gateway/plugin_grok_parity_test.go b/internal/gateway/plugin_grok_parity_test.go index cec39a4db..5abd0f1c5 100644 --- a/internal/gateway/plugin_grok_parity_test.go +++ b/internal/gateway/plugin_grok_parity_test.go @@ -172,15 +172,15 @@ func TestPluginBesideBuiltinCountsByEstimate(t *testing.T) { } } -// Grok's plugin beside the built-in Grok (grok-plugin) searches by itself -// as the built-in does, on Responses only. +// Grok's plugin searches by itself as the built-in did, on Responses only. +// With the built-in retired the plugin is "grok", not grok-plugin beside it. func TestGrokPluginSearchesItself(t *testing.T) { pid := besideFake(t, "grok", http.NotFoundHandler()) p, err := provider.Find(pid) if err != nil { t.Fatal(err) } - if pid != "grok-plugin" || !searchesItself(*p, provider.Responses) || searchesItself(*p, provider.Chat) { + if pid != "grok" || !searchesItself(*p, provider.Responses) || searchesItself(*p, provider.Chat) { t.Fatalf("%s searches by itself: %v on Responses, %v on Chat", pid, searchesItself(*p, provider.Responses), searchesItself(*p, provider.Chat)) } } diff --git a/internal/gateway/video_test.go b/internal/gateway/video_test.go index 8bbcfe1c4..528ea9d73 100644 --- a/internal/gateway/video_test.go +++ b/internal/gateway/video_test.go @@ -572,7 +572,7 @@ func TestVideoModelByItsBareName(t *testing.T) { for name, c := range map[string]struct { code int want string - }{"nothing": {404, "knows no model"}, "grok-4.7": {400, "can't make videos"}} { + }{"nothing": {404, "knows no model"}, "fake-1": {400, "can't make videos"}} { // fake-1: a chat model the (fake) Grok plugin lists code, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"prompt":"a kite","model":"`+name+`"}`) if code != c.code || !strings.Contains(errorOf(obj), c.want) { t.Errorf("%s: %d %s", name, code, raw) @@ -627,6 +627,7 @@ func TestVideoSecondsAndResolutionAsAsked(t *testing.T) { // user's settings.json "fetchPrivate" names it. func TestVideoContentAtPrivateAddressNotFetched(t *testing.T) { grokSignedIn(t) + allowPrivate(t) // grokSignedIn names loopback; here no private host is named inside, hits := secret(t, "secret-bytes") up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") diff --git a/internal/provider/account.go b/internal/provider/account.go index eb32e1e6a..c084cb87d 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -853,9 +853,6 @@ func Accounts() []Provider { if p, ok := copilotAccount(cfg); ok { out = append(out, p) } - if p, ok := grokAccount(); ok { - out = append(out, p) - } if p, ok := devinAccount(); ok { out = append(out, p) } diff --git a/internal/provider/grok.go b/internal/provider/grok.go index 7e531a9b4..1ab7843e2 100644 --- a/internal/provider/grok.go +++ b/internal/provider/grok.go @@ -1,13 +1,14 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-grok-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/grok) and raise the mover's -// min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-grok-auth (provider.BuiltinRetired). Its +// sign-in, models, requests and usage are the plugin's; what is left here +// reads the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and finds the Grok CLI the plugin signs in +// with, and shapes the plugin's request bodies (grokBody). A fix belongs in +// the plugin (github.com/magpie-community/plugins, packages/grok), with the +// mover's min raised in internal/provider/migrate_side.go. // A Grok subscription (SuperGrok, X Premium+) is served straight from the // backend xAI's Grok Build CLI talks to, OpenAI's Responses API at @@ -23,9 +24,7 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io" "maps" - "net/http" "os" "os/exec" "path/filepath" @@ -33,13 +32,11 @@ import ( "runtime" "slices" "sort" - "strconv" "strings" "sync" "time" "github.com/yetone/magpie/internal/appdir" - "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" ) @@ -159,62 +156,6 @@ func readGrokCredential(home string) (grokCredential, bool) { return grokCredential{}, false } -func grokAccount() (Provider, bool) { - if GrokExecutable() == "" { - return Provider{}, false - } - ls := grokLogins() - if len(ls) == 0 { - return Provider{}, false - } - home := ls[0].Home - acct := &Account{Agent: "grok", User: ls[0].User, Plan: ls[0].Plan, Home: home} - if home == GrokHome() { - acct.Home = "" // the CLI's own, wherever it is - } - grokSigned(acct, home) - acct.body = grokBody - acct.models = func() []catalog.Model { return []catalog.Model{{ID: "grok-4.7", Name: "Grok 4.7"}} } - acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { - ms, err := grokModels(ctx, acct.sign) - if err != nil { - return nil, err - } - return ms, catalog.SaveLive("grok", GrokBase, ms) - } - return Provider{ID: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Website: "https://x.ai/cli", Responses: GrokBase, Account: acct}, true -} - -// grokSigned has the account's requests signed with the sign-in in home. -func grokSigned(acct *Account, home string) { - acct.sign = func(ctx context.Context, req *http.Request, body []byte) error { - c, err := grokAccessToken(home, GrokExecutable(), false) - if err != nil { - return err - } - grokHeaders(req, c.Key) - if m, window := grokWindowed(bodyModel(body)); m != "" { - req.Header.Set("x-grok-model-override", m) - if window > 0 { - // grok-4.7@500k goes as grok-4.7 at that window, as the - // CLI's /context-window 500k sends it - req.Header.Set("x-grok-context-window", strconv.Itoa(window)) - nb := withModel(body, m) - req.Body = io.NopCloser(bytes.NewReader(nb)) - req.ContentLength = int64(len(nb)) - req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(nb)), nil } - } - } - var v struct { - Key string `json:"prompt_cache_key"` - } - if json.Unmarshal(body, &v) == nil && v.Key != "" { - req.Header.Set("x-grok-conv-id", v.Key) - } - return nil - } -} - // grokTools are the tool types Grok's backend takes; it turns the whole // request away over another, as over Codex's freeform apply_patch (custom) // or a namespace, which groups its sub-agent tools. A namespace's functions @@ -599,269 +540,6 @@ func flatCall(it map[string]any) bool { return true } -// grokHeaders say a request comes from the Grok CLI, which the backend -// wants to know the version of: without it the CLI is "outdated". -func grokHeaders(req *http.Request, token string) { - v := grokVersion() - req.Header.Set("Authorization", "Bearer "+token) - req.Header.Set("x-grok-client-version", v) - req.Header.Set("x-xai-token-auth", "xai-grok-cli") - req.Header.Set("x-grok-client-identifier", "grok-shell") - req.Header.Set("x-grok-client-mode", "headless") - goos, arch := runtime.GOOS, runtime.GOARCH - if goos == "darwin" { - goos = "macos" - } - switch arch { - case "arm64": - arch = "aarch64" - case "amd64": - arch = "x86_64" - } - req.Header.Set("User-Agent", "grok-shell/"+v+" ("+goos+"; "+arch+")") -} - -// grokClientVersion is the Grok CLI version magpie says it is, unless the -// installed one is newer. -const grokClientVersion = "1.0.41" - -var grokVersionCache struct { - sync.Mutex - v string - at time.Time -} - -var grokSemver = regexp.MustCompile(`\d+\.\d+\.\d+`) - -func grokVersion() string { - grokVersionCache.Lock() - defer grokVersionCache.Unlock() - if time.Since(grokVersionCache.at) < 10*time.Minute { - return grokVersionCache.v - } - v := grokClientVersion - if exe := GrokExecutable(); exe != "" { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - if out, err := proc.ProbeContext(ctx, exe, "--version").Output(); err == nil { // "grok 1.0.41 (4220f3b224a6)" - if c := grokSemver.FindString(string(out)); c != "" && compareClaudeVersion(c, v) > 0 { - v = c - } - } - cancel() - } - grokVersionCache.v, grokVersionCache.at = v, time.Now() - return v -} - -// grokModels lists what the account can use, with each model's context -// window and efforts, as the CLI's backend lists them. -func grokModels(ctx context.Context, sign func(context.Context, *http.Request, []byte) error) ([]catalog.Model, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, GrokBase+"/models", nil) - if err != nil { - return nil, err - } - if err := sign(ctx, req, nil); err != nil { - return nil, err - } - res, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) - if res.StatusCode != http.StatusOK { - return nil, errorf("Grok models: %s", APIError(b, res.Status)) - } - ms := parseGrokModels(b) - if len(ms) == 0 { - return nil, errorf("Grok listed no models") - } - return ms, nil -} - -func parseGrokModels(b []byte) []catalog.Model { - var v struct { - Data []struct { - ID string `json:"id"` - Name string `json:"name"` - Context int `json:"context_window"` - Windows []int `json:"context_windows"` - Backend string `json:"api_backend"` - Efforts []struct { - Value string `json:"value"` - } `json:"reasoning_efforts"` - } `json:"data"` - } - if json.Unmarshal(b, &v) != nil { - return nil - } - var ms []catalog.Model - for _, d := range v.Data { - if d.ID == "" || (d.Backend != "" && d.Backend != "responses") { - continue - } - m := catalog.Model{ID: d.ID, Name: d.Name, Context: d.Context, Images: true, APIs: []string{"responses"}} - if m.Name == "" { - m.Name = d.ID - } - // listed hardest first; kept easiest first, as the others are - for i := len(d.Efforts) - 1; i >= 0; i-- { - if e := d.Efforts[i].Value; e != "" { - m.Efforts = append(m.Efforts, e) - } - } - ms = append(ms, grokContextModels(m, d.Windows)...) - } - return ms -} - -// grokContextModels is one model for each context window Grok lists it at -// (#1608). context_window is the default and keeps the plain id -// (grok-4.7), so a saved agent stays where it was; each other size in -// context_windows is offered beside it (grok-4.7@500k), the way the CLI's -// /context-window offers it, and asked for with x-grok-context-window -// (grokWindowed). The same as the grok plugin's windowsOf (plugins#83). -func grokContextModels(m catalog.Model, listed []int) []catalog.Model { - var windows []int - for _, w := range listed { - if w > 0 && !slices.Contains(windows, w) { - windows = append(windows, w) - } - } - if len(windows) == 0 { - return []catalog.Model{m} - } - if !slices.Contains(windows, m.Context) { - m.Context = windows[0] - } - out := []catalog.Model{m} - for _, w := range windows { - if w == m.Context { - continue - } - at := grokWindowLabel(w) - o := m - o.ID, o.Name, o.Context = m.ID+"@"+at, m.Name+" @ "+at, w - o.Efforts = slices.Clone(m.Efforts) - o.APIs = slices.Clone(m.APIs) - out = append(out, o) - } - return out -} - -// grokWindowLabel is a window as an id names it: 500000 is "500k". -func grokWindowLabel(n int) string { - if n%1000 == 0 { - return strconv.Itoa(n/1000) + "k" - } - return strconv.Itoa(n) -} - -// grokWindowed splits a requested id into the model Grok lists and the -// window the id names: grok-4.7 is grok-4.7 at its default window (0, no -// header), grok-4.7@500k is grok-4.7 at 500000 tokens. A size no multiple -// of 1000 is the window itself, as grokWindowLabel writes it (131072). -func grokWindowed(id string) (string, int) { - model, size, ok := strings.Cut(id, "@") - if !ok { - return id, 0 - } - k, isK := strings.CutSuffix(size, "k") - n, err := strconv.Atoi(k) - if err != nil || n <= 0 || model == "" { - return id, 0 - } - if isK { - n *= 1000 - } - return model, n -} - -// grokRefreshMargin is how close to its expiry a borrowed token has the CLI -// refresh it first. -const grokRefreshMargin = 5 * time.Minute - -var grokRefresh sync.Mutex - -// grokAccessToken is the CLI's sign-in, with a token still good. One about -// to expire is first refreshed by the CLI in its own home: a `grok models` -// there renews it the way any use of the CLI does; so is one a run has -// found expired. -func grokAccessToken(home, binary string, expired bool) (grokCredential, error) { - c, ok := readGrokCredential(home) - if ok && (expired || time.Until(c.ExpiresAt) < grokRefreshMargin) && binary != "" { - grokRefresh.Lock() - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - cmd := proc.CommandContext(ctx, binary, "models") - cmd.Dir = filepath.Dir(home) - cmd.Env = netproxy.Env(grokOwnEnv(os.Environ(), home)) - _ = cmd.Run() - cancel() - grokRefresh.Unlock() - c, ok = readGrokCredential(home) - } - if !ok { - return c, errorf("Grok is not signed in; run `grok login`") - } - if !c.ExpiresAt.IsZero() && time.Until(c.ExpiresAt) <= 0 { - return c, errorf("Grok's sign-in has expired; run `grok login`") - } - return c, nil -} - -// grokOwnEnv runs the CLI as the user runs it, in its own home. -func grokOwnEnv(env []string, home string) []string { - out := make([]string, 0, len(env)+1) - for _, e := range env { - k, _, _ := strings.Cut(e, "=") - switch strings.ToUpper(k) { - case "GROK_HOME", "GROK_AUTH_PROVIDER_COMMAND", "GROK_AUTH_EXPIRED": - continue - } - out = append(out, e) - } - return append(out, "GROK_HOME="+home) -} - -// startGrokSignIn runs `grok login` with its device code, hands its link to -// the window, and finishes when the CLI says the account is in. With the -// CLI signed in already, a further account signs in in a home of magpie's, -// so the CLI's own sign-in stays as it is. -func startGrokSignIn(s *signInFlow) error { - path := GrokExecutable() - if path == "" { - c, _ := cliFor("grok") - manual := c.sh - if runtime.GOOS == "windows" { - manual = c.ps - } - return errorf("install Grok Build first: %s", manual) - } - if _, ok := readGrokCredential(GrokHome()); !ok { - return runCLISignIn(s, "grok login", nil, true, nil, func() (string, string, bool) { - c, ok := readGrokCredential(GrokHome()) - return c.Email, "", ok - }, nil, path, "login", "--device-auth") - } - home, err := newGrokHome() - if err != nil { - return err - } - err = runCLISignIn(s, "grok login", grokOwnEnv(os.Environ(), home), false, func() { removeGrokHome(home) }, func() (string, string, bool) { - user, err := addGrokLogin(home) - return user, "", err == nil - }, nil, path, "login", "--device-auth") - if err != nil { - removeGrokHome(home) - } - return err -} - -// agentCommand runs an agent's CLI with magpie's proxy. -func agentCommand(ctx context.Context, path string, args ...string) *exec.Cmd { - return withProxy(proc.CommandContext(ctx, path, args...)) -} - // agentProbe is agentCommand for asking the CLI something (proc.ProbeContext). func agentProbe(ctx context.Context, path string, args ...string) *exec.Cmd { return withProxy(proc.ProbeContext(ctx, path, args...)) diff --git a/internal/provider/grok_accounts.go b/internal/provider/grok_accounts.go index 49723f5ec..7522af588 100644 --- a/internal/provider/grok_accounts.go +++ b/internal/provider/grok_accounts.go @@ -1,13 +1,14 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-grok-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/grok) and raise the mover's -// min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-grok-auth (provider.BuiltinRetired). Its +// sign-in, models, requests and usage are the plugin's; what is left here +// reads the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and finds the Grok CLI the plugin signs in +// with, and shapes the plugin's request bodies (grokBody). A fix belongs in +// the plugin (github.com/magpie-community/plugins, packages/grok), with the +// mover's min raised in internal/provider/migrate_side.go. // Several Grok subscriptions. The Grok CLI keeps one account, in its own // home (~/.grok), which magpie only ever reads. Each further account gets a @@ -16,19 +17,6 @@ package provider // logins.json names those homes; the CLI's own account is remembered there // too, with no home, so it can stand behind another or be turned off. -import ( - "context" - "errors" - "os" - "path/filepath" - "strings" - "sync" - "time" -) - -// grokAccountsDir holds the homes of the Grok accounts magpie signed in. -func grokAccountsDir() string { return filepath.Join(filepath.Dir(Path()), "grok") } - // grokLogin is a Grok account and the home it is signed in in. type grokLogin struct { Login @@ -55,164 +43,3 @@ func grokLogins() []grokLogin { } return out } - -func grokSide() []sideLogin { - var out []sideLogin - for _, g := range grokLogins() { - out = append(out, sideLogin{Login: g.Login}) - } - return out -} - -// grokLoginList is the Grok accounts as Logins lists them. -func grokLoginList() []Login { return loginsOf(grokSide()) } - -// switchGrokLogin puts a Grok account first. The CLI's own sign-in stays -// as it is: magpie only changes which account its gateway uses first. -func switchGrokLogin(user string) error { return switchSideLogin("grok", user, grokSide()) } - -func setGrokLoginOn(user string, on bool) error { - return setSideLoginOn("grok", user, on, grokSide()) -} - -// forgetGrokLogin drops an account magpie signed in, with its home. The -// CLI's own is only hidden (forgetSideLogin). -func forgetGrokLogin(user string) error { - return forgetSideLogin("grok", user, grokSide(), - func(l savedLogin) { removeGrokHome(l.Home) }) -} - -// removeGrokHome deletes a home magpie made, and nothing else. -func removeGrokHome(home string) { - if rel, err := filepath.Rel(grokAccountsDir(), home); err == nil && rel != "." && !strings.HasPrefix(rel, "..") { - _ = os.RemoveAll(home) - } -} - -// newGrokHome makes the home a further Grok account is signed in in. -func newGrokHome() (string, error) { - home := filepath.Join(grokAccountsDir(), strings.ToLower(strings.NewReplacer("-", "", "_", "").Replace(randomToken(9)))) - return home, os.MkdirAll(home, 0o700) -} - -// addGrokLogin keeps the account just signed in in home, in use beside -// the others. Signed in again, an account keeps the newer home. -func addGrokLogin(home string) (string, error) { - c, ok := readGrokCredential(home) - if !ok || c.Email == "" { - removeGrokHome(home) - return "", errors.New("grok login finished without an account") - } - own, _ := readGrokCredential(GrokHome()) - return c.Email, addSideLogin(savedLogin{Agent: "grok", User: c.Email, Home: home}, own.Email, - func(l savedLogin) { removeGrokHome(l.Home) }) -} - -// grokAlsoOn is the Grok accounts in use behind the first. -func grokAlsoOn(p Provider) []Provider { - var out []Provider - for _, g := range grokLogins() { - if g.Active || !g.On { - continue - } - a := *p.Account - a.User, a.Plan, a.Home = g.User, g.Plan, g.Home - grokSigned(&a, g.Home) - q := p - q.Account = &a - out = append(out, q) - } - return out -} - -var grokHomeUsage struct { - sync.Mutex - m map[string]loginUsageEntry // home - pending map[string]uint64 // home: the reading out now - reads uint64 -} - -// grokLoginUsage is each Grok account's allowance, by user, as LoginUsage -// answers it. -func grokLoginUsage(ctx context.Context) map[string]SubscriptionQuota { - ctx, _ = quotaReading(ctx) // the page's read asks this account too: order the two - out := map[string]SubscriptionQuota{} - var mu sync.Mutex - var wg sync.WaitGroup - u := &grokHomeUsage - held := holding(ctx) - for _, g := range grokLogins() { - u.Lock() - e, ok := u.m[g.Home] - u.Unlock() - // with allowances read only when asked, what was read last, or - // kept on disk, unless the vendor just turned the account away - // (StaleAllowance) - gctx := ctx - if held && isStaleRead("grok/"+strings.ToLower(g.User)) { - gctx = unheld(ctx) - } else if held { - q := e.q - if !ok { - q = keepLast(SubscriptionQuota{Provider: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Windows: []QuotaWindow{}, Error: errNotAsked.Error()}, g.User) - } - mu.Lock() - out[g.User] = q - mu.Unlock() - continue - } - if ok && time.Since(e.at) < time.Minute && !held { - mu.Lock() - out[g.User] = e.q - mu.Unlock() - continue - } - u.Lock() - if u.pending == nil { - u.pending = map[string]uint64{} - } - u.reads++ - read := u.reads - u.pending[g.Home] = read - u.Unlock() - wg.Add(1) - takeStaleRead("grok/" + strings.ToLower(g.User)) - go func(g grokLogin) { - defer wg.Done() - q := keepReading(gctx, grokUsageAt(gctx, g.Home), g.User) - if q.Error != "" && ok { - q = e.q // a hiccup keeps what was known - } - u.Lock() - // one dropped meanwhile (StaleAllowance) was asked for too soon, - // and one a later reading took over from is older: either goes - // to its caller but isn't kept, as in loginReading - if u.pending[g.Home] == read { - delete(u.pending, g.Home) - if u.m == nil { - u.m = map[string]loginUsageEntry{} - } - u.m[g.Home] = loginUsageEntry{at: time.Now(), q: q} - } - u.Unlock() - mu.Lock() - out[g.User] = q - mu.Unlock() - }(g) - } - wg.Wait() - return out -} - -// grokUsageAt is the allowance of the account signed in in home. -func grokUsageAt(ctx context.Context, home string) SubscriptionQuota { - q := SubscriptionQuota{Provider: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Windows: []QuotaWindow{}} - c, err := grokAccessToken(home, GrokExecutable(), false) - if err == nil { - q.Windows, err = grokWindows(ctx, c.Key) - } - if err != nil { - q.Error = err.Error() - } - return q -} diff --git a/internal/provider/grok_accounts_test.go b/internal/provider/grok_accounts_test.go index 85e49c8ae..bb586c7ea 100644 --- a/internal/provider/grok_accounts_test.go +++ b/internal/provider/grok_accounts_test.go @@ -1,14 +1,10 @@ package provider import ( - "context" - "fmt" - "net/http" - "net/http/httptest" + "errors" "os" "path/filepath" - "sync" - "sync/atomic" + "strings" "testing" "time" ) @@ -20,264 +16,19 @@ func grokSignedIn(t *testing.T, home, email string) { }) } -// Grok has its own allowance cache, reached through the same public entry -// point. A cache hit after a fetch starts must share its result lock. -func TestLoginUsageGrokMixedCache(t *testing.T) { - home := signIn(t) - t.Setenv("GROK_HOME", filepath.Join(home, ".grok")) - grokSignedIn(t, GrokHome(), "me@x.ai") - extra, err := newGrokHome() - if err != nil { - t.Fatal(err) - } - grokSignedIn(t, extra, "two@x.ai") - if _, err := addGrokLogin(extra); err != nil { - t.Fatal(err) - } - ls := grokLogins() - if len(ls) != 2 { - t.Fatalf("logins: %+v", ls) - } - // Keep the cached account last regardless of how logins are ordered, - // so its map write follows the uncached account's go statement. - fetched, cached := ls[0], ls[len(ls)-1] - grokHomeUsage.Lock() - oldCache := grokHomeUsage.m - grokHomeUsage.m = map[string]loginUsageEntry{ - cached.Home: {at: time.Now(), q: SubscriptionQuota{Provider: "grok", - Windows: []QuotaWindow{{Name: "7 days", Used: 97}}}}, - } - grokHomeUsage.Unlock() - t.Cleanup(func() { - grokHomeUsage.Lock() - grokHomeUsage.m = oldCache - grokHomeUsage.Unlock() - }) - - var hits atomic.Int32 - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - hits.Add(1) - if r.URL.Path != "/billing" || r.URL.Query().Get("format") != "credits" || - r.Header.Get("Authorization") != "Bearer k-"+fetched.User { - t.Errorf("unexpected usage request: %s", r.URL) - w.WriteHeader(http.StatusBadRequest) - return - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"config":{"creditUsagePercent":12,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY"}}}`)) - })) - defer fake.Close() - old := GrokBase - GrokBase = fake.URL - t.Cleanup(func() { GrokBase = old }) - - for i := range 2 { // the fetched account is cached on the second read - u := LoginUsage(context.Background(), "grok") - if len(u) != 2 { - t.Fatalf("read %d: usage for %d accounts, want 2", i, len(u)) - } - for user, want := range map[string]float64{fetched.User: 12, cached.User: 97} { - q := u[user] - if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Used != want { - t.Fatalf("read %d: %s usage %+v, want %v%%", i, user, q, want) - } - } - if got := hits.Load(); got != 1 { - t.Fatalf("read %d: %d requests, want only the uncached account fetched once", i, got) - } - } +// newGrokHome and addGrokLogin keep a further Grok account the way the +// retired built-in kept one, in a home of its own, so the move onto the +// plugin is tested against what users who signed in there still have. +func newGrokHome() (string, error) { + home := filepath.Join(filepath.Dir(Path()), "grok", strings.ToLower(strings.NewReplacer("-", "", "_", "").Replace(randomToken(9)))) + return home, os.MkdirAll(home, 0o700) } -// The Usage page's whole-page read of a Grok account and the per-home read -// LoginUsage makes of the same account write the one key on disk: the page's -// started first, so its late answer is the older reading, and must not -// become what the next failed read falls back to. -func TestGrokPerHomeReadKeepsTheNewerReading(t *testing.T) { - home := signIn(t) - t.Setenv("GROK_HOME", filepath.Join(home, ".grok")) - grokSignedIn(t, GrokHome(), "grok@example.com") - reset := func() { - lastQuotas.Lock() - lastQuotas.m, lastQuotas.loaded = nil, false - lastQuotas.Unlock() - grokHomeUsage.Lock() - grokHomeUsage.m = nil - grokHomeUsage.Unlock() - } - reset() - t.Cleanup(reset) - - // what the CLI's own /usage says, and whether the vendor is refusing it: - // the httptest handler reads both off its own goroutine, while the test - // writes them here - used, refused := atomic.Int32{}, atomic.Bool{} - used.Store(80) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - if refused.Load() { - w.WriteHeader(http.StatusServiceUnavailable) - return - } - fmt.Fprintf(w, `{"config":{"creditUsagePercent":%d,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY"}}}`, used.Load()) - })) - t.Cleanup(srv.Close) - oldBase := GrokBase - GrokBase = srv.URL - t.Cleanup(func() { GrokBase = oldBase }) - - // the page's read starts first - pageCtx, _ := quotaReading(context.Background()) - - used.Store(80) // the per-home read, started later, answers first - u := grokLoginUsage(context.Background()) - if got := u["grok@example.com"].Windows[0].Used; got != 80 { - t.Fatalf("per-home read %v%%, want 80", got) - } - - used.Store(10) // the page's answer: started first, so the older reading - keepReading(pageCtx, readNow(grokSubscriptionUsage(pageCtx)), "") - - c := &lastQuotas - c.Lock() - kept := c.m["grok/grok@example.com"].Q - c.Unlock() - if kept.Windows[0].Used != 80 { - t.Fatalf("last reading on disk is %v%%, want the newer 80", kept.Windows[0].Used) - } - - // the vendor has a hiccup: the last reading kept is what the account - // falls back to, the file read again as after a restart - c.Lock() - c.m, c.loaded = nil, false - c.Unlock() - refused.Store(true) - failCtx, _ := quotaReading(context.Background()) - q := keepReading(failCtx, grokUsageAt(failCtx, GrokHome()), "grok@example.com") - if q.Error != "" || q.AsOf == nil || len(q.Windows) != 1 || q.Windows[0].Used != 80 { - t.Fatalf("after a failed read %+v, want the kept 80%%", q) - } -} - -// A further Grok account signs in in a home of magpie's: the CLI's own -// stays as it is, both are in use, and either can go first. -func TestGrokAccounts(t *testing.T) { - home := signIn(t) - own := filepath.Join(home, ".grok") - grokSignedIn(t, own, "me@x.ai") - - extra, err := newGrokHome() - if err != nil { - t.Fatal(err) - } - grokSignedIn(t, extra, "two@x.ai") - if u, err := addGrokLogin(extra); err != nil || u != "two@x.ai" { - t.Fatalf("add: %q %v", u, err) - } - ls := Logins("grok") - if len(ls) != 2 || ls[0].User != "me@x.ai" || !ls[0].Active || ls[1].User != "two@x.ai" || !ls[1].On { - t.Fatalf("logins: %+v", ls) - } - p := Provider{ID: "grok", Account: &Account{Agent: "grok", User: "me@x.ai"}} - if also := p.AlsoOn(); len(also) != 1 || also[0].Account.User != "two@x.ai" || also[0].Account.Home != extra { - t.Fatalf("also on: %+v", also) - } - - if err := SwitchLogin("grok", "two@x.ai"); err != nil { - t.Fatal(err) - } - ls = Logins("grok") - if ls[0].User != "two@x.ai" || !ls[0].Active || !ls[1].On { - t.Fatalf("after switch: %+v", ls) - } - if b, _ := os.ReadFile(filepath.Join(own, "auth.json")); len(b) == 0 { - t.Fatal("the CLI's own sign-in was touched") - } - if err := SetLoginOn("grok", "me@x.ai", false); err != nil { - t.Fatal(err) - } - if also := p.AlsoOn(); len(also) != 0 { - t.Fatalf("turned off, still on: %+v", also) - } - - // signed in again, an account keeps one home - again, _ := newGrokHome() - grokSignedIn(t, again, "two@x.ai") - addGrokLogin(again) - if _, err := os.Stat(extra); !os.IsNotExist(err) { - t.Fatal("the old home was kept") - } - SwitchLogin("grok", "me@x.ai") - if err := ForgetLogin("grok", "two@x.ai"); err != nil { - t.Fatal(err) - } - if _, err := os.Stat(again); !os.IsNotExist(err) || len(Logins("grok")) != 1 { - t.Fatalf("forgotten: %v %+v", err, Logins("grok")) - } -} - -// A Grok account refused while its allowance is being read is read again -// on the next ask: the reading out at the refusal goes to its caller but -// isn't kept, so it isn't served for a minute as the account's share. -func TestGrokUsageStaleMidRead(t *testing.T) { - home := signIn(t) - t.Setenv("GROK_HOME", filepath.Join(home, ".grok")) - grokSignedIn(t, GrokHome(), "me@x.ai") - grokHomeUsage.Lock() - oldCache := grokHomeUsage.m - grokHomeUsage.m = nil - grokHomeUsage.Unlock() - t.Cleanup(func() { - grokHomeUsage.Lock() - grokHomeUsage.m = oldCache - grokHomeUsage.Unlock() - }) - - release := make(chan struct{}) - var once sync.Once - var hits atomic.Int32 - fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - used := 40 - if hits.Add(1) == 1 { // out as the request is refused - <-release - used = 90 - } - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `{"config":{"creditUsagePercent":%d,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY"}}}`, used) - })) - var wg sync.WaitGroup - // the reading this test starts is waited for before the server closes - t.Cleanup(func() { - once.Do(func() { close(release) }) - wg.Wait() - fake.Close() - }) - old := GrokBase - GrokBase = fake.URL - t.Cleanup(func() { GrokBase = old }) - - used := func(u map[string]SubscriptionQuota) float64 { - q := u["me@x.ai"] - if q.Error != "" || len(q.Windows) != 1 { - t.Fatalf("usage %+v", q) - } - return q.Windows[0].Used - } - var first map[string]SubscriptionQuota - wg.Add(1) - go func() { - defer wg.Done() - first = LoginUsage(context.Background(), "grok") - }() - for hits.Load() < 1 { - time.Sleep(5 * time.Millisecond) - } - StaleAllowance("grok", "me@x.ai") - once.Do(func() { close(release) }) - wg.Wait() - if u := used(first); u != 90 { - t.Fatalf("the reading out at the refusal gave its caller %v%%", u) - } - if u := used(LoginUsage(context.Background(), "grok")); u != 40 || hits.Load() != 2 { - t.Fatalf("next reading %v%%, %d requests: the one from before the refusal was kept", u, hits.Load()) +func addGrokLogin(home string) (string, error) { + c, ok := readGrokCredential(home) + if !ok || c.Email == "" { + return "", errors.New("grok login finished without an account") } + own, _ := readGrokCredential(GrokHome()) + return c.Email, addSideLogin(savedLogin{Agent: "grok", User: c.Email, Home: home}, own.Email, func(savedLogin) {}) } diff --git a/internal/provider/grok_install.go b/internal/provider/grok_install.go index ff320059f..7f3413be4 100644 --- a/internal/provider/grok_install.go +++ b/internal/provider/grok_install.go @@ -1,13 +1,14 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-grok-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/grok) and raise the mover's -// min in internal/provider/migrate_side.go. +// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-grok-auth (provider.BuiltinRetired). Its +// sign-in, models, requests and usage are the plugin's; what is left here +// reads the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and finds the Grok CLI the plugin signs in +// with, and shapes the plugin's request bodies (grokBody). A fix belongs in +// the plugin (github.com/magpie-community/plugins, packages/grok), with the +// mover's min raised in internal/provider/migrate_side.go. // Grok Build installed without a shell, as its installer // (https://x.ai/cli/install.sh) installs it: the channel's version, that diff --git a/internal/provider/grok_price_test.go b/internal/provider/grok_price_test.go index 7e6dd6be8..92f6f70c7 100644 --- a/internal/provider/grok_price_test.go +++ b/internal/provider/grok_price_test.go @@ -119,7 +119,7 @@ func TestCursorGrokFastPrice(t *testing.T) { } } -// A window the id names without a k (grokWindowLabel writes a window that +// A window the id names without a k (the grok plugin writes a window that // no multiple of 1000 is as bare digits) is priced as its model, as one // spelled with a k is. func TestGrokWindowWithoutKListPrice(t *testing.T) { diff --git a/internal/provider/grok_test.go b/internal/provider/grok_test.go index 485a447e4..14b15504c 100644 --- a/internal/provider/grok_test.go +++ b/internal/provider/grok_test.go @@ -1,165 +1,19 @@ package provider import ( - "context" "encoding/json" "fmt" - "io" "maps" - "net/http" - "net/http/httptest" "os" "path/filepath" "runtime" "slices" "strings" "testing" - "time" "github.com/yetone/magpie/internal/testenv" ) -func TestParseGrokModels(t *testing.T) { - b := []byte(`{"object":"list","data":[ - {"id":"grok-4.7","name":"Grok 4.7","context_window":500000,"api_backend":"responses","reasoning_efforts":[{"value":"xhigh"},{"value":"high"},{"value":"medium"},{"value":"low"}]}, - {"id":"grok-4.7-build-fast","context_window":256000,"api_backend":"responses"}, - {"id":"grok-old","api_backend":"chat_completions"}]}`) - ms := parseGrokModels(b) - if len(ms) != 2 || ms[0].ID != "grok-4.7" || ms[0].Name != "Grok 4.7" || ms[0].Context != 500000 || - strings.Join(ms[0].Efforts, ",") != "low,medium,high,xhigh" || ms[1].Name != "grok-4.7-build-fast" || ms[1].Efforts != nil { - t.Fatalf("models = %+v", ms) - } -} - -// A model Grok lists at more than one context window is offered at each, -// as the CLI's /context-window offers it (#1608): the default keeps the -// plain id, 500K is grok-4.7@500k. The literal list is Grok 1.0.50's -// models_cache.json from the report. -func TestParseGrokModelsWindows(t *testing.T) { - b := []byte(`{"object":"list","data":[ - {"id":"grok-4.7","name":"Grok 4.7","context_window":256000,"context_windows":[256000,500000],"api_backend":"responses","reasoning_efforts":[{"value":"high"},{"value":"low"}]}, - {"id":"grok-4.5","context_window":256000,"context_windows":[256000],"api_backend":"responses"}, - {"id":"grok-odd","context_window":100000,"context_windows":[200000,400000,400000],"api_backend":"responses"}]}`) - var got []string - for _, m := range parseGrokModels(b) { - got = append(got, fmt.Sprintf("%s|%s|%d|%s", m.ID, m.Name, m.Context, strings.Join(m.Efforts, ","))) - } - want := []string{ - "grok-4.7|Grok 4.7|256000|low,high", "grok-4.7@500k|Grok 4.7 @ 500k|500000|low,high", - "grok-4.5|grok-4.5|256000|", - // a default the list doesn't hold goes to the list's first - "grok-odd|grok-odd|200000|", "grok-odd@400k|grok-odd @ 400k|400000|"} - if !slices.Equal(got, want) { - t.Fatalf("models =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} - -// A model at a window of its own goes to Grok as the model it lists, with -// the window in x-grok-context-window, as the CLI sends it (#1608); the -// plain id goes as it is, with no window. -func TestGrokSignsWindow(t *testing.T) { - home := t.TempDir() - grokSignedIn(t, home, "me@x.ai") - acct := &Account{Agent: "grok"} - grokSigned(acct, home) - for _, c := range []struct{ model, sent, window string }{ - {"grok-4.7@500k", "grok-4.7", "500000"}, - {"grok-4.7", "grok-4.7", ""}, - {"grok-4.7@big", "grok-4.7@big", ""}, - } { - body := []byte(`{"model":"` + c.model + `","input":"hi","prompt_cache_key":"c1"}`) - req, _ := http.NewRequest("POST", "http://grok.invalid/responses", strings.NewReader(string(body))) - if err := acct.sign(context.Background(), req, body); err != nil { - t.Fatal(err) - } - b, _ := io.ReadAll(req.Body) - var v map[string]any - if err := json.Unmarshal(b, &v); err != nil || v["model"] != c.sent || v["input"] != "hi" || req.ContentLength != int64(len(b)) { - t.Errorf("%s: body = %s (%d)", c.model, b, req.ContentLength) - } - if req.Header.Get("x-grok-model-override") != c.sent || req.Header.Get("x-grok-context-window") != c.window || - req.Header.Get("x-grok-conv-id") != "c1" { - t.Errorf("%s: headers = %v", c.model, req.Header) - } - } -} - -// A window the id names without a k (131072: grokWindowLabel writes a -// window that no multiple of 1000 is as bare digits) is signed as that -// window at the model Grok lists, not sent as an id of its own. -func TestGrokSignsWindowWithoutK(t *testing.T) { - home := t.TempDir() - grokSignedIn(t, home, "me@x.ai") - acct := &Account{Agent: "grok"} - grokSigned(acct, home) - for _, c := range []struct{ model, sent, window string }{ - {"grok-4.7@131072", "grok-4.7", "131072"}, - {"grok-4.7@500k", "grok-4.7", "500000"}, - } { - body := []byte(`{"model":"` + c.model + `","input":"hi"}`) - req, _ := http.NewRequest("POST", "http://grok.invalid/responses", strings.NewReader(string(body))) - if err := acct.sign(context.Background(), req, body); err != nil { - t.Fatal(err) - } - if req.Header.Get("x-grok-model-override") != c.sent || req.Header.Get("x-grok-context-window") != c.window { - t.Errorf("%s: headers = %v, want %s at window %s", c.model, req.Header, c.sent, c.window) - } - } -} - -// A request is signed with the sign-in of its account's home, as the CLI -// signs its own. -func TestGrokSigns(t *testing.T) { - var got http.Header - up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - got = r.Header.Clone() - w.Write([]byte(`{"data":[{"id":"grok-4.7","api_backend":"responses"}]}`)) - })) - defer up.Close() - base := GrokBase - GrokBase = up.URL - defer func() { GrokBase = base }() - home := t.TempDir() - grokSignedIn(t, home, "me@x.ai") - acct := &Account{Agent: "grok"} - grokSigned(acct, home) - req, _ := http.NewRequest("POST", up.URL+"/responses", nil) - if err := acct.sign(context.Background(), req, []byte(`{"model":"grok-4.7","prompt_cache_key":"c1"}`)); err != nil { - t.Fatal(err) - } - if req.Header.Get("Authorization") != "Bearer k-me@x.ai" || req.Header.Get("x-grok-client-version") == "" || - req.Header.Get("x-grok-model-override") != "grok-4.7" || req.Header.Get("x-grok-conv-id") != "c1" || - !strings.HasPrefix(req.Header.Get("User-Agent"), "grok-shell/") { - t.Fatalf("headers = %v", req.Header) - } - ms, err := grokModels(context.Background(), acct.sign) - if err != nil || len(ms) != 1 || got.Get("Authorization") != "Bearer k-me@x.ai" { - t.Fatalf("%v %+v %v", err, ms, got) - } -} - -func TestGrokTokenReadsTheCLIsSignIn(t *testing.T) { - home := t.TempDir() - exp := time.Now().Add(2 * time.Hour).UTC() - auth := map[string]any{"https://auth.x.ai::u1": map[string]any{ - "key": "tok", "email": "me@example.com", "auth_mode": "oidc", "refresh_token": "r", - "expires_at": exp.Format(time.RFC3339Nano), "oidc_issuer": "https://auth.x.ai"}} - b, _ := json.Marshal(auth) - if err := os.WriteFile(filepath.Join(home, "auth.json"), b, 0o600); err != nil { - t.Fatal(err) - } - if u, ok := GrokUser(home); !ok || u != "me@example.com" { - t.Fatalf("user = %q %v", u, ok) - } - c, err := grokAccessToken(home, "", false) - if err != nil || c.Key != "tok" { - t.Fatalf("%+v %v", c, err) - } - if _, err := grokAccessToken(t.TempDir(), "", false); err == nil { - t.Fatal("no sign-in, yet a token") - } -} - // Codex's freeform apply_patch is left out: Grok's backend turns away a // request with a tool type it doesn't know, a namespace among them. A // namespace's functions go as functions of their own, under their flat diff --git a/internal/provider/grok_usage.go b/internal/provider/grok_usage.go index 9e92b4ea9..1797c6990 100644 --- a/internal/provider/grok_usage.go +++ b/internal/provider/grok_usage.go @@ -1,97 +1,14 @@ package provider -// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a deprecated built-in -// subscription served by its plugin, @magpie-community/opencode-grok-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/grok) and raise the mover's -// min in internal/provider/migrate_side.go. - -// How much of a Grok subscription's allowance is gone, as the CLI's own -// /usage reads it: the credits of the current period, weekly for SuperGrok, -// and what on-demand spending has used of its cap. - -import ( - "context" - "strings" - "time" -) +// PLUGIN-SERVED (see AGENTS.md): Grok ("grok") is a retired built-in +// subscription, served by its plugin alone, +// @magpie-community/opencode-grok-auth (provider.BuiltinRetired). Its +// sign-in, models, requests and usage are the plugin's; what is left here +// reads the accounts signed in to the built-in for the move onto the plugin +// (migrate_side.go), installs and finds the Grok CLI the plugin signs in +// with, and shapes the plugin's request bodies (grokBody). A fix belongs in +// the plugin (github.com/magpie-community/plugins, packages/grok), with the +// mover's min raised in internal/provider/migrate_side.go. // GrokBase is the CLI's backend; a var so tests can point it elsewhere. var GrokBase = "https://cli-chat-proxy.grok.com/v1" - -func grokSubscriptionUsage(ctx context.Context) SubscriptionQuota { - q := SubscriptionQuota{Provider: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Windows: []QuotaWindow{}} - if c, ok := readGrokCredential(GrokHome()); ok { - q.User = c.Email - } - if holding(ctx) { - q.Error = errNotAsked.Error() - return q - } - c, err := grokAccessToken(GrokHome(), GrokExecutable(), false) - if err == nil { - q.Windows, err = grokWindows(ctx, c.Key) - } - if err != nil { - q.Error = err.Error() - } - return q -} - -type grokAmount struct { - Val float64 `json:"val"` -} - -// grokWindows: the credits used this period, and the on-demand spending -// when the account allows any. -func grokWindows(ctx context.Context, token string) ([]QuotaWindow, error) { - var data struct { - Config struct { - CreditUsagePercent float64 `json:"creditUsagePercent"` - CurrentPeriod *struct { - Type string `json:"type"` - End string `json:"end"` - } `json:"currentPeriod"` - BillingPeriodEnd string `json:"billingPeriodEnd"` - OnDemandCap grokAmount `json:"onDemandCap"` - OnDemandUsed grokAmount `json:"onDemandUsed"` - } `json:"config"` - } - if err := accountJSON(ctx, GrokBase+"/billing?format=credits", token, nil, &data); err != nil { - return []QuotaWindow{}, err - } - cfg := data.Config - name, end := "Allowance", cfg.BillingPeriodEnd - if p := cfg.CurrentPeriod; p != nil { - name, end = grokPeriodName(p.Type), p.End - } - w := QuotaWindow{Name: name, Used: cfg.CreditUsagePercent, Span: grokPeriodSpan[name]} - if t, err := time.Parse(time.RFC3339Nano, end); err == nil { - w.ResetsAt = &t - } - out := []QuotaWindow{w} - if cfg.OnDemandCap.Val > 0 { - out = append(out, QuotaWindow{Name: "On-demand", Used: 100 * cfg.OnDemandUsed.Val / cfg.OnDemandCap.Val, ResetsAt: w.ResetsAt, Aside: true}) - } - return out, nil -} - -// grokPeriodName names a USAGE_PERIOD_TYPE_* the way the other allowances -// are named. -func grokPeriodName(t string) string { - switch strings.TrimPrefix(t, "USAGE_PERIOD_TYPE_") { - case "DAILY": - return "1 day" - case "WEEKLY": - return "7 days" - case "MONTHLY": - return "Month" - } - return "Allowance" -} - -// grokPeriodSpan is how long each of grokPeriodName's periods runs. -var grokPeriodSpan = map[string]time.Duration{"1 day": 24 * time.Hour, "7 days": 7 * 24 * time.Hour, "Month": 30 * 24 * time.Hour} diff --git a/internal/provider/grok_usage_test.go b/internal/provider/grok_usage_test.go deleted file mode 100644 index 64abacf99..000000000 --- a/internal/provider/grok_usage_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package provider - -import ( - "context" - "net/http" - "net/http/httptest" - "testing" -) - -func TestGrokWindows(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/billing" || r.URL.Query().Get("format") != "credits" || r.Header.Get("Authorization") != "Bearer tok" { - http.NotFound(w, r) - return - } - w.Write([]byte(`{"config":{"creditUsagePercent":42.5,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY","start":"2026-09-21T02:17:59.504011+00:00","end":"2026-09-28T02:17:59.504011+00:00"},"onDemandCap":{"val":2000},"onDemandUsed":{"val":500},"billingPeriodEnd":"2026-09-28T02:17:59.504011+00:00"}}`)) - })) - defer srv.Close() - defer func(b string) { GrokBase = b }(GrokBase) - GrokBase = srv.URL - - ws, err := grokWindows(context.Background(), "tok") - if err != nil { - t.Fatal(err) - } - if len(ws) != 2 || ws[0].Name != "7 days" || ws[0].Used != 42.5 || ws[0].ResetsAt == nil || ws[0].ResetsAt.Day() != 28 { - t.Fatalf("period = %+v", ws) - } - if ws[1].Name != "On-demand" || ws[1].Used != 25 { - t.Fatalf("on-demand = %+v", ws[1]) - } -} - -// An untouched allowance leaves creditUsagePercent out, and no on-demand cap -// means no on-demand meter. -func TestGrokWindowsUnused(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"config":{"currentPeriod":{"type":"USAGE_PERIOD_TYPE_MONTHLY","end":"2026-10-01T00:00:00+00:00"},"onDemandCap":{"val":0}}}`)) - })) - defer srv.Close() - defer func(b string) { GrokBase = b }(GrokBase) - GrokBase = srv.URL - - ws, err := grokWindows(context.Background(), "tok") - if err != nil || len(ws) != 1 || ws[0].Name != "Month" || ws[0].Used != 0 || ws[0].ResetsAt == nil { - t.Fatalf("windows = %+v, %v", ws, err) - } -} diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index a14afe95b..78e267b3b 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -85,11 +85,6 @@ func loginUsageAt(ctx context.Context, agent string) (map[string]SubscriptionQuo return out, asked } out := map[string]SubscriptionQuota{} - if agent == "grok" { - if _, ok := pluginOfAgent(agent); !ok { - return grokLoginUsage(ctx), asked - } - } logins, ok := usageLogins(agent) if !ok { return out, asked diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 9ee769159..0cab3a756 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -805,8 +805,6 @@ func Logins(agent string) []Login { } var side []Login switch agent { - case "grok": - return grokLoginList() case "copilot": return copilotLoginList() case "devin": @@ -829,14 +827,16 @@ func Logins(agent string) []Login { } } // a built-in moved onto its plugin lists its accounts there (an - // agent's own sign-in, which the built-in still finds, too) + // agent's own sign-in, which the built-in still finds, too); a + // retired one (no list) keeps its place, its plugin serving it for _, b := range []struct { id string list func() []Login }{ - {"grok", grokLoginList}, {"copilot", copilotLoginList}, - {"devin", devinLoginList}, {CommandCodePlanID, cmdLoginList}, - {ChatGPTAPIID, siwcLoginList}, {"gemini", func() []Login { return googleLoginList("gemini") }}, + {"grok", nil}, {"copilot", copilotLoginList}, {"zcode", nil}, {"kiro", nil}, + {"devin", devinLoginList}, {"workbuddy", nil}, {WorkBuddyAIID, nil}, {CommandCodePlanID, cmdLoginList}, + {"qoder", nil}, {QoderCNID, nil}, {"zed", nil}, {"factory", nil}, + {MiMoID, nil}, {ChatGPTAPIID, siwcLoginList}, {"gemini", func() []Login { return googleLoginList("gemini") }}, {"antigravity", func() []Login { return googleLoginList("antigravity") }}, } { if !PluginServes(b.id) { @@ -1030,8 +1030,6 @@ func switchLogin(agent, user string) error { return switchPluginLogin(pp, user) } switch agent { - case "grok": - return switchGrokLogin(user) case "copilot": return switchCopilotLogin(user) case "devin": @@ -1210,8 +1208,6 @@ func ForgetLogin(agent, user string) error { return forgetPluginLogin(pp, user) } switch agent { - case "grok": - return forgetGrokLogin(user) case "copilot": return forgetCopilotLogin(user) case "devin": diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go index 22447cebb..ba13175f7 100644 --- a/internal/provider/logins_on.go +++ b/internal/provider/logins_on.go @@ -35,8 +35,6 @@ func SetLoginOn(agent, user string, on bool) error { return setPluginLoginOn(pp, user, on) } switch agent { - case "grok": - return setGrokLoginOn(user, on) case "copilot": return setCopilotLoginOn(user, on) case "devin": @@ -138,9 +136,6 @@ func (p Provider) alsoOn() []Provider { if p.IsPlugin() { return pluginAlsoOn(*p.Account.plugin) } - if p.Account != nil && p.Account.Agent == "grok" && p.Account.token == nil { - return grokAlsoOn(p) - } if p.Account != nil && p.Account.Agent == "copilot" { return copilotAlsoOn() } diff --git a/internal/provider/migrate.go b/internal/provider/migrate.go index aa2be7e15..596fad348 100644 --- a/internal/provider/migrate.go +++ b/internal/provider/migrate.go @@ -274,6 +274,7 @@ var retiredBuiltins = map[string]bool{ MiMoID: true, "zcode": true, "factory": true, + "grok": true, } // PluginServes is whether the built-in id's subscription is its plugin's to diff --git a/internal/provider/models.go b/internal/provider/models.go index e537a525f..c6ad02c0d 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2169,9 +2169,9 @@ func byIDOrWas(id string) (Provider, bool) { var grokEffort = regexp.MustCompile(`^((?:.*/)?grok-[0-9][^/]*?)-(?:minimal|low|medium|high|xhigh|extra-high)$`) // grokWindow is a Grok id offered at a context window of its own -// ("grok-4.7@500k", grokContextModels and the grok plugin's windowsOf): the -// same model, asked for at a longer window. A window no multiple of 1000 -// the id names without the k (grokWindowLabel, grokWindowed). +// ("grok-4.7@500k", the grok plugin's windowsOf): the same model, asked for +// at a longer window. A window no multiple of 1000 the id names without the +// k. var grokWindow = regexp.MustCompile(`^((?:.*/)?grok-[0-9][^/@]*)@[0-9]+k?$`) // pricedNames are the ids a model is priced by, in order: its own, then, diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 203b2a4db..b5be1394c 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -680,19 +680,6 @@ func StaleAllowance(agent, user string) { delete(loginUsageCache.m, key) delete(loginUsageCache.pending, key) // nor a reading asked for before loginUsageCache.Unlock() - // the built-in keeps Grok's usage by home; a Grok moved to its plugin - // keeps it as "plugin:grok"'s, the line above - if agent == "grok" { - gs := grokLogins() - grokHomeUsage.Lock() - for _, g := range gs { - if strings.EqualFold(g.User, user) { - delete(grokHomeUsage.m, g.Home) - delete(grokHomeUsage.pending, g.Home) - } - } - grokHomeUsage.Unlock() - } usedCache.Lock() if usedCache.at != nil { usedCache.at[agent] = time.Time{} diff --git a/internal/provider/side_logins_hide_test.go b/internal/provider/side_logins_hide_test.go deleted file mode 100644 index 921a45c76..000000000 --- a/internal/provider/side_logins_hide_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package provider - -import ( - "bytes" - "os" - "path/filepath" - "testing" -) - -// own the same way, and shows it again once it is another account. -func TestGrokHideOwnSignIn(t *testing.T) { - home := signIn(t) - own := filepath.Join(home, ".grok") - grokSignedIn(t, own, "me@x.ai") - extra, _ := newGrokHome() - grokSignedIn(t, extra, "two@x.ai") - if _, err := addGrokLogin(extra); err != nil { - t.Fatal(err) - } - before, _ := os.ReadFile(filepath.Join(own, "auth.json")) - if err := ForgetLogin("grok", "me@x.ai"); err != nil { - t.Fatal(err) - } - if ls := Logins("grok"); len(ls) != 1 || ls[0].User != "two@x.ai" || !ls[0].Active { - t.Fatalf("after hide %+v", ls) - } - if after, _ := os.ReadFile(filepath.Join(own, "auth.json")); !bytes.Equal(before, after) { - t.Fatal("the CLI's own sign-in was touched") - } - grokSignedIn(t, own, "new@x.ai") - if ls := Logins("grok"); len(ls) != 2 || ls[0].User != "two@x.ai" || ls[1].User != "new@x.ai" || !ls[1].Own { - t.Fatalf("another account %+v", ls) - } -} diff --git a/internal/provider/signin.go b/internal/provider/signin.go index c7b44dd6c..229b46fbe 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -374,11 +374,6 @@ func (s *signInFlow) begin() error { s.mu.Lock() s.st.URL = siwcAuthorize(s.redirect, s.state, s.nonce, challenge, s.hostID) s.mu.Unlock() - case "grok": - // so is Grok: its CLI signs in with a device code - if err := startGrokSignIn(s); err != nil { - return err - } case "devin": // `devin auth login` is a TUI over this same PKCE + localhost // callback, so magpie runs the round itself diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 3cc110e77..d61a6d0e9 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -447,11 +447,6 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota { } } } - if !moved("grok") && !hidden["grok"] { - if _, ok := grokAccount(); ok { - fetches = append(fetches, func() SubscriptionQuota { return keepReading(ctx, readNow(grokSubscriptionUsage(via("grok"))), "") }) - } - } if home, err := os.UserHomeDir(); err == nil { if p, ok := codexAccount(home); ok && !hidden["codex"] { if ls := accountsOf("codex"); len(ls) > 1 {