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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/quotas/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ const (
)

func fetchAnthropic(ctx context.Context, source Source, client *http.Client) (Report, error) {
token, err := source.AnthropicPlanToken()
token, credentialSource, err := source.AnthropicPlanToken()
if err != nil {
return Report{}, err
}
decoded, err := getJSON(ctx, client, anthropicURL, map[string]string{
"Authorization": "Bearer " + token,
"anthropic-beta": "oauth-2025-04-20",
}, readWait)
}, readWait, credentialSource)
if err != nil {
return Report{}, err
}
Expand Down
4 changes: 2 additions & 2 deletions internal/quotas/copilot.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ const (
)

func fetchCopilot(ctx context.Context, source Source, client *http.Client) (Report, error) {
token, err := source.CopilotToken(ctx)
token, credentialSource, err := source.CopilotToken(ctx)
if err != nil {
return Report{}, err
}
decoded, err := getJSON(ctx, client, copilotURL, map[string]string{
"Authorization": "token " + token,
"X-GitHub-Api-Version": "2025-04-01",
}, readWait)
}, readWait, credentialSource)
if err != nil {
return Report{}, err
}
Expand Down
88 changes: 44 additions & 44 deletions internal/quotas/creds.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,49 +26,49 @@ type Source struct {
}

// APIKey reads provider keys, including Pi keys for Ollama Cloud and OpenCode Go.
func (s Source) APIKey(provider string, vars []string, what string) (string, error) {
func (s Source) APIKey(provider string, vars []string, what string) (string, string, error) {
switch provider {
case "ollama-cloud", "opencode-go":
for _, key := range vars {
if value := strings.TrimSpace(s.env(key)); value != "" {
return value, nil
return value, key + " environment variable", nil
}
}
if token := s.piToken(provider, "api_key", "key"); token != "" {
return token, nil
return token, "Pi", nil
}
}
dotenv := s.dotEnv()
for _, key := range vars {
if value := preferDotEnv(dotenv, key, s.env(key)); value != "" {
return value, nil
if value, location := preferDotEnv(dotenv, key, s.env(key)); value != "" {
return value, location, nil
}
}
if token := s.poolToken(provider); token != "" {
return token, nil
return token, "Hermes", nil
}
return "", MissingError{Text: fmt.Sprintf("Add a %s key in Hermes to read its plan.", what)}
return "", "", MissingError{Text: fmt.Sprintf("Add a %s key in Hermes to read its plan.", what)}
}

// AnthropicPlanToken is Claude's plan sign-in. A Console API key has no plan.
func (s Source) AnthropicPlanToken() (string, error) {
func (s Source) AnthropicPlanToken() (string, string, error) {
dotenv := s.dotEnv()
if token := firstSecret(dotenv, s.env, "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"); token != "" {
return requirePlanToken(token)
if token, location := firstSecret(dotenv, s.env, "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"); token != "" {
return requirePlanToken(token, location)
}
if token := preferDotEnv(dotenv, "ANTHROPIC_API_KEY", s.env("ANTHROPIC_API_KEY")); token != "" {
return requirePlanToken(token)
if token, location := preferDotEnv(dotenv, "ANTHROPIC_API_KEY", s.env("ANTHROPIC_API_KEY")); token != "" {
return requirePlanToken(token, location)
}
if token := s.poolToken("anthropic"); claudeOAuth(token) {
return token, nil
return token, "Hermes", nil
}
if token := s.claudeCodeToken(); claudeOAuth(token) {
return token, nil
return token, "Claude Code", nil
}
if token := s.hermesOAuthToken(); claudeOAuth(token) {
return token, nil
return token, "Hermes", nil
}
return "", MissingError{Text: "Sign in to Claude in Hermes to read its plan."}
return "", "", MissingError{Text: "Sign in to Claude in Hermes to read its plan."}
}

// Command finds a service CLI from an override, PATH, or mise's shims.
Expand All @@ -86,60 +86,60 @@ func (s Source) Command(overrideEnv, name, missing string) (string, error) {
}

// CopilotToken is the GitHub token behind Copilot's premium requests.
func (s Source) CopilotToken(ctx context.Context) (string, error) {
func (s Source) CopilotToken(ctx context.Context) (string, string, error) {
for _, key := range []string{"GITHUB_TOKEN", "GH_TOKEN"} {
if value := strings.TrimSpace(s.env(key)); value != "" {
return value, nil
return value, key + " environment variable", nil
}
}
if token := s.piToken("github-copilot", "oauth", "access"); token != "" {
return token, nil
return token, "Pi", nil
}
gh, err := s.look("gh")
if err != nil || blank(gh) {
gh = s.shim("gh")
}
if gh == "" {
return "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."}
return "", "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."}
}
output, err := s.run(ctx, gh, "auth", "token")
token := strings.TrimSpace(string(output))
if err != nil || blank(token) {
return "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."}
return "", "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."}
}
return token, nil
return token, "GitHub CLI", nil
}

// MiniMaxToken is a Coding Plan key, or the OAuth access token for that plan.
func (s Source) MiniMaxToken() (string, error) {
token, err := s.APIKey("minimax", []string{"MINIMAX_API_KEY"}, "MiniMax")
func (s Source) MiniMaxToken() (string, string, error) {
token, location, err := s.APIKey("minimax", []string{"MINIMAX_API_KEY"}, "MiniMax")
if err == nil {
return token, nil
return token, location, nil
}
if oauth := s.providerToken("minimax-oauth"); oauth != "" {
return oauth, nil
return oauth, "Hermes", nil
}
if oauth := s.poolToken("minimax-oauth"); oauth != "" {
return oauth, nil
return oauth, "Hermes", nil
}
return "", err
return "", "", err
}

// XAIToken is a SuperGrok or X Premium sign-in, never an xAI API key.
func (s Source) XAIToken() (string, error) {
func (s Source) XAIToken() (string, string, error) {
if token := s.grokCLIToken(); token != "" {
return token, nil
return token, "Grok CLI", nil
}
if token := s.piToken("xai", "oauth", "access"); token != "" {
return token, nil
return token, "Pi", nil
}
if token := s.providerToken("xai-oauth"); token != "" {
return token, nil
return token, "Hermes", nil
}
if token := s.poolToken("xai-oauth"); token != "" {
return token, nil
return token, "Hermes", nil
}
return "", MissingError{Text: "Sign in to Grok with the Grok CLI, Pi, or Hermes to read its plan."}
return "", "", MissingError{Text: "Sign in to Grok with the Grok CLI, Pi, or Hermes to read its plan."}
}

func (s Source) authDocuments() []map[string]any {
Expand Down Expand Up @@ -317,31 +317,31 @@ func (s Source) userHome() string {
return home
}

func preferDotEnv(dotenv map[string]string, key, environ string) string {
func preferDotEnv(dotenv map[string]string, key, environ string) (string, string) {
raw := strings.TrimSpace(dotenv[key])
if strings.HasPrefix(raw, "op://") {
raw = ""
}
if raw != "" {
return raw
return raw, "Hermes .env (" + key + ")"
}
return strings.TrimSpace(environ)
return strings.TrimSpace(environ), key + " environment variable"
}

func firstSecret(dotenv map[string]string, env func(string) string, keys ...string) string {
func firstSecret(dotenv map[string]string, env func(string) string, keys ...string) (string, string) {
for _, key := range keys {
if value := preferDotEnv(dotenv, key, env(key)); value != "" {
return value
if value, location := preferDotEnv(dotenv, key, env(key)); value != "" {
return value, location
}
}
return ""
return "", ""
}

func requirePlanToken(token string) (string, error) {
func requirePlanToken(token, location string) (string, string, error) {
if claudeOAuth(token) {
return token, nil
return token, location, nil
}
return "", MissingError{Text: "Claude's plan is only reported for a Claude sign-in, not a Console API key."}
return "", "", MissingError{Text: "Claude's plan is only reported for a Claude sign-in, not a Console API key."}
}

func claudeOAuth(token string) bool {
Expand Down
14 changes: 7 additions & 7 deletions internal/quotas/creds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func TestXAITokenUsesClientSignInsInOrder(t *testing.T) {
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
}
source := Source{UserHome: func() string { return home }, Env: func(string) string { return "" }}
token, err := source.XAIToken()
token, _, err := source.XAIToken()
if tc.want == "" {
var missing MissingError
require.ErrorAs(t, err, &missing)
Expand Down Expand Up @@ -102,7 +102,7 @@ func TestPiAPIKeysPrecedeHermesButNotEnvironment(t *testing.T) {
}
return nil, os.ErrNotExist
}
key, err := source.APIKey(provider.id, []string{provider.envKey}, provider.id)
key, _, err := source.APIKey(provider.id, []string{provider.envKey}, provider.id)
require.NoError(t, err)
assert.Equal(t, tc.want, key)
})
Expand Down Expand Up @@ -139,7 +139,7 @@ func TestCopilotUsesPiBeforeGitHubCLI(t *testing.T) {
assert.Equal(t, "gh-token", tc.want, "GitHub CLI should only run as a fallback")
return []byte("gh-token\n"), nil
}
token, err := source.CopilotToken(t.Context())
token, _, err := source.CopilotToken(t.Context())
require.NoError(t, err)
assert.Equal(t, tc.want, token)
})
Expand All @@ -152,7 +152,7 @@ func TestDotEnvBeatsAStaleEnvironmentKey(t *testing.T) {
t.Setenv("DEEPSEEK_API_KEY", "from-env")
require.NoError(t, os.WriteFile(filepath.Join(home, ".env"), []byte("DEEPSEEK_API_KEY=from-dotenv\n"), 0o600))

key, err := (Source{}).APIKey("deepseek", []string{"DEEPSEEK_API_KEY"}, "DeepSeek")
key, _, err := (Source{}).APIKey("deepseek", []string{"DEEPSEEK_API_KEY"}, "DeepSeek")
require.NoError(t, err)
assert.Equal(t, "from-dotenv", key)
}
Expand All @@ -165,7 +165,7 @@ func TestPoolSuppliesAKeyTheEnvironmentDoesNot(t *testing.T) {
t.Setenv("Z_AI_API_KEY", "")
require.NoError(t, os.WriteFile(filepath.Join(home, "auth.json"), []byte(`{"credential_pool":{"zai":[{"access_token":"pool-zai"}]}}`), 0o600))

key, err := (Source{}).APIKey("zai", []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai")
key, _, err := (Source{}).APIKey("zai", []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai")
require.NoError(t, err)
assert.Equal(t, "pool-zai", key)
}
Expand All @@ -176,7 +176,7 @@ func TestConsoleAPIKeyIsNotAClaudePlan(t *testing.T) {
t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")
t.Setenv("ANTHROPIC_API_KEY", "sk-ant-api-test")

_, err := (Source{}).AnthropicPlanToken()
_, _, err := (Source{}).AnthropicPlanToken()
var missing MissingError
require.ErrorAs(t, err, &missing)
assert.Contains(t, missing.Error(), "Console API key")
Expand All @@ -192,7 +192,7 @@ func TestClaudeCodeFileSuppliesAPlanToken(t *testing.T) {
require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude"), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(home, ".claude", ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"sk-ant-oat-file"}}`), 0o600))

token, err := (Source{UserHome: func() string { return home }}).AnthropicPlanToken()
token, _, err := (Source{UserHome: func() string { return home }}).AnthropicPlanToken()
require.NoError(t, err)
assert.Equal(t, "sk-ant-oat-file", token)
}
4 changes: 2 additions & 2 deletions internal/quotas/deepseek.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ const (
)

func fetchDeepSeek(ctx context.Context, source Source, client *http.Client) (Report, error) {
key, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek")
key, credentialSource, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek")
if err != nil {
return Report{}, err
}
decoded, err := getJSON(ctx, client, deepSeekURL, bearer(key), readWait)
decoded, err := getJSON(ctx, client, deepSeekURL, bearer(key), readWait, credentialSource)
if err != nil {
return Report{}, err
}
Expand Down
64 changes: 64 additions & 0 deletions internal/quotas/fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,70 @@ func TestZAIRefusesAKeyWithoutACodingPlan(t *testing.T) {
assert.Equal(t, "This key has no GLM Coding Plan: subscribe at z.ai/subscribe.", said.Error())
}

func TestQuotaRefusalsNameCredentialSource(t *testing.T) {
t.Parallel()
tests := []struct {
name string
fetch func(context.Context, Source, *http.Client) (Report, error)
source Source
status int
body string
want string
}{
{"DeepSeek environment", fetchDeepSeek, envSource(map[string]string{"DEEPSEEK_API_KEY": "test-key"}), http.StatusUnauthorized, "", "DEEPSEEK_API_KEY environment variable"},
{"MiniMax body refusal", fetchMiniMax, envSource(map[string]string{"MINIMAX_API_KEY": "test-key"}), http.StatusOK, `{"base_resp":{"status_code":1004}}`, "MINIMAX_API_KEY environment variable"},
{"Copilot Pi sign-in", fetchCopilot, Source{
UserHome: func() string { return "/test-home" },
Env: func(string) string { return "" },
ReadFile: func(path string) ([]byte, error) {
if path == "/test-home/.pi/agent/auth.json" {
return []byte(`{"github-copilot":{"type":"oauth","access":"test-key"}}`), nil
}
return nil, os.ErrNotExist
},
}, http.StatusForbidden, "", "Pi"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.status)
_, _ = w.Write([]byte(tc.body))
})
_, err := tc.fetch(t.Context(), tc.source, client)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.want)
assert.NotContains(t, err.Error(), "test-key")
})
}
}

func TestGrokNamesRejectedCredentialSource(t *testing.T) {
t.Parallel()
cases := []struct {
name string
path string
body string
}{
{"Grok CLI", ".grok/auth.json", `{"https://auth.x.ai::client":{"auth_mode":"oidc","key":"token"}}`},
{"Pi", ".pi/agent/auth.json", `{"xai":{"type":"oauth","access":"token"}}`},
{"Hermes", ".hermes/auth.json", `{"providers":{"xai-oauth":{"tokens":{"access_token":"token"}}}}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
path := filepath.Join(home, tc.path)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
require.NoError(t, os.WriteFile(path, []byte(tc.body), 0o600))
source := Source{UserHome: func() string { return home }, Env: func(string) string { return "" }}
client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) })
_, err := fetchGrok(t.Context(), source, client)
require.Error(t, err)
assert.Contains(t, err.Error(), "401")
assert.Contains(t, err.Error(), tc.name)
})
}
}

func TestGrokNamesATeamAccount(t *testing.T) {
t.Parallel()
client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) {
Expand Down
Loading
Loading