Skip to content
Open
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
7 changes: 7 additions & 0 deletions docs/oauth-subscriptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ Pick **Sign in with OAuth** → the list of providers that do real OAuth → cho
`ZERO_OAUTH_ALLOW_PRESETS=1`. As of mid-2026 the Codex backend is
Cloudflare-gated: requests from a non-Codex client can still be challenged, and
the `chatgpt-proxy` route in §2 is the conservative fallback.

ChatGPT model availability comes from the authenticated Codex catalog. Open
`/model` or run `/model list` to refresh it; `Ctrl+R` retries from the picker.
If discovery fails, the picker reports the error and labels fallback suggestions
as unverified. Public OpenAI metadata can enrich live models but cannot establish
subscription access. `zero providers models chatgpt` probes the live endpoint
directly and reports failures.
- **Hugging Face — opt-in preset, BYO client_id** — `zero auth login huggingface`
(or `--device` for headless) opens a Hugging Face OAuth flow. The bearer works on
the OpenAI-compatible router at `https://router.huggingface.co/v1` for hundreds
Expand Down
16 changes: 13 additions & 3 deletions internal/cli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -1325,7 +1325,7 @@ func resolveAgentContextWindow(ctx context.Context, registry modelregistry.Regis
if window := modelContextWindow(registry, profile.Model); window > 0 {
return window
}
if window := discoveredModelContextWindow(ctx, profile); window > 0 {
if window := discoveredModelContextWindow(ctx, profile, providermodeldiscovery.Options{}); window > 0 {
return window
}
return modelregistry.AgentContextWindow(0)
Expand All @@ -1334,7 +1334,9 @@ func resolveAgentContextWindow(ctx context.Context, registry modelregistry.Regis
// discoveredModelContextWindow queries the provider's live model list for the
// active model's context window. Returns 0 when the provider isn't catalogued, the
// credential can't be resolved, discovery fails, or the model reports no window.
func discoveredModelContextWindow(ctx context.Context, profile config.ProviderProfile) int {
// options carries transport overrides (HTTP client, catalog URLs); the credential
// resolvers are always derived here from the authenticated profile.
func discoveredModelContextWindow(ctx context.Context, profile config.ProviderProfile, options providermodeldiscovery.Options) int {
descriptor, ok := providercatalog.Get(strings.TrimSpace(profile.CatalogID))
if !ok {
return 0
Expand All @@ -1349,9 +1351,17 @@ func discoveredModelContextWindow(ctx context.Context, profile config.ProviderPr
if strings.TrimSpace(authed.APIKey) == "" && strings.TrimSpace(authed.APIKeyEnv) != "" {
authed.APIKey = strings.TrimSpace(os.Getenv(authed.APIKeyEnv))
}
if providercatalog.NormalizeID(descriptor.ID) == "chatgpt" {
// ChatGPT discovery is a live account probe that fails without the stored
// OAuth bearer, so a keyless subscription profile needs the same login the
// runtime provider uses; a profile with its own key keeps that key instead.
resolver, loginKey := oauthLoginForProfile(authed)
options.OAuthResolver = resolver
options.CodexAccountResolver = providers.CodexAccountResolverForLogin(loginKey)
}
dctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
models, err := providermodeldiscovery.DiscoverCatalog(dctx, descriptor, authed, providermodeldiscovery.Options{})
models, err := providermodeldiscovery.DiscoverCatalog(dctx, descriptor, authed, options)
if err != nil {
return 0
}
Expand Down
70 changes: 70 additions & 0 deletions internal/cli/exec_context_window_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package cli

import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"

"github.com/Twigpine/zero/internal/config"
"github.com/Twigpine/zero/internal/oauth"
"github.com/Twigpine/zero/internal/providermodeldiscovery"
)

// A keyless ChatGPT profile authenticates headless discovery with its stored
// OAuth login: the live account probe only answers with the bearer and the
// account header present, and the discovered context window must come through
// instead of the generic fallback. Also pins that a profile with its own key
// never borrows the subscription login.
func TestDiscoveredModelContextWindowUsesChatGPTLogin(t *testing.T) {
root := t.TempDir()
for _, key := range []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME"} {
t.Setenv(key, root)
}
t.Setenv("ZERO_OAUTH_STORAGE", "file") // an inherited "keyring" would ignore the temp path and hit the OS keychain
t.Setenv("ZERO_OAUTH_TOKENS_PATH", filepath.Join(root, "oauth-tokens.json"))
store, err := oauth.NewStore(oauth.StoreOptions{})
if err != nil {
t.Fatalf("oauth store: %v", err)
}
if err := store.Save(oauth.ProviderKey("chatgpt"), oauth.Token{
AccessToken: "subscription-bearer", ExpiresAt: time.Now().Add(time.Hour), Account: "acct-123",
}); err != nil {
t.Fatalf("seed login: %v", err)
}

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api.json" {
http.Error(w, "metadata unavailable", http.StatusServiceUnavailable)
return
}
if r.Header.Get("Authorization") != "Bearer subscription-bearer" || r.Header.Get("chatgpt-account-id") != "acct-123" {
http.Error(w, "login required", http.StatusUnauthorized)
return
}
_, _ = w.Write([]byte(`{"models":[{"slug":"gpt-live-coder","visibility":"list","context_window":123456}]}`))
}))
defer server.Close()

profile := config.ProviderProfile{
Name: "chatgpt", CatalogID: "chatgpt", ProviderKind: config.ProviderKindOpenAICompatible,
BaseURL: server.URL + "/backend-api/codex", Model: "gpt-live-coder",
}
// Keep the optional metadata enrichment off the network; the live probe is
// what this test is about.
options := providermodeldiscovery.Options{HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json"}
if window := discoveredModelContextWindow(context.Background(), profile, options); window != 123456 {
t.Fatalf("context window = %d, want 123456 from the account-authenticated probe", window)
}

// A sibling profile that resolves its own key must not reach the stored
// login; the endpoint rejects the key, so discovery yields no window.
keyed := profile
keyed.Name = "chatgpt-keyed"
keyed.APIKey = "own-key"
if window := discoveredModelContextWindow(context.Background(), keyed, options); window != 0 {
t.Fatalf("keyed profile context window = %d, want 0 (must not borrow the OAuth login)", window)
}
}
141 changes: 141 additions & 0 deletions internal/providermodeldiscovery/chatgpt_catalog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package providermodeldiscovery

import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/Twigpine/zero/internal/config"
"github.com/Twigpine/zero/internal/providercatalog"
)

func chatGPTTestProfile(baseURL string) (providercatalog.Descriptor, config.ProviderProfile) {
provider, _ := providercatalog.Get("chatgpt")
return provider, config.ProviderProfile{
Name: "subscription", CatalogID: "chatgpt", ProviderKind: config.ProviderKindOpenAICompatible,
BaseURL: baseURL + "/backend-api/codex", APIKey: "test-bearer",
}
}

func TestChatGPTCatalogRequiresLiveDiscovery(t *testing.T) {
for _, response := range []string{"unauthorized", "empty", "non-coding"} {
t.Run(response, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api.json" {
_, _ = w.Write([]byte(`{"openai":{"models":{"gpt-stale":{"id":"gpt-stale","tool_call":true}}}}`))
return
}
switch response {
case "unauthorized":
http.Error(w, "login expired", http.StatusUnauthorized)
case "empty":
_, _ = w.Write([]byte(`{"models":[]}`))
case "non-coding":
_, _ = w.Write([]byte(`{"models":[{"slug":"gpt-image-1"}]}`))
}
}))
defer server.Close()
provider, profile := chatGPTTestProfile(server.URL)
models, err := DiscoverCatalog(context.Background(), provider, profile, Options{
HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json",
})
if err == nil || len(models) != 0 {
t.Fatalf("failed subscription discovery returned models=%v err=%v; public metadata must not claim account availability", modelIDs(models), err)
}
})
}
}

func TestChatGPTCatalogProbesLiveBeforeOptionalMetadata(t *testing.T) {
var liveSeen atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api.json" {
if !liveSeen.Load() {
t.Error("optional public metadata was fetched before the subscription catalog")
}
http.Error(w, "metadata unavailable", http.StatusServiceUnavailable)
return
}
liveSeen.Store(true)
_, _ = w.Write([]byte(`{"models":[{"slug":"gpt-future-coder","visibility":"list","context_window":123456}]}`))
}))
defer server.Close()
provider, profile := chatGPTTestProfile(server.URL)
models, err := DiscoverCatalog(context.Background(), provider, profile, Options{
HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json",
})
if err != nil || len(models) != 1 || models[0].ID != "gpt-future-coder" || models[0].ContextWindow != 123456 {
t.Fatalf("live models lost when metadata failed: models=%v err=%v", models, err)
}
}

func TestChatGPTCatalogBoundsOptionalMetadata(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api.json" {
<-r.Context().Done()
return
}
_, _ = w.Write([]byte(`{"models":[{"slug":"gpt-future-coder"}]}`))
}))
defer server.Close()
provider, profile := chatGPTTestProfile(server.URL)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
models, err := DiscoverCatalog(ctx, provider, profile, Options{
HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json",
})
if err != nil || strings.Join(modelIDs(models), ",") != "gpt-future-coder" {
t.Fatalf("slow metadata prevented live results: models=%v err=%v", modelIDs(models), err)
}
}

func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) {
const oldToken, newToken = "opaque-old-subscription", "opaque-new-subscription"
// A CSI whose final byte is a credential letter consumes that letter, so
// the display would hold a damaged copy; those errors are withheld whole.
withheld := map[string]bool{"\x1b[": true, "\x1b[9": true}
for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m", "\u200b", "\u2060", "\ufeff", "\u202e", "\u00ad", "\u034f", "\ufe0f", "\u180b", "\x1b[", "\x1b[9", "\u009b"} {
t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) {
var requests int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
body := "expired " + oldToken
if requests > 1 {
body = "expired opaque-" + split + "new-subscription and " + oldToken
}
http.Error(w, body, http.StatusUnauthorized)
}))
defer server.Close()
_, profile := chatGPTTestProfile(server.URL)
profile.APIKey = ""
_, err := Discover(context.Background(), profile, Options{
HTTPClient: server.Client(),
OAuthResolver: func(_ context.Context, force bool) (string, string, bool, error) {
token := oldToken
if force {
token = newToken
}
return "Authorization", "Bearer " + token, true, nil
},
})
if err == nil || requests != 2 {
t.Fatalf("expected failed refresh retry: requests=%d err=%v", requests, err)
}
if withheld[split] {
if !errors.Is(err, errWithheldDiscoveryDetails) {
t.Fatalf("damaged OAuth bearer was not withheld: %q", err)
}
return
}
if !strings.Contains(err.Error(), "expired [REDACTED] and [REDACTED]") || strings.Contains(err.Error(), oldToken) || strings.Contains(err.Error(), "new-subscription") {
t.Fatalf("discovery error exposed OAuth bearer: %v", err)
}
})
}
}
51 changes: 40 additions & 11 deletions internal/providermodeldiscovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"github.com/Twigpine/zero/internal/providermodelcatalog"
"github.com/Twigpine/zero/internal/providers/openai"
"github.com/Twigpine/zero/internal/providers/providerio"
"github.com/Twigpine/zero/internal/redaction"
)

const (
Expand Down Expand Up @@ -55,6 +54,24 @@ type Options struct {
}

func DiscoverCatalog(ctx context.Context, provider providercatalog.Descriptor, profile config.ProviderProfile, options Options) ([]Model, error) {
if providercatalog.NormalizeID(provider.ID) == "chatgpt" {
// Public OpenAI metadata cannot establish subscription entitlements. Probe
// the account first and surface failures instead of calling metadata live.
liveModels, err := Discover(ctx, profile, options)
if err != nil {
return nil, err
}
// Enrichment is optional and must not consume the caller's entire discovery
// budget, leaving a working subscription looking unavailable.
metadataCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
catalogModels, _ := fetchCatalogModels(metadataCtx, provider, options)
models := mergeLiveModels(provider, liveModels, catalogModels)
if len(models) == 0 {
return nil, fmt.Errorf("ChatGPT models endpoint returned no visible coding models")
}
return models, nil
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
catalogModels, catalogErr := fetchCatalogModels(ctx, provider, options)
// OpenRouter and OpenGateway publish public live model lists. Probe them even
// without credentials so the picker stays current before a key is entered.
Expand Down Expand Up @@ -269,29 +286,43 @@ func fetchProviderModels(ctx context.Context, endpoint string, profile config.Pr
if client == nil {
client = &http.Client{Timeout: 10 * time.Second}
}
response, err := providerio.SendWithAuthRetry(ctx, client, http.MethodGet, endpoint, nil, auth, options.OAuthResolver, func(request *http.Request) {
resolver := options.OAuthResolver
var resolvedSecrets []string
if resolver != nil {
resolver = func(ctx context.Context, force bool) (string, string, bool, error) {
header, value, ok, err := options.OAuthResolver(ctx, force)
if ok {
// Include both attempts: an upstream may echo either the rejected
// bearer or its replacement in a failure response.
resolvedSecrets = append(resolvedSecrets, value, strings.TrimSpace(strings.TrimPrefix(value, "Bearer ")))
}
return header, value, ok, err
}
}
redact := func(err error) error { return redactDiscoveryError(err, profile, resolvedSecrets...) }
response, err := providerio.SendWithAuthRetry(ctx, client, http.MethodGet, endpoint, nil, auth, resolver, func(request *http.Request) {
request.Header.Set("Accept", "application/json")
if configure != nil {
configure(request)
}
}, 1)
if err != nil {
return nil, redactDiscoveryError(err, profile)
return nil, redact(err)
}
defer response.Body.Close()

// OpenRouter's full catalog is ~0.5MB today; keep headroom for growth.
body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20))
if err != nil {
return nil, redactDiscoveryError(err, profile)
return nil, redact(err)
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, redactDiscoveryError(fmt.Errorf("models endpoint returned %s: %s", response.Status, strings.TrimSpace(string(body))), profile)
return nil, redact(fmt.Errorf("models endpoint returned %s: %s", response.Status, strings.TrimSpace(string(body))))
}

models, err := parseModelsResponse(body)
if err != nil {
return nil, redactDiscoveryError(err, profile)
return nil, redact(err)
}
return models, nil
}
Expand Down Expand Up @@ -714,14 +745,12 @@ func firstDiscoverySource(values ...string) string {
return ""
}

func redactDiscoveryError(err error, profile config.ProviderProfile) error {
func redactDiscoveryError(err error, profile config.ProviderProfile, secrets ...string) error {
if err == nil {
return nil
}
return fmt.Errorf("%s", redaction.RedactString(err.Error(), redaction.Options{ExtraSecretValues: []string{
profile.APIKey,
profile.AuthHeaderValue,
}}))
secrets = append(secrets, profile.APIKey, profile.AuthHeaderValue)
return RedactError(err, secrets...)
}

func displayProviderName(profile config.ProviderProfile) string {
Expand Down
Loading
Loading