Documentation
¶
Overview ¶
Package codex authenticates against the OpenAI Codex (ChatGPT subscription) backend and speaks its Responses API. The OAuth client id, endpoints and redirect URI mirror the Codex CLI, which is what the subscription endpoint accepts; the flow itself is a standard OAuth 2.0 authorization code grant with PKCE (RFC 7636).
Index ¶
- Constants
- Variables
- func AuthorizeURL(state string, pkce *PKCE, callbackPort int) (string, error)
- func CodexCLIAuthPath() string
- func CodexCLIHome() string
- func NewSessionID() string
- func RandomState() (string, error)
- func RedirectURI(port int) string
- type APIError
- type AuthInfo
- type Backend
- type BootstrapOption
- type Claims
- type Client
- func (c *Client) Exchange(ctx context.Context, code string, pkce *PKCE, callbackPort int) (*Token, error)
- func (c *Client) Login(ctx context.Context, callbackPort int, openBrowser bool, announce func(string)) (*LoginResult, error)
- func (c *Client) Refresh(ctx context.Context, refreshToken string) (*Token, error)
- type LoginResult
- type Model
- type PKCE
- type PickerRow
- type Registry
- func (r *Registry) AdvertisedIDs() []string
- func (r *Registry) BootstrapOptions() []BootstrapOption
- func (r *Registry) Lookup(id string) (Model, bool)
- func (r *Registry) Models() []Model
- func (r *Registry) PickerOptions() []PickerRow
- func (r *Registry) Prefix() string
- func (r *Registry) Resolve(name string) (Resolution, bool)
- type Resolution
- type Store
- func (s *Store) Access(ctx context.Context) (accessToken, accountID string, err error)
- func (s *Store) Authenticated() bool
- func (s *Store) NativePath() string
- func (s *Store) Path() string
- func (s *Store) Peek() (*Token, error)
- func (s *Store) Save(token *Token) error
- func (s *Store) Sources() []string
- type StoreOptions
- type Token
Constants ¶
const ( // AuthURL and TokenURL are the OpenAI OAuth endpoints. AuthURL = "https://auth.openai.com/oauth/authorize" TokenURL = "https://auth.openai.com/oauth/token" // ClientID is the public client id of the Codex CLI. ClientID = "app_EMoamEEZ73f0CkXaXp7hrann" // Scopes requests an ID token plus a refresh token. Scopes = "openid email profile offline_access" )
Variables ¶
var Catalog = []Model{ { ID: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol (Codex)", Description: "Frontier coding and research model. Capable at low effort; turn it up for harder work.", ContextLength: 372000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh", "max"}, DefaultEffort: "medium", SupportsImages: true, BehavesAs: "claude-opus-5", }, { ID: "gpt-6-astra", DisplayName: "GPT-6 Astra (Codex)", Description: "OpenAI's most intelligent model: computer use, browsing and software engineering.", ContextLength: 272000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh", "max"}, DefaultEffort: "medium", SupportsImages: true, BehavesAs: "claude-opus-5", }, { ID: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra (Codex)", Description: "Frontier model for complex, long-running work.", ContextLength: 372000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh", "max"}, DefaultEffort: "medium", SupportsImages: true, BehavesAs: "claude-opus-5", }, { ID: "gpt-5.6-luna", DisplayName: "GPT-5.6 Luna (Codex)", Description: "Frontier model for complex, long-running work.", ContextLength: 372000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh", "max"}, DefaultEffort: "medium", SupportsImages: true, BehavesAs: "claude-opus-5", }, { ID: "gpt-5.5", DisplayName: "GPT-5.5 (Codex)", Description: "Frontier model for complex coding, research and real-world work.", ContextLength: 272000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh"}, DefaultEffort: "medium", SupportsImages: true, BehavesAs: "claude-sonnet-5", }, { ID: "gpt-5.3-codex-spark", DisplayName: "GPT-5.3 Codex Spark", Description: "Ultra-fast coding model for quick edits.", ContextLength: 128000, MaxOutput: 128000, ReasoningLevel: []string{"low", "medium", "high", "xhigh"}, DefaultEffort: "medium", SupportsImages: false, BehavesAs: "claude-haiku-4-5", }, }
Catalog is the set of Codex models reachable with a ChatGPT subscription. The ids are the slugs the ChatGPT backend expects verbatim in the request body; availability still depends on the signed-in account's plan, so a model listed here can legitimately be rejected upstream.
var ErrNotAuthenticated = errors.New("codex: not authenticated, run `ccmproxy login codex` or sign in with the Codex CLI")
ErrNotAuthenticated is returned when no Codex credentials can be found.
Functions ¶
func AuthorizeURL ¶
AuthorizeURL builds the URL the user opens to grant access.
func CodexCLIAuthPath ¶
func CodexCLIAuthPath() string
CodexCLIAuthPath reports the Codex CLI credential file, or "" when the home directory cannot be determined.
func CodexCLIHome ¶
func CodexCLIHome() string
CodexCLIHome reports the Codex CLI's configuration directory, honouring the CODEX_HOME override the CLI itself uses.
func NewSessionID ¶
func NewSessionID() string
NewSessionID returns a random RFC 4122 version 4 UUID.
func RandomState ¶
RandomState returns an opaque value for the OAuth state parameter.
func RedirectURI ¶
RedirectURI builds the loopback redirect URI for the given callback port. The registered client only accepts the Codex CLI's port, so callers should stay on the default unless they know better.
Types ¶
type AuthInfo ¶
type AuthInfo struct {
ChatGPTAccountID string `json:"chatgpt_account_id"`
ChatGPTPlanType string `json:"chatgpt_plan_type"`
ChatGPTUserID string `json:"chatgpt_user_id"`
UserID string `json:"user_id"`
}
AuthInfo carries the ChatGPT account details embedded in the ID token.
type Backend ¶
type Backend struct {
BaseURL string
UserAgent string
Originator string
Store *Store
HTTP *http.Client
}
Backend calls the Codex Responses endpoint on behalf of a signed-in ChatGPT account.
func NewBackend ¶
func NewBackend(baseURL, userAgent, originator string, store *Store, transport http.RoundTripper) *Backend
NewBackend wires a backend with a streaming-friendly HTTP client. There is no overall request timeout because a single response can stream for minutes; the caller's context bounds the call instead.
type BootstrapOption ¶
type BootstrapOption struct {
Model string `json:"model"`
Name string `json:"name"`
Description string `json:"description"`
DisabledReason *string `json:"disabled_reason"`
}
BootstrapOption is one entry of the `additional_model_options` array in the Claude Code bootstrap response. The field names are Claude Code's.
type Claims ¶
type Claims struct {
Email string `json:"email"`
Exp int64 `json:"exp"`
Auth AuthInfo `json:"https://api.openai.com/auth"`
}
Claims is the subset of the ID token payload the proxy needs.
func ParseIDToken ¶
ParseIDToken decodes the claims of a JWT without verifying its signature. The token arrives over TLS straight from the issuer's token endpoint, so it is only being read for the account id and plan, never trusted as proof.
type Client ¶
Client performs the OAuth token calls.
func (*Client) Exchange ¶
func (c *Client) Exchange(ctx context.Context, code string, pkce *PKCE, callbackPort int) (*Token, error)
Exchange trades an authorization code for tokens.
func (*Client) Login ¶
func (c *Client) Login(ctx context.Context, callbackPort int, openBrowser bool, announce func(string)) (*LoginResult, error)
Login runs the authorization code + PKCE flow end to end: it starts a loopback callback server, opens the browser, waits for the redirect and exchanges the code for tokens. openBrowser can be disabled for headless machines, where the URL is printed by the caller instead.
type LoginResult ¶
type LoginResult struct {
Token *Token
// AuthorizeURL is exposed so callers can print it when no browser opened.
AuthorizeURL string
}
LoginResult reports the outcome of an interactive login.
type Model ¶
type Model struct {
ID string
DisplayName string
Description string
ContextLength int
MaxOutput int
ReasoningLevel []string
DefaultEffort string
SupportsImages bool
// BehavesAs names the Claude model whose client-side handling Claude
// Code should apply to this one. It is required for a `modelPicker` row:
// a row naming a model the installed version does not know is not
// offered without it. The value only affects the client's own prompt
// profile and effort defaults; the model id sent upstream is unchanged.
BehavesAs string
}
Model describes one Codex model as advertised to Claude Code.
func (Model) ClampEffort ¶
ClampEffort keeps a requested reasoning level only when this model supports it, otherwise returning the closest level it does. An empty effort stays empty, meaning "no preference".
Claude Code offers effort levels based on the model its picker row says to behave as, which can be a level the real model does not have.
type PKCE ¶
type PKCE struct {
Verifier string `json:"code_verifier"`
Challenge string `json:"code_challenge"`
}
PKCE holds a verifier and its derived S256 challenge.
type PickerRow ¶
type PickerRow struct {
// Model is the id to send, taken verbatim; the same value --model takes.
Model string `json:"model"`
// Label is the row title, Description its subtitle.
Label string `json:"label,omitempty"`
Description string `json:"description,omitempty"`
// BehavesAs names a model the installed Claude Code knows, whose
// client-side handling applies. Without it a row for an unknown model
// is not offered at all.
BehavesAs string `json:"behavesAs,omitempty"`
}
PickerRow is one entry of the `modelPicker.options` array in Claude Code's settings.json. The field names and semantics are Claude Code's, not this proxy's.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry resolves client model names to Codex models. It is immutable after construction and safe for concurrent use.
func NewRegistry ¶
NewRegistry builds a registry over the catalog. allow, when non-empty, restricts the catalog to those ids. prefix is an optional namespace clients may use in front of an id (for example "codex/"). variants controls whether per-effort model ids are advertised.
func (*Registry) AdvertisedIDs ¶
AdvertisedIDs lists every model id the proxy adds to the Anthropic model list, including per-effort variants when enabled.
func (*Registry) BootstrapOptions ¶
func (r *Registry) BootstrapOptions() []BootstrapOption
BootstrapOptions renders one bootstrap model option per advertised model.
func (*Registry) PickerOptions ¶
PickerOptions renders one settings.json picker row per advertised model.
func (*Registry) Resolve ¶
func (r *Registry) Resolve(name string) (Resolution, bool)
Resolve matches name against the catalog. The second return value is false when the name is not a Codex model, in which case the request must be passed through to Anthropic untouched.
Accepted spellings, all case-insensitive:
gpt-5.5 the model at its default effort gpt-5.5-high an effort variant gpt-5.5:high the same, colon separated codex/gpt-5.5-high with the configured prefix
type Resolution ¶
type Resolution struct {
// Model is the catalog entry that matched.
Model Model
// Effort is the reasoning effort requested through the model name, empty
// when the name carried none.
Effort string
// Requested is the name exactly as the client sent it.
Requested string
}
Resolution is the outcome of matching a client-supplied model name against the Codex catalog.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store finds, caches and refreshes Codex credentials.
Credentials are looked for in order: an explicitly configured file, this proxy's own file, then the Codex CLI's ~/.codex/auth.json. A refreshed token is written back to whichever file it came from, so signing in with either tool is enough and the two stay in sync.
func NewStore ¶
func NewStore(client *Client, options StoreOptions) *Store
NewStore builds a store from the given options.
func (*Store) Access ¶
Access returns a usable access token together with the account id, refreshing the credential when it is close to expiry.
func (*Store) Authenticated ¶
Authenticated reports whether credentials are available.
func (*Store) NativePath ¶
NativePath reports this proxy's own credential file.
func (*Store) Path ¶
Path reports the file credentials were loaded from, falling back to the file a fresh login would write.
type StoreOptions ¶
type StoreOptions struct {
// Dir is where this proxy keeps its own credential file.
Dir string
// ExplicitPath, when set, is the only file consulted, in whichever
// layout it turns out to be.
ExplicitPath string
// UseCodexCLI enables reading (and keeping in sync) the Codex CLI's
// ~/.codex/auth.json when this proxy has no credentials of its own.
UseCodexCLI bool
}
StoreOptions configures where credentials are looked for.
type Token ¶
type Token struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
AccountID string `json:"account_id"`
Email string `json:"email"`
PlanType string `json:"plan_type,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
LastRefresh time.Time `json:"last_refresh"`
Type string `json:"type"`
}
Token is the credential set persisted for a Codex account.