Documentation
¶
Overview ¶
pi: auth/oauth/device-code.ts.
pi: auth/helpers.ts.
pi: auth/oauth/anthropic.ts.
Anthropic OAuth flow (Claude Pro/Max). pi uses Node's http.createServer for the OAuth callback server (CLI-only); pig uses net/http directly. The token-exchange HTTP call goes through the anthropicOAuthPostJSON seam so tests can stub it (pi: vi.stubGlobal("fetch")).
pi: auth/oauth/callback-server.ts.
Loopback OAuth redirect handler shared by the browser sign-in flows. pi uses node:http; pig uses net/http directly. The 2026-09-12 port-leak fix (close the raw listener before Server.Close so a close racing Serve startup cannot leak the bind) is baked into Close, and Go's http.Server.Close already drops spare keep-alive connections — pi's chatgpt flow needs an explicit closeAllConnections for the same hazard.
pi: auth/oauth/github-copilot.ts — GitHub Copilot OAuth device flow.
Segment deviations (declared):
- pi's static import of the generated GITHUB_COPILOT_MODELS catalog becomes the githubCopilotKnownModelIDs hook: the catalog lives in package ai, which package auth cannot import (layering); ai/providers/github_copilot.go injects the lookup at init.
- Extra token fields (availableModelIds, enterpriseUrl) ride OAuth credential Extra (pi: open index signature on OAuthCredentials).
- pi's fetch calls go through the githubCopilotOAuthDo transport seam (pi: vi.stubGlobal("fetch") in tests); Date.now() shares the deviceCodeNow fake-clock seam.
pi: auth/oauth/kimi-coding.ts.
Kimi Code (subscription) OAuth flow — RFC 8628 device authorization grant against https://auth.kimi.com with JSON responses. The access token authenticates requests to https://api.kimi.com/coding as an Authorization: Bearer header.
pi: auth/oauth/meta.ts.
Meta Model API OAuth flow ¶
RFC 8628 device authorization grant against https://auth.meta.com (JSON responses). Meta splits identity from API access: the resulting identity token is not accepted for inference, so it is exchanged for a Model API key via the Muse Code key-mint endpoint (minted keys live about a day). The identity token is stored as `refresh` and the minted key as `access`, so the standard OAuth scheduler re-mints the key when it expires with no bespoke renewal machinery. The identity token itself is not renewable (auth.meta.com answers grant_type=refresh_token with 404 and issues no refresh_token), so a 401/403 from mint means the session is dead and the user must sign in again.
pi: auth/oauth/openai-chatgpt.ts.
OpenAI Responses API token sharing through Sign in with ChatGPT. This public-client flow uses no client secret and sends the resulting user access token directly to api.openai.com. pi keeps a flow-local callback server here (it needs the issued client_id from the callback query, and its page texts differ from the shared server's); pig mirrors that 1:1. All OAuth HTTP traffic goes through the chatGPTOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).
pi: auth/oauth/openai-codex.ts.
OpenAI Codex (ChatGPT OAuth) flow. pi uses Node's crypto/http for the callback server (CLI-only); pig uses net/http directly. All OAuth HTTP traffic goes through the codexOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).
pi: auth/oauth/openrouter.ts.
OpenRouter OAuth PKCE flow. OpenRouter exchanges an authorization code for a permanent, user-controlled API key rather than an expiring access/refresh token pair. The callback is handled by a one-shot loopback server on an ephemeral port, raced against a manual prompt so remote/headless sessions can paste the redirect URL when the browser cannot reach the loopback server. All OAuth HTTP traffic goes through the openRouterOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).
pi: auth/oauth/oauth-page.ts.
pi: auth/oauth/xai.ts.
xAI OAuth device-code flow (RFC 8628) against https://auth.x.ai with JSON responses. The access token authenticates requests to https://api.x.ai/v1 as an Authorization: Bearer header.
pi: auth/oauth/pkce.ts.
pi: auth/types.ts.
Index ¶
- func GeneratePKCE() (verifier string, challenge string, err error)
- func GitHubCopilotAvailableModelIDs(credential *OAuthCredential) (ids []string, ok bool)
- func OAuthErrorHTML(message string, details string) string
- func OAuthSuccessHTML(message string) string
- func PollOAuthDeviceCodeFlow[T any](options DeviceCodePollOptions[T]) (T, error)
- func SetGitHubCopilotKnownModelIDs(fn func() map[string]bool)
- type AnthropicOAuth
- func (AnthropicOAuth) IsSubscription() bool
- func (AnthropicOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (AnthropicOAuth) LoginLabel() string
- func (AnthropicOAuth) Name() string
- func (AnthropicOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (AnthropicOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type ApiKeyAuth
- type ApiKeyAuthChecker
- type ApiKeyAuthInput
- type ApiKeyAuthLogin
- type ApiKeyCredential
- type AuthCheck
- type AuthContext
- type AuthEvent
- type AuthInfoLink
- type AuthInteraction
- type AuthOperationOptions
- type AuthPrompt
- type AuthPromptOption
- type AuthResolutionOverrides
- type AuthResult
- type AuthSource
- type AuthType
- type Credential
- type CredentialInfo
- type CredentialStore
- type CredentialType
- type DeviceCodePollOptions
- type DeviceCodePollResult
- type DeviceCodePollStatus
- type GitHubCopilotOAuth
- func (GitHubCopilotOAuth) IsSubscription() bool
- func (GitHubCopilotOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (GitHubCopilotOAuth) LoginLabel() string
- func (GitHubCopilotOAuth) Name() string
- func (GitHubCopilotOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (GitHubCopilotOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type InMemoryCredentialStore
- func (s *InMemoryCredentialStore) Delete(ctx context.Context, providerID string) error
- func (s *InMemoryCredentialStore) List(ctx context.Context) ([]CredentialInfo, error)
- func (s *InMemoryCredentialStore) Modify(ctx context.Context, providerID string, ...) (Credential, error)
- func (s *InMemoryCredentialStore) Read(ctx context.Context, providerID string) (Credential, error)
- type KimiCodingOAuth
- func (KimiCodingOAuth) IsSubscription() bool
- func (KimiCodingOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (KimiCodingOAuth) LoginLabel() string
- func (KimiCodingOAuth) Name() string
- func (KimiCodingOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (KimiCodingOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type LoginOptions
- type MetaOAuth
- func (MetaOAuth) IsSubscription() bool
- func (MetaOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (MetaOAuth) LoginLabel() string
- func (MetaOAuth) Name() string
- func (MetaOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (MetaOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type ModelAuth
- type ModelsError
- type ModelsErrorCode
- type OAuthAuth
- type OAuthCallbackOrManual
- type OAuthCallbackOutcome
- type OAuthCallbackServer
- type OAuthCallbackServerOptions
- type OAuthCredential
- type OAuthCredentials
- type OpenAIChatGPTOAuth
- func (OpenAIChatGPTOAuth) IsSubscription() bool
- func (OpenAIChatGPTOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (OpenAIChatGPTOAuth) LoginLabel() string
- func (OpenAIChatGPTOAuth) Name() string
- func (OpenAIChatGPTOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (OpenAIChatGPTOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type OpenAICodexOAuth
- func (OpenAICodexOAuth) IsSubscription() bool
- func (OpenAICodexOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (OpenAICodexOAuth) LoginLabel() string
- func (OpenAICodexOAuth) Name() string
- func (OpenAICodexOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (OpenAICodexOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type OpenRouterOAuth
- func (OpenRouterOAuth) IsSubscription() bool
- func (OpenRouterOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (OpenRouterOAuth) LoginLabel() string
- func (OpenRouterOAuth) Name() string
- func (OpenRouterOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (OpenRouterOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
- type ProviderAuth
- type XaiOAuth
- func (XaiOAuth) IsSubscription() bool
- func (XaiOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
- func (XaiOAuth) LoginLabel() string
- func (XaiOAuth) Name() string
- func (XaiOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
- func (XaiOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GeneratePKCE ¶
GeneratePKCE produces a PKCE code verifier and S256 challenge (pi: generatePKCE): a 32-byte base64url verifier plus its SHA-256 digest.
func GitHubCopilotAvailableModelIDs ¶
func GitHubCopilotAvailableModelIDs(credential *OAuthCredential) (ids []string, ok bool)
GitHubCopilotAvailableModelIDs reads the account's available model ids from an OAuth credential (pi: credential.availableModelIds). ok is false when the field is absent or malformed — both mean "do not filter".
func OAuthErrorHTML ¶
OAuthErrorHTML is the callback page shown after a failed login (pi: oauthErrorHtml).
func OAuthSuccessHTML ¶
OAuthSuccessHTML is the callback page shown after a completed login (pi: oauthSuccessHtml).
func PollOAuthDeviceCodeFlow ¶
func PollOAuthDeviceCodeFlow[T any](options DeviceCodePollOptions[T]) (T, error)
PollOAuthDeviceCodeFlow runs the RFC 8628 polling loop (pi: pollOAuthDeviceCodeFlow).
func SetGitHubCopilotKnownModelIDs ¶
SetGitHubCopilotKnownModelIDs installs the catalog-membership lookup used by the policy-model filter during login (see the file header for why this is a hook rather than a static reference).
Types ¶
type AnthropicOAuth ¶
type AnthropicOAuth struct{}
AnthropicOAuth is the Claude Pro/Max OAuth auth (pi: anthropicOAuth).
func (AnthropicOAuth) IsSubscription ¶
func (AnthropicOAuth) IsSubscription() bool
func (AnthropicOAuth) Login ¶
func (AnthropicOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow, asking for the method first (pi: login with the method select prompt — browser default, copy code headless).
func (AnthropicOAuth) LoginLabel ¶
func (AnthropicOAuth) LoginLabel() string
func (AnthropicOAuth) Name ¶
func (AnthropicOAuth) Name() string
func (AnthropicOAuth) Refresh ¶
func (AnthropicOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh exchanges the refresh token.
func (AnthropicOAuth) ToAuth ¶
func (AnthropicOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives request auth from a valid credential.
type ApiKeyAuth ¶
type ApiKeyAuth interface {
// Name is a display name, e.g. "Anthropic API key".
Name() string
// Resolve derives auth from the stored credential and/or ambient
// sources, merging per field (credential key ?? env(...), credential env
// ?? env(...)). A nil result means not configured. Resolution is
// provider-scoped; model-specific endpoint preparation happens after
// auth has been resolved.
Resolve(input ApiKeyAuthInput) (*AuthResult, error)
}
ApiKeyAuth is api-key auth: stored key/provider env plus ambient sources (env vars, AWS profiles, ADC files). Ambient-only providers omit the login capability (ApiKeyAuthLogin).
func EnvAPIKeyAuth ¶
func EnvAPIKeyAuth(name string, envVars []string) ApiKeyAuth
EnvAPIKeyAuth is standard api-key auth: a stored credential key wins, otherwise the first set env var resolves. Includes a Login that prompts for the key (pi: envApiKeyAuth; pi's returned object carries resolve and the optional login member — pig expresses the optional member as the ApiKeyAuthLogin capability, satisfied by the same value).
Providers with non-standard resolution (provider env, ambient files, IAM) write their own ApiKeyAuth.
type ApiKeyAuthChecker ¶
type ApiKeyAuthChecker interface {
Check(input ApiKeyAuthInput) (*AuthCheck, error)
}
ApiKeyAuthChecker is the optional side-effect-free availability check capability of an ApiKeyAuth (pi: optional check member). Use it when Resolve may execute commands or other request-time work; when absent, Models checks availability by resolving auth.
type ApiKeyAuthInput ¶
type ApiKeyAuthInput struct {
// Ctx is pi's ctx: the AuthContext for env/file access.
Ctx AuthContext
// Credential is the stored api-key credential, nil when none stored.
Credential *ApiKeyCredential
// Context is pi's signal.
Context context.Context
}
ApiKeyAuthInput is the input of ApiKeyAuth Resolve and Check (pi: { ctx, credential?, signal }).
type ApiKeyAuthLogin ¶
type ApiKeyAuthLogin interface {
Login(ctx context.Context, interaction AuthInteraction) (*ApiKeyCredential, error)
}
ApiKeyAuthLogin is the optional interactive-setup capability of an ApiKeyAuth (pi: optional login member; absent = ambient-only).
type ApiKeyCredential ¶
type ApiKeyCredential struct {
Key string `json:"key,omitempty"`
Env types.ProviderEnv `json:"env,omitempty"`
}
ApiKeyCredential is a stored api-key credential. Env holds provider-scoped environment/config values such as Cloudflare account/gateway ids.
func (*ApiKeyCredential) CredentialType ¶
func (*ApiKeyCredential) CredentialType() CredentialType
func (*ApiKeyCredential) MarshalJSON ¶
func (c *ApiKeyCredential) MarshalJSON() ([]byte, error)
func (*ApiKeyCredential) UnmarshalJSON ¶
func (c *ApiKeyCredential) UnmarshalJSON(data []byte) error
type AuthContext ¶
type AuthContext interface {
// Env resolves one environment variable; ok is false when unset or
// blank.
Env(name string) (value string, ok bool)
// FileExists reports whether a file exists. Supports a leading ~.
FileExists(path string) bool
}
AuthContext is environment access for auth resolution. Injectable for tests.
func DefaultProviderAuthContext ¶
func DefaultProviderAuthContext() AuthContext
DefaultProviderAuthContext returns the ambient AuthContext: env vars from the process environment, file existence via the filesystem (pi reads process.env and node:fs; pig uses os and always supports files).
type AuthEvent ¶
type AuthEvent struct {
Type string `json:"type"`
// info
Message string `json:"message,omitempty"`
Links []AuthInfoLink `json:"links,omitempty"`
// auth_url
URL string `json:"url,omitempty"`
Instructions string `json:"instructions,omitempty"`
// device_code
UserCode string `json:"userCode,omitempty"`
VerificationURI string `json:"verificationUri,omitempty"`
IntervalSeconds *int64 `json:"intervalSeconds,omitempty"`
ExpiresInSeconds *int64 `json:"expiresInSeconds,omitempty"`
}
AuthEvent is one progress notification from a login flow. Type is "info", "auth_url", "device_code", or "progress"; exactly the matching fields are set.
type AuthInfoLink ¶
AuthInfoLink is a link rendered alongside an info event.
type AuthInteraction ¶
type AuthInteraction interface {
Prompt(prompt AuthPrompt) (string, error)
Notify(event AuthEvent)
}
AuthInteraction serves both api-key and OAuth login flows.
Prompt shows one prompt and returns the entered/selected string (select returns the option id); an error means cancel/abort. Per-prompt cancellation uses the prompt context. Notify delivers a non-blocking progress event.
type AuthOperationOptions ¶
type AuthOperationOptions struct{}
AuthOperationOptions carried cancellation in pi; pig passes a Go context at call sites instead.
type AuthPrompt ¶
type AuthPrompt struct {
Type string `json:"type"` // "text" | "secret" | "select" | "manual_code"
Message string `json:"message"`
Placeholder string `json:"placeholder,omitempty"`
Options []AuthPromptOption `json:"options,omitempty"`
}
AuthPrompt is a prompt shown to the user during login. pi attaches a per-prompt AbortSignal so a flow can cancel a pending prompt when an out-of-band event resolves the step; pig hands the prompt's context to the interaction call instead (see AuthInteraction).
type AuthPromptOption ¶
type AuthPromptOption struct {
ID string `json:"id"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
AuthPromptOption is one selectable option of a select prompt.
type AuthResolutionOverrides ¶
type AuthResolutionOverrides struct {
APIKey string
Env types.ProviderEnv
// MinOAuthValidityMs requires this much remaining OAuth-token validity;
// defaults to five minutes.
MinOAuthValidityMs int64
}
AuthResolutionOverrides adjust one auth resolution.
type AuthResult ¶
type AuthResult struct {
Auth ModelAuth
// Env holds provider-scoped environment/config values resolved from
// credentials and ambient context.
Env types.ProviderEnv `json:"env,omitempty"`
// Source is a human-readable label for status UI: "ANTHROPIC_API_KEY",
// "OAuth", "~/.aws/credentials".
Source string `json:"source,omitempty"`
}
AuthResult is the result of resolving auth for a model.
func ResolveProviderAuth ¶
func ResolveProviderAuth(ctx context.Context, source AuthSource, credentials CredentialStore, authContext AuthContext, overrides *AuthResolutionOverrides) (*AuthResult, error)
ResolveProviderAuth resolves auth shared by the Models and the (deferred) image-generation chain collections. A stored credential owns the provider: ambient/env is consulted only when nothing is stored. No silent env fallback after a failed refresh or for a credential type without a matching handler.
type AuthSource ¶
type AuthSource interface {
ID() string
Auth() ProviderAuth
}
AuthSource is the structural provider input of ResolveProviderAuth (pi: { id, auth }).
type Credential ¶
type Credential interface {
CredentialType() CredentialType
}
Credential is one type-tagged credential per provider — the shape of today's auth.json. Concrete types: ApiKeyCredential, OAuthCredential.
func UnmarshalCredential ¶
func UnmarshalCredential(data []byte) (Credential, error)
UnmarshalCredential decodes one credential, dispatching on its "type" field.
type CredentialInfo ¶
type CredentialInfo struct {
ProviderID string `json:"providerId"`
Type CredentialType `json:"type"`
}
CredentialInfo is non-secret credential metadata for account/status enumeration.
type CredentialStore ¶
type CredentialStore interface {
// Read the stored credential, possibly expired. Display/status use;
// resolved request auth comes from Models.GetAuth.
Read(ctx context.Context, providerID string) (Credential, error)
// List stored credential metadata without resolving or exposing secrets.
// Implementations must not execute configured API-key commands while
// listing.
List(ctx context.Context) ([]CredentialInfo, error)
// Modify is the serialized write path. fn sees the current credential
// because correct writes (refresh, login-during-refresh) depend on it;
// return the new credential, or nil to leave the entry unchanged.
// Mutual exclusion is per provider id, cross-process too where the
// backing store supports it (e.g. a file lock). Returns the post-write
// credential; fn errors propagate.
Modify(ctx context.Context, providerID string, fn func(current Credential) (Credential, error)) (Credential, error)
// Delete removes a credential (logout). Implementations serialize this
// against Modify.
Delete(ctx context.Context, providerID string) error
}
CredentialStore is app-owned credential storage, keyed by provider id, one credential per provider. Modify is the only write path, so every mutation is a serialized read-modify-write; Models runs OAuth refresh inside Modify so concurrent requests cannot double-refresh a rotated token. The app persists a credential after login via Modify(providerID, func(Credential) (Credential, error)).
Error semantics: Read returns (nil, nil) for missing entries. Methods fail only on storage failure; Models wraps such errors in a ModelsError with code "auth". Best-effort stores that serve an in-memory view and record persistence errors internally (like coding-agent's AuthStorage) are valid implementations.
type CredentialType ¶
type CredentialType string
CredentialType discriminates stored credentials.
const ( CredentialTypeAPIKey CredentialType = "api_key" CredentialTypeOAuth CredentialType = "oauth" )
type DeviceCodePollOptions ¶
type DeviceCodePollOptions[T any] struct { // IntervalSeconds is the initial poll interval; 0 uses the RFC default. IntervalSeconds int64 // ExpiresInSeconds bounds the whole flow; 0 means no deadline. ExpiresInSeconds int64 WaitBeforeFirstPoll bool Poll func() DeviceCodePollResult[T] // Ctx cancels the wait (pi: signal; pi's cancel message becomes the // ctx-caused error text). Ctx context.Context }
DeviceCodePollOptions bounds one device-code poll loop (pi: OAuthDeviceCodePollOptions; signal → ctx).
type DeviceCodePollResult ¶
type DeviceCodePollResult[T any] struct { Status DeviceCodePollStatus // IntervalSeconds carries the server-provided new interval of a // slow_down response (pi: optional intervalSeconds). IntervalSeconds int64 Message string Value T }
DeviceCodePollResult is one poll callback outcome (pi: OAuthDeviceCodePollResult<T>).
type DeviceCodePollStatus ¶
type DeviceCodePollStatus string
DeviceCodePollStatus discriminates one poll outcome.
const ( DeviceCodePending DeviceCodePollStatus = "pending" DeviceCodeSlowDown DeviceCodePollStatus = "slow_down" DeviceCodeFailed DeviceCodePollStatus = "failed" DeviceCodeComplete DeviceCodePollStatus = "complete" )
type GitHubCopilotOAuth ¶
type GitHubCopilotOAuth struct{}
GitHubCopilotOAuth is the GitHub Copilot subscription OAuth auth (pi: githubCopilotOAuth).
func (GitHubCopilotOAuth) IsSubscription ¶
func (GitHubCopilotOAuth) IsSubscription() bool
func (GitHubCopilotOAuth) Login ¶
func (GitHubCopilotOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
func (GitHubCopilotOAuth) LoginLabel ¶
func (GitHubCopilotOAuth) LoginLabel() string
func (GitHubCopilotOAuth) Name ¶
func (GitHubCopilotOAuth) Name() string
func (GitHubCopilotOAuth) Refresh ¶
func (GitHubCopilotOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
func (GitHubCopilotOAuth) ToAuth ¶
func (GitHubCopilotOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives the credential-specific proxy endpoint for each request (pi: toAuth).
type InMemoryCredentialStore ¶
type InMemoryCredentialStore struct {
// contains filtered or unexported fields
}
InMemoryCredentialStore is the default in-memory credential store. Apps inject persistent stores. Keyed by provider id, one credential per provider; see CredentialStore. Writes are serialized per provider.
func (*InMemoryCredentialStore) Delete ¶
func (s *InMemoryCredentialStore) Delete(ctx context.Context, providerID string) error
Delete removes a credential (logout), serialized against Modify.
func (*InMemoryCredentialStore) List ¶
func (s *InMemoryCredentialStore) List(ctx context.Context) ([]CredentialInfo, error)
List returns stored credential metadata without exposing secrets.
func (*InMemoryCredentialStore) Modify ¶
func (s *InMemoryCredentialStore) Modify(ctx context.Context, providerID string, fn func(current Credential) (Credential, error)) (Credential, error)
Modify is the serialized write path: fn runs under the provider's lock and sees the current credential; returning nil leaves the entry unchanged. The post-write credential is returned.
func (*InMemoryCredentialStore) Read ¶
func (s *InMemoryCredentialStore) Read(ctx context.Context, providerID string) (Credential, error)
Read returns the stored credential, possibly expired; (nil, nil) when missing.
type KimiCodingOAuth ¶
type KimiCodingOAuth struct{}
KimiCodingOAuth is the Kimi Code subscription OAuth auth (pi: kimiCodingOAuth).
func (KimiCodingOAuth) IsSubscription ¶
func (KimiCodingOAuth) IsSubscription() bool
func (KimiCodingOAuth) Login ¶
func (KimiCodingOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow.
func (KimiCodingOAuth) LoginLabel ¶
func (KimiCodingOAuth) LoginLabel() string
func (KimiCodingOAuth) Name ¶
func (KimiCodingOAuth) Name() string
func (KimiCodingOAuth) Refresh ¶
func (KimiCodingOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh exchanges the refresh token.
func (KimiCodingOAuth) ToAuth ¶
func (KimiCodingOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives request auth from a valid credential.
type LoginOptions ¶ added in v1.0.0
type LoginOptions struct {
// GetDeviceId returns the stable ID of this app installation, e.g. sent
// to OpenAI as its agent host ID. Called only by login flows that need
// it, so apps can create the ID on first use and must return the same
// ID on every later call.
GetDeviceId func() string
}
LoginOptions is app-supplied context for OAuth login (pi: LoginOptions).
type MetaOAuth ¶ added in v0.86.1
type MetaOAuth struct{}
MetaOAuth is the Meta (Muse subscription) OAuth auth method (pi: metaOAuth).
func (MetaOAuth) IsSubscription ¶ added in v0.86.1
func (MetaOAuth) Login ¶ added in v0.86.1
func (MetaOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow.
func (MetaOAuth) LoginLabel ¶ added in v0.86.1
func (MetaOAuth) Refresh ¶ added in v0.86.1
func (MetaOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh re-mints the API key from the stored identity token.
type ModelAuth ¶
type ModelAuth struct {
APIKey string `json:"apiKey,omitempty"`
Headers types.ProviderHeaders `json:"headers,omitempty"`
BaseURL string `json:"baseUrl,omitempty"`
}
ModelAuth is the request auth for a single model request. If a value cannot be expressed as APIKey, Headers, or BaseURL, it is provider config, not auth.
type ModelsError ¶
type ModelsError struct {
Code ModelsErrorCode
// contains filtered or unexported fields
}
ModelsError carries a Models error code. Callers surface Error() only, so the underlying reason is folded into the message (pi: withCauseDetail) and remains reachable via Unwrap.
func NewModelsError ¶
func NewModelsError(code ModelsErrorCode, message string, cause error) *ModelsError
NewModelsError builds a ModelsError; cause may be nil.
func (*ModelsError) Error ¶
func (e *ModelsError) Error() string
func (*ModelsError) Unwrap ¶
func (e *ModelsError) Unwrap() error
type ModelsErrorCode ¶
type ModelsErrorCode string
ModelsErrorCode classifies Models failures.
const ( ModelsErrorModelSource ModelsErrorCode = "model_source" ModelsErrorModelValidation ModelsErrorCode = "model_validation" ModelsErrorProvider ModelsErrorCode = "provider" ModelsErrorStream ModelsErrorCode = "stream" ModelsErrorAuth ModelsErrorCode = "auth" ModelsErrorOAuth ModelsErrorCode = "oauth" )
type OAuthAuth ¶
type OAuthAuth interface {
// Name is a display name, e.g. "Anthropic (Claude Pro/Max)".
Name() string
// IsSubscription reports whether access through this auth method is
// backed by a provider subscription (pi: optional isSubscription).
IsSubscription() bool
// LoginLabel is the selector label for the OAuth login option, e.g.
// "Sign in with SuperGrok or X Premium"; empty when none (pi: optional
// loginLabel).
LoginLabel() string
// Login runs the provider-owned login flow.
Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
// Refresh exchanges the refresh token. Network call; errors on failure
// (invalid_grant etc.). Models runs it under the store lock.
Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
// ToAuth derives request auth from a valid credential,
// side-effect-free. Covers per-credential baseUrl (GitHub Copilot).
ToAuth(credential *OAuthCredential) (*ModelAuth, error)
}
OAuthAuth is OAuth auth. The Refresh/ToAuth split lets Models own the locked refresh pattern: Refresh produces a credential, ToAuth derives request auth from whatever credential ends up stored.
type OAuthCallbackOrManual ¶ added in v1.0.0
type OAuthCallbackOrManual[T any] struct { // Type is "callback" or "manual". Type string // Value is the completed callback value when Type is "callback". Value T // Input is the pasted text when Type is "manual". Input string }
OAuthCallbackOrManual is the result of waiting for the browser callback or a pasted code (pi: the { type: "callback", value } | { type: "manual", input } union).
func WaitForCallbackOrManualInput ¶ added in v1.0.0
func WaitForCallbackOrManualInput[T any](interaction AuthInteraction, callback *OAuthCallbackServer[T], message string, placeholder string) (OAuthCallbackOrManual[T], error)
WaitForCallbackOrManualInput waits for the browser callback, or for the user to paste the code or redirect URL when the browser cannot reach the loopback server (for example over SSH). Without a callback server only the manual prompt is used (pi: waitForCallbackOrManualInput). pig's AuthInteraction has no per-prompt abort, so a prompt that returns after the callback settles is simply ignored (declared deviation — the UI layer cancels its own dialog).
type OAuthCallbackOutcome ¶ added in v1.0.0
OAuthCallbackOutcome is one resolution of the callback wait. Cancel resolves with Cancelled set and a zero Value (pi: wait() → undefined).
type OAuthCallbackServer ¶ added in v1.0.0
type OAuthCallbackServer[T any] struct { // contains filtered or unexported fields }
OAuthCallbackServer is one loopback callback listener (pi: OAuthCallbackServer<T>).
func StartOAuthCallbackServer ¶ added in v1.0.0
func StartOAuthCallbackServer[T any](options OAuthCallbackServerOptions[T]) (*OAuthCallbackServer[T], error)
StartOAuthCallbackServer listens and serves the callback route (pi: startOAuthCallbackServer). The listen is synchronous: an occupied port fails the call, and each flow decides whether to degrade to manual input (anthropic/codex catch) or propagate (openrouter).
func (*OAuthCallbackServer[T]) Cancel ¶ added in v1.0.0
func (s *OAuthCallbackServer[T]) Cancel()
Cancel stops waiting for the browser unless a callback is already being completed (pi: cancel).
func (*OAuthCallbackServer[T]) Close ¶ added in v1.0.0
func (s *OAuthCallbackServer[T]) Close()
Close stops waiting (with an error, matching pi) and releases the port (pi: close).
func (*OAuthCallbackServer[T]) OutcomeChan ¶ added in v1.0.0
func (s *OAuthCallbackServer[T]) OutcomeChan() <-chan OAuthCallbackOutcome[T]
OutcomeChan resolves with the single wait outcome (pi: wait()).
func (*OAuthCallbackServer[T]) RedirectURI ¶ added in v1.0.0
func (s *OAuthCallbackServer[T]) RedirectURI() string
RedirectURI is the loopback URL the provider redirects to (pi: redirectUri).
func (*OAuthCallbackServer[T]) Wait ¶ added in v1.0.0
func (s *OAuthCallbackServer[T]) Wait() (T, error)
Wait blocks until the callback completes or the wait is cancelled; a cancelled wait returns the zero value and a nil error (pi: wait() → undefined).
type OAuthCallbackServerOptions ¶ added in v1.0.0
type OAuthCallbackServerOptions[T any] struct { // ProviderName is used on the browser page, for example `OpenAI`. ProviderName string // Host is the address to listen on. Host string // Port is the port to listen on; 0 picks a free port. Port int Path string // RedirectHost is the host in the redirect URI when it differs from // Host, for example `localhost`. RedirectHost string // State is the expected state parameter; empty skips the state check // (pi: omit when the provider does not send one — no provider sends an // empty state, so the empty-string encoding is safe). State string // Complete finishes the sign-in with the received code before the // browser page is sent, so the page can show exchange failures. Pass an // identity function to exchange the code later. Complete func(ctx context.Context, code string) (T, error) // Ctx is pi's signal: aborting cancels the wait ("Login cancelled"), // and an already-cancelled Ctx fails the start. Ctx context.Context // Timeout fails the wait after this long; zero waits indefinitely (pi: // timeoutMs). Timeout time.Duration }
OAuthCallbackServerOptions configures one shared callback server (pi: OAuthCallbackServerOptions<T>).
type OAuthCredential ¶
type OAuthCredential struct {
OAuthCredentials
}
OAuthCredential is a stored canonical OAuth credential.
func (*OAuthCredential) CredentialType ¶
func (*OAuthCredential) CredentialType() CredentialType
func (*OAuthCredential) MarshalJSON ¶
func (c *OAuthCredential) MarshalJSON() ([]byte, error)
func (*OAuthCredential) UnmarshalJSON ¶
func (c *OAuthCredential) UnmarshalJSON(data []byte) error
type OAuthCredentials ¶
type OAuthCredentials struct {
Refresh string `json:"refresh"`
Access string `json:"access"`
// Expires is a Unix timestamp in milliseconds.
Expires int64 `json:"expires"`
Extra map[string]any `json:"-"`
}
OAuthCredentials is the OAuth token data returned by extension compatibility flows; Extra preserves further token fields on roundtrip.
type OpenAIChatGPTOAuth ¶ added in v1.0.0
type OpenAIChatGPTOAuth struct{}
OpenAIChatGPTOAuth is the OpenAI (ChatGPT subscription) OAuth auth (pi: openaiChatGPTOAuth).
func (OpenAIChatGPTOAuth) IsSubscription ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) IsSubscription() bool
func (OpenAIChatGPTOAuth) Login ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow.
func (OpenAIChatGPTOAuth) LoginLabel ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) LoginLabel() string
func (OpenAIChatGPTOAuth) Name ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) Name() string
func (OpenAIChatGPTOAuth) Refresh ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh exchanges the refresh token (pi: refresh).
func (OpenAIChatGPTOAuth) ToAuth ¶ added in v1.0.0
func (OpenAIChatGPTOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives request auth from a valid credential (pi: toAuth).
type OpenAICodexOAuth ¶
type OpenAICodexOAuth struct{}
OpenAICodexOAuth is the OpenAI Codex (ChatGPT Plus/Pro) OAuth auth (pi: openaiCodexOAuth). pi has no loginLabel; LoginLabel stays empty.
func (OpenAICodexOAuth) IsSubscription ¶
func (OpenAICodexOAuth) IsSubscription() bool
func (OpenAICodexOAuth) Login ¶
func (OpenAICodexOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow, dispatching on the method select (pi: login).
func (OpenAICodexOAuth) LoginLabel ¶
func (OpenAICodexOAuth) LoginLabel() string
func (OpenAICodexOAuth) Name ¶
func (OpenAICodexOAuth) Name() string
func (OpenAICodexOAuth) Refresh ¶
func (OpenAICodexOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh exchanges the refresh token (pi: refreshOpenAICodexToken).
func (OpenAICodexOAuth) ToAuth ¶
func (OpenAICodexOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives request auth from a valid credential (pi: toAuth — the access token authenticates as the API key).
type OpenRouterOAuth ¶ added in v1.0.0
type OpenRouterOAuth struct{}
OpenRouterOAuth is the OpenRouter OAuth auth (pi: openRouterOAuth).
func (OpenRouterOAuth) IsSubscription ¶ added in v1.0.0
func (OpenRouterOAuth) IsSubscription() bool
func (OpenRouterOAuth) Login ¶ added in v1.0.0
func (OpenRouterOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow.
func (OpenRouterOAuth) LoginLabel ¶ added in v1.0.0
func (OpenRouterOAuth) LoginLabel() string
func (OpenRouterOAuth) Name ¶ added in v1.0.0
func (OpenRouterOAuth) Name() string
func (OpenRouterOAuth) Refresh ¶ added in v1.0.0
func (OpenRouterOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh is a no-op: the stored credential is a permanent API key (pi: refresh returns the credential unchanged).
func (OpenRouterOAuth) ToAuth ¶ added in v1.0.0
func (OpenRouterOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)
ToAuth derives request auth from a valid credential.
type ProviderAuth ¶
type ProviderAuth struct {
APIKey ApiKeyAuth
OAuth OAuthAuth
}
ProviderAuth is provider auth. At least one of APIKey/OAuth must be present: even ambient-credential providers and keyless local servers provide APIKey auth whose Resolve reports whether the provider is configured.
type XaiOAuth ¶
type XaiOAuth struct{}
XaiOAuth is the xAI (Grok/X subscription) OAuth auth method (pi: xaiOAuth).
func (XaiOAuth) IsSubscription ¶
func (XaiOAuth) Login ¶
func (XaiOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
Login runs the provider-owned login flow.
func (XaiOAuth) LoginLabel ¶
func (XaiOAuth) Refresh ¶
func (XaiOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
Refresh exchanges the refresh token.