provider/openai/chatgpt
import "github.com/barevoidco/zelk/core/provider/openai/chatgpt"Package chatgpt signs in with ChatGPT to use the user’s ChatGPT plan for Responses requests, as OpenAI documents for open-source tools (https://developers.openai.com/siwc/token-sharing-open-source).
SignIn runs the browser sign-in and returns the account’s Credentials, which a Store such as File keeps. Source then supplies an access token for each request, renewing it under the store’s lock when it is due, and is the openai adapter’s TokenSource:
model, err := openai.New(chatgpt.BaseURL, openai.WithTokenSource(source), openai.WithPlanUsage())The package reads no environment and opens no browser: the host picks the credential file and shows the sign-in URL.
Constants
Section titled “Constants”const ( // Issuer is OpenAI's OpenID Connect issuer, whose discovery document // names the sign-in endpoints. Issuer = "https://auth.openai.com" // BaseURL is the API that plan access tokens are for: the openai // adapter's base URL, and the token's resource. BaseURL = "https://api.openai.com/v1" // PlanScope is the scope that lets a token use the user's ChatGPT // plan. A user can sign in without granting it. PlanScope = "chatgpt.tokens.use.direct")The OpenAI endpoints of ChatGPT plan usage.
Variables
Section titled “Variables”var ( // ErrAccessDenied: the user declined in the browser. ErrAccessDenied = errors.New("chatgpt: the sign-in was declined") // ErrAccountMismatch: the browser signed in to another account than the // one being signed in to again, or answered for another client. ErrAccountMismatch = errors.New("chatgpt: the sign-in is for another account"))The ways a sign-in can end without credentials.
var ( // ErrNotSignedIn: the store holds no tokens. ErrNotSignedIn = errors.New("chatgpt: not signed in") // ErrNoPlanUsage: the user signed in but didn't let the tokens use // their ChatGPT plan. ErrNoPlanUsage = errors.New("chatgpt: the sign-in does not allow ChatGPT plan usage") // ErrSignInAgain: the issuer won't renew the tokens any more, such as // after the user disconnected the app in ChatGPT's settings. The store // no longer holds them. ErrSignInAgain = errors.New("chatgpt: the sign-in has ended; sign in again"))The ways a Source can’t supply a token without the user signing in.
var ErrRevocationUnconfirmed = errors.New("chatgpt: the issuer did not confirm the sign-out; disconnect the app in ChatGPT's settings")ErrRevocationUnconfirmed means signing out cleared the tokens here, but the issuer didn’t confirm it ended the session. The user can disconnect the app in ChatGPT’s settings.
NewHostID
Section titled “NewHostID”func NewHostID(random io.Reader) (string, error)NewHostID returns a new host ID, a random UUID URN, read from random (normally crypto/rand.Reader).
Example
// A host makes its ID once, from crypto/rand.Reader, and keeps it.id, err := chatgpt.NewHostID(strings.NewReader("0123456789abcdef"))if err != nil { fmt.Println(err) return}fmt.Println(id)// Output: urn:uuid:30313233-3435-4637-b839-616263646566Output:
urn:uuid:30313233-3435-4637-b839-616263646566Revoke
Section titled “Revoke”func Revoke(ctx context.Context, c Credentials, opts ...Option) errorRevoke ends the renewable session in c without changing any Store. Hosts use it to discard tokens from a sign-in that cannot be saved. If revocation cannot be confirmed, the error wraps ErrRevocationUnconfirmed.
Example
// Discard a browser result that could not be saved. Empty credentials// need no issuer request.err := chatgpt.Revoke(context.Background(), chatgpt.Credentials{})fmt.Println(err)// Output: <nil>Output:
<nil>SignOut
Section titled “SignOut”func SignOut(ctx context.Context, store Store, opts ...Option) errorSignOut ends the stored sign-in, as OpenAI documents (https://developers.openai.com/siwc/token-sharing-open-source/profiles-and-sessions#end-the-renewable-session): it revokes the refresh token at the issuer, then clears the tokens, keeping the account, its client and the host ID for the next sign-in. The tokens are cleared even when revocation fails; the error then wraps ErrRevocationUnconfirmed.
Credentials
Section titled “Credentials”type Credentials struct { // Email and Subject identify the account, from its verified ID token. // Email is for display only; Subject is the identity. Email string `json:"email,omitempty"` Issuer string `json:"issuer,omitempty"` Subject string `json:"subject,omitempty"` // ClientID is the client issued at the account's first sign-in, which // later sign-ins and renewals reuse. ClientID string `json:"client_id,omitempty"` // HostID identifies this host to OpenAI (ext_agent_host_id). It is // chosen before the first sign-in and kept across sign-outs; NewHostID // makes one. HostID string `json:"ext_agent_host_id,omitempty"` // PendingSignIn is an opaque host attempt ID. A host sets it before // waiting for a browser, so even signing out without stored tokens can // supersede that attempt. Before replacing the record, the host compares // the stored PendingSignIn with its attempt ID under Update. SignedOut clears it. PendingSignIn string `json:"pending_sign_in,omitempty"` // IDToken is retained in protected storage; displayed authorization // URLs use Email as a hint instead. IDToken string `json:"id_token,omitempty"` AccessToken string `json:"access_token,omitempty"` RefreshToken string `json:"refresh_token,omitempty"` TokenType string `json:"token_type,omitempty"` // Expiry is when AccessToken expires, and RefreshAfter the earliest // time the issuer renews it, if it said. Expiry time.Time `json:"expires_at,omitzero"` RefreshAfter time.Time `json:"earliest_refresh_at,omitzero"` // Scopes are the scopes granted. Scopes []string `json:"scopes,omitempty"` SavedAt time.Time `json:"saved_at,omitzero"`}Credentials is one ChatGPT account’s sign-in on this host: who signed in, the client registered for them, and the tokens. Its JSON form is the credential record OpenAI documents. It holds secrets: keep it out of logs and files others can read.
SignIn
Section titled “SignIn”func SignIn(ctx context.Context, req SignInRequest, opts ...Option) (Credentials, error)SignIn signs in with ChatGPT in the browser, as OpenAI documents for open-source tools (https://developers.openai.com/siwc/token-sharing-open-source/sign-in): an authorization code flow with PKCE and a loopback redirect, then the code exchange and verification of the account’s ID token. It waits for the browser until ctx ends.
The credentials it returns are for the host to store. The user may sign in without letting the app use their ChatGPT plan: check PlanUsage.
Example
A host signs in once, keeps the credentials, and gives the openai adapter a Source of them.
ctx := context.Background()store := chatgpt.NewFile("/path/to/chatgpt.json")stored, err := store.Load(ctx)if err != nil { fmt.Println(err) return}if stored.HostID == "" { if stored.HostID, err = chatgpt.NewHostID(rand.Reader); err != nil { fmt.Println(err) return }}c, err := chatgpt.SignIn(ctx, chatgpt.SignInRequest{ HostID: stored.HostID, AppName: "zelk", Previous: stored, Open: func(_ context.Context, u string) error { fmt.Println("Open", u) // or start the system browser return nil },})if err != nil { fmt.Println(err) return}if err := store.Update(ctx, func(s *chatgpt.Credentials) error { *s = c; return nil }); err != nil { fmt.Println(err) return}source, err := chatgpt.NewSource(store)if err != nil { fmt.Println(err) return}model, err := openai.New(chatgpt.BaseURL, openai.WithTokenSource(source), openai.WithPlanUsage())if err != nil { fmt.Println(err) return}defer model.Close()Credentials.PlanUsage
Section titled “Credentials.PlanUsage”func (c Credentials) PlanUsage() boolPlanUsage reports whether the user let c’s tokens use their ChatGPT plan.
Credentials.SignedIn
Section titled “Credentials.SignedIn”func (c Credentials) SignedIn() boolSignedIn reports whether c holds tokens.
Credentials.SignedOut
Section titled “Credentials.SignedOut”func (c Credentials) SignedOut() CredentialsSignedOut returns c without its tokens or pending sign-in attempt, keeping the account, its client and the host ID for the next sign-in.
type File struct { // contains filtered or unexported fields}File is a Store kept as a secret.Document: in one JSON file, readable only by its owner, or in a keychain item a marker in that file names, beside a lock file of the same name with “.lock” added. It is safe for concurrent use, also by other processes. Load and Update refuse directories owned by another user or writable by group/others, and symlinked credential or lock paths. On Windows they require ACLs that keep other principals out; where neither exist, they fail closed.
NewFile
Section titled “NewFile”func NewFile(path string, opts ...secret.Option) *FileNewFile returns the store kept at path. Its directory is created, private, on the first Update. An existing directory is checked, never chmodded. opts choose a keychain (secret.WithVault, secret.WithNewIn).
File.Document
Section titled “File.Document”func (f *File) Document() *secret.DocumentDocument returns the secret document the sign-in is kept in, for listing it and moving it between a file and a keychain.
File.Load
Section titled “File.Load”func (f *File) Load(ctx context.Context) (Credentials, error)Load reads the credentials. A missing file holds none.
File.Update
Section titled “File.Update”func (f *File) Update(ctx context.Context, fn func(*Credentials) error) errorUpdate locks the file, applies fn to what it holds and writes the result in its place: to a new file, synced, then renamed over it, so a crash leaves either the old credentials or the new.
type Model struct { // Slug is the name to request it by; DisplayName the one to show. Slug, DisplayName string // ContextWindow is the model's context window in tokens, or 0 if the // list doesn't say. ContextWindow int64}Model is a model the signed-in account may use.
OAuthError
Section titled “OAuthError”type OAuthError struct { // StatusCode is the token endpoint's HTTP status; zero for an error // the browser's redirect brought. StatusCode int Code string Description string}OAuthError is an error the issuer answered with (RFC 6749 §§4.1.2.1, 5.2).
OAuthError.Error
Section titled “OAuthError.Error”func (e *OAuthError) Error() stringOption
Section titled “Option”type Option func(*settings)Option configures how the package reaches OpenAI.
WithClock
Section titled “WithClock”func WithClock(now func() time.Time) OptionWithClock injects the clock that token expiry is judged by.
WithHTTPClient
Section titled “WithHTTPClient”func WithHTTPClient(hc *http.Client) OptionWithHTTPClient injects a caller-owned HTTP client. The default ignores proxy environment variables.
WithIssuer
Section titled “WithIssuer”func WithIssuer(issuer string) OptionWithIssuer replaces the OpenID Connect issuer, normally Issuer, whose discovery document names every endpoint the package calls.
SignInRequest
Section titled “SignInRequest”type SignInRequest struct { // HostID identifies this host (NewHostID). The host keeps it across // sign-ins and sign-outs. Required. HostID string // AppName is the name a first sign-in registers the app under, which // the user sees and may change in the browser. Required for a first // sign-in. AppName string // Previous is the account's last record, to sign in to the same // account again with its issued client. Zero for a first sign-in. Previous Credentials // Open shows the user the authorization URL, normally by opening the // system browser. Returning sign-ins use only the saved email as a // hint, so the URL contains no retained ID token. Required. Open func(ctx context.Context, authURL string) error // Listener, if set, takes the browser's redirect: it must be a TCP // listener on 127.0.0.1. SignIn closes it. By default SignIn listens // on 127.0.0.1:1455, else any free port. Listener net.Listener}SignInRequest says what SignIn signs in to.
Source
Section titled “Source”type Source struct { // contains filtered or unexported fields}Source supplies access tokens from a Store, renewing them when they are due: it is the openai adapter’s TokenSource. It reads the store for each token, so a sign-in or sign-out by another process takes effect at once. It is safe for concurrent use, also with Sources of the same store in other processes: renewals happen under the store’s lock.
NewSource
Section titled “NewSource”func NewSource(store Store, opts ...Option) (*Source, error)NewSource returns a Source of store’s credentials.
Source.Close
Section titled “Source.Close”func (s *Source) Close() errorClose closes the idle connections of the HTTP client the Source made for renewals, when it made one rather than being given it (WithHTTPClient). A Source closed and then used again still works, opening connections anew.
Source.Models
Section titled “Source.Models”func (s *Source) Models(ctx context.Context, baseURL string) ([]Model, error)Models lists the models the signed-in account offers for display, in the server’s order, with their context windows, from the model list at baseURL (normally BaseURL). The list is the account’s own and changes with the account (https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference).
Source.Token
Section titled “Source.Token”func (s *Source) Token(ctx context.Context) (string, error)Token returns an access token for a request now. It fails with ErrNotSignedIn, ErrNoPlanUsage or ErrSignInAgain when the user has to sign in. While a due token is still valid, a renewal that fails for any other reason returns the record read under the lock, so a replaced credential is never used as a fallback. Once it has expired, the failure is a *provider.Error: ErrorNotDispatched for a network or server failure, which the driver retries, else ErrorAuth.
type Store interface { // Load returns the stored credentials, zero if there are none. Load(ctx context.Context) (Credentials, error) // Update replaces the stored credentials with what f makes of them, // holding a lock that keeps every other Update of the store, in any // process, waiting. When f fails, nothing is saved. A refresh token // rotates as it is used, so two renewals must never overlap. Update(ctx context.Context, f func(*Credentials) error) error}Store keeps an account’s Credentials.