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
58 changes: 55 additions & 3 deletions internal/quotas/creds.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

const commandWait = 10 * time.Second

// Source reads the sign-ins Hermes already stores on this machine.
// Source reads the sign-ins clients already store on this machine.
// A zero Source reads the process environment, HERMES_HOME, and the user home.
type Source struct {
Env func(string) string
Expand All @@ -25,8 +25,19 @@ type Source struct {
ReadFile func(string) ([]byte, error)
}

// APIKey is a provider key from Hermes's .env, the environment, or the credential pool.
// 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) {
switch provider {
case "ollama-cloud", "opencode-go":
for _, key := range vars {
if value := strings.TrimSpace(s.env(key)); value != "" {
return value, nil
}
}
if token := s.piToken(provider, "api_key", "key"); token != "" {
return token, nil
}
}
dotenv := s.dotEnv()
for _, key := range vars {
if value := preferDotEnv(dotenv, key, s.env(key)); value != "" {
Expand Down Expand Up @@ -81,6 +92,9 @@ func (s Source) CopilotToken(ctx context.Context) (string, error) {
return value, nil
}
}
if token := s.piToken("github-copilot", "oauth", "access"); token != "" {
return token, nil
}
gh, err := s.look("gh")
if err != nil || blank(gh) {
gh = s.shim("gh")
Expand Down Expand Up @@ -113,13 +127,19 @@ func (s Source) MiniMaxToken() (string, error) {

// XAIToken is a SuperGrok or X Premium sign-in, never an xAI API key.
func (s Source) XAIToken() (string, error) {
if token := s.grokCLIToken(); token != "" {
return token, nil
}
if token := s.piToken("xai", "oauth", "access"); token != "" {
return token, nil
}
if token := s.providerToken("xai-oauth"); token != "" {
return token, nil
}
if token := s.poolToken("xai-oauth"); token != "" {
return token, nil
}
return "", MissingError{Text: "Sign in to Grok in 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 @@ -169,6 +189,26 @@ func (s Source) env(key string) string {
return os.Getenv(key)
}

func (s Source) grokCLIToken() string {
document := s.readJSON(filepath.Join(s.userHome(), ".grok", "auth.json"))
for id, value := range document {
if !strings.HasPrefix(id, "https://auth.x.ai::") {
continue
}
state, ok := asObject(value)
if !ok {
continue
}
if state["auth_mode"] != "oidc" {
continue
}
if token := oauthAccessToken(state, "", "key"); token != "" {
return token
}
}
return ""
}

func (s Source) hermesHome() string {
if s.Hermes != nil {
return s.Hermes()
Expand All @@ -190,6 +230,18 @@ func (s Source) look(name string) (string, error) {
return exec.LookPath(name)
}

func (s Source) piToken(provider, kind, field string) string {
document := s.readJSON(filepath.Join(s.userHome(), ".pi", "agent", "auth.json"))
state, ok := asObject(document[provider])
if !ok {
return ""
}
if state["type"] != kind {
return ""
}
return oauthAccessToken(state, "", field)
}

func (s Source) poolToken(provider string) string {
for _, document := range s.authDocuments() {
entries, present := poolEntries(document, provider)
Expand Down
137 changes: 137 additions & 0 deletions internal/quotas/creds_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package quotas

import (
"context"
"os"
"path/filepath"
"testing"
Expand All @@ -9,6 +10,142 @@ import (
"github.com/stretchr/testify/require"
)

func TestXAITokenUsesClientSignInsInOrder(t *testing.T) {
t.Parallel()
const grok = `{"https://auth.x.ai::client-id":{"auth_mode":"oidc","key":"grok-token"}}`
const pi = `{"xai":{"type":"oauth","access":"pi-token","refresh":"pi-refresh"}}`
const hermes = `{"providers":{"xai-oauth":{"tokens":{"access_token":"hermes-token"}}}}`
cases := []struct {
name string
grok string
pi string
hermes string
want string
}{
{name: "Grok before Pi and Hermes", grok: grok, pi: pi, hermes: hermes, want: "grok-token"},
{name: "Pi before Hermes", pi: pi, hermes: hermes, want: "pi-token"},
{name: "Hermes provider", hermes: hermes, want: "hermes-token"},
{name: "Hermes pool", hermes: `{"credential_pool":{"xai-oauth":[{"access_token":"pool-token"}]}}`, want: "pool-token"},
{name: "malformed Grok", grok: `{`, pi: pi, want: "pi-token"},
{name: "malformed Pi", pi: `[]`, hermes: hermes, want: "hermes-token"},
{name: "empty Grok token", grok: `{"https://auth.x.ai::client-id":{"auth_mode":"oidc","key":""}}`, pi: pi, want: "pi-token"},
{name: "Pi refresh alone", pi: `{"xai":{"type":"oauth","refresh":"not-an-access-token"}}`, hermes: hermes, want: "hermes-token"},
{name: "Grok API key", grok: `{"https://auth.x.ai::client-id":{"auth_mode":"api_key","key":"not-a-plan-token"}}`, pi: pi, want: "pi-token"},
{name: "unrelated issuer", grok: `{"https://other.example::client-id":{"auth_mode":"oidc","key":"not-a-grok-token"}}`, pi: pi, want: "pi-token"},
{name: "Pi API key", pi: `{"xai":{"type":"api_key","key":"not-a-plan-token","access":"not-oauth"}}`},
{name: "no sign-in"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
home := t.TempDir()
files := map[string]string{
filepath.Join(home, ".grok", "auth.json"): tc.grok,
filepath.Join(home, ".pi", "agent", "auth.json"): tc.pi,
filepath.Join(home, ".hermes", "auth.json"): tc.hermes,
}
for path, body := range files {
if body == "" {
continue
}
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
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()
if tc.want == "" {
var missing MissingError
require.ErrorAs(t, err, &missing)
assert.Contains(t, err.Error(), "Sign in to Grok")
} else {
require.NoError(t, err)
}
assert.Equal(t, tc.want, token)
})
}
}

func TestPiAPIKeysPrecedeHermesButNotEnvironment(t *testing.T) {
t.Parallel()
providers := []struct {
id string
envKey string
}{
{id: "ollama-cloud", envKey: "OLLAMA_API_KEY"},
{id: "opencode-go", envKey: "OPENCODE_GO_API_KEY"},
}
cases := []struct {
name string
entry string
env string
want string
}{
{name: "Pi before Hermes dotenv and pool", entry: `{"type":"api_key","key":"pi-key"}`, want: "pi-key"},
{name: "environment override", entry: `{"type":"api_key","key":"pi-key"}`, env: "env-key", want: "env-key"},
{name: "missing Pi entry", entry: `null`, want: "hermes-key"},
{name: "empty Pi key", entry: `{"type":"api_key","key":""}`, want: "hermes-key"},
{name: "OAuth is not an API key", entry: `{"type":"oauth","key":"wrong-type","access":"oauth-token"}`, want: "hermes-key"},
}
for _, provider := range providers {
for _, tc := range cases {
t.Run(provider.id+"/"+tc.name, func(t *testing.T) {
t.Parallel()
source := envSource(map[string]string{provider.envKey: tc.env})
source.ReadFile = func(path string) ([]byte, error) {
switch path {
case filepath.Join(".pi", "agent", "auth.json"):
return []byte(`{"` + provider.id + `":` + tc.entry + `}`), nil
case ".env":
return []byte(provider.envKey + "=hermes-key"), nil
case "auth.json":
return []byte(`{"credential_pool":{"` + provider.id + `":[{"access_token":"pool-key"}]}}`), nil
}
return nil, os.ErrNotExist
}
key, err := source.APIKey(provider.id, []string{provider.envKey}, provider.id)
require.NoError(t, err)
assert.Equal(t, tc.want, key)
})
}
}
}

func TestCopilotUsesPiBeforeGitHubCLI(t *testing.T) {
t.Parallel()
cases := []struct {
name string
entry string
env string
want string
}{
{name: "Pi OAuth", entry: `{"type":"oauth","access":"pi-token","refresh":"pi-refresh"}`, want: "pi-token"},
{name: "environment override", entry: `{"type":"oauth","access":"pi-token"}`, env: "env-token", want: "env-token"},
{name: "GitHub CLI fallback", entry: `null`, want: "gh-token"},
{name: "refresh is not access", entry: `{"type":"oauth","refresh":"pi-refresh"}`, want: "gh-token"},
{name: "API key is not OAuth", entry: `{"type":"api_key","access":"wrong-type","key":"pi-key"}`, want: "gh-token"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
source := envSource(map[string]string{"GH_TOKEN": tc.env})
source.ReadFile = func(path string) ([]byte, error) {
if path == filepath.Join(".pi", "agent", "auth.json") {
return []byte(`{"github-copilot":` + tc.entry + `}`), nil
}
return nil, os.ErrNotExist
}
source.LookPath = func(string) (string, error) { return "gh", nil }
source.Run = func(context.Context, string, ...string) ([]byte, error) {
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())
require.NoError(t, err)
assert.Equal(t, tc.want, token)
})
}
}

func TestDotEnvBeatsAStaleEnvironmentKey(t *testing.T) {
home := t.TempDir()
t.Setenv("HERMES_HOME", home)
Expand Down
Loading