codex

package
v2.10.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package codex runs models from a ChatGPT subscription through the official codex CLI: model calls go through `codex exec`, and sign-in, account status, rate limits and the model list go through `codex app-server` (JSON-RPC over stdio). Lectern never sees or stores the ChatGPT tokens; the CLI keeps them in its own home (~/.codex).

Index

Constants

View Source
const DefaultBinary = "codex"

DefaultBinary is the command looked up on PATH when no binary is set.

View Source
const ProviderID = "codex"

ProviderID is the registry id of this provider.

Variables

This section is empty.

Functions

func Available

func Available(ctx context.Context, bin string) bool

Available reports whether the CLI is installed and signed in. The answer is kept for availableTTL per binary. A cancelled ctx gives an answer that is not kept.

func ListModels

func ListModels(ctx context.Context, bin string) ([]llm.ModelInfo, error)

ListModels returns the models the signed-in account can use. Tools is set on each, since the CLI runs its own tool loop. Name is the display name, falling back to the id.

func Login

func Login(ctx context.Context, bin string, mode LoginMode) (<-chan LoginEvent, error)

Login starts a sign-in and reports its progress on the returned channel. The channel is closed after a LoginDone or LoginFailed event. Cancelling ctx sends account/login/cancel and reports a LoginFailed whose error says "cancelled". If the account is already signed in, the first event is a LoginDone that says so.

func Logout

func Logout(ctx context.Context, bin string) error

Logout signs the CLI out through the app-server, and falls back to `<bin> logout` when that fails.

func Resolve

func Resolve(bin string) (string, error)

Resolve finds the codex binary: bin as given, or DefaultBinary on PATH when bin is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a running `codex app-server`. One goroutine reads its stdout and hands each response to the request waiting for it; notifications wait in a buffer until WaitNotification asks for them. Methods are safe to call from several goroutines.

func StartAppServer

func StartAppServer(ctx context.Context, bin string) (*Client, error)

StartAppServer starts `<bin> app-server` and completes the initialize handshake. The child is stopped when ctx is cancelled, and by Close.

func (*Client) Close

func (c *Client) Close() error

Close stops the child. It closes stdin, sends SIGTERM to the child's process group, waits up to closeGrace for it to exit, then sends SIGKILL and waits for the exit. Calling Close again does nothing.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method string, params, out any) error

Request sends one JSON-RPC request and decodes its result into out. A JSON-RPC error becomes a Go error that carries the server's message. A nil params is sent as no params at all. out may be nil when the result is not needed.

func (*Client) WaitNotification

func (c *Client) WaitNotification(ctx context.Context, method string, match func(params json.RawMessage) bool) (json.RawMessage, error)

WaitNotification returns the params of the first notification named method for which match is true (nil match accepts any). A notification that arrived before the call is still returned. It fails when ctx ends or the server exits first.

type Credits

type Credits struct {
	HasCredits bool
	Unlimited  bool
	Balance    string // as reported, a decimal string
}

Credits is the account's credit balance, when it has one.

type LoginEvent

type LoginEvent struct {
	Kind   LoginEventKind
	Mode   LoginMode // the flow actually used (never LoginAuto)
	URL    string    // where to sign in
	Code   string    // one-time code (device flow only)
	Opened bool      // a browser was opened for URL
	// AlreadySignedIn marks a LoginDone sent at once because the CLI was
	// signed in before the login started; no sign-in took place.
	AlreadySignedIn bool
	Message         string
	Status          *Status
	Err             error
}

LoginEvent is one step of a sign-in. The channel returned by Login is closed after a LoginDone or LoginFailed event.

type LoginEventKind

type LoginEventKind string

LoginEventKind says what a LoginEvent carries.

const (
	LoginStarted LoginEventKind = "started" // URL (and Code for device) are set
	LoginInfo    LoginEventKind = "info"    // Message is progress text
	LoginDone    LoginEventKind = "done"    // signed in; Status may be filled
	LoginFailed  LoginEventKind = "failed"  // Err is set
)

type LoginMode

type LoginMode int

LoginMode chooses the sign-in flow.

const (
	// LoginAuto picks Browser when a browser can open on this machine
	// (a local display and not an SSH session), else Device.
	LoginAuto LoginMode = iota
	// LoginBrowser opens ChatGPT in a browser on this machine; the CLI
	// listens for the callback on localhost.
	LoginBrowser
	// LoginDevice shows a URL and a one-time code to enter on any device.
	LoginDevice
)

type Options

type Options struct {
	Binary     string                                             // "" -> DefaultBinary
	Cwd        func() string                                      // nil -> os.Getwd
	ListModels func(ctx context.Context) ([]llm.ModelInfo, error) // nil -> built-in fallback list
	Timeout    time.Duration                                      // 0 -> 10 min per call
}

Options configures a Provider. The zero value runs codex from PATH with a 10 minute limit per call and the working directory of the process.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider runs model calls through the codex CLI. It keeps nothing between calls: each Stream starts one `codex exec`, and the CLI holds the login.

func New

func New(o Options) *Provider

New returns a Provider for o.

func (*Provider) ID

func (p *Provider) ID() string

ID returns ProviderID.

func (*Provider) Models

func (p *Provider) Models(ctx context.Context) ([]llm.ModelInfo, error)

Models returns the models the plan offers. The subscription has no per-token price, so the prices are zero and CatalogPriced says a zero means free.

func (*Provider) Stream

func (p *Provider) Stream(ctx context.Context, req llm.Request) (<-chan llm.Event, error)

Stream starts one model call and returns its events. The channel always ends with exactly one EvFinish or EvError, then closes. The call runs in a goroutine, so a failure to start is an EvError too, not a second error path.

type RateLimit

type RateLimit struct {
	Name        string // "5h", "weekly", or the window length in words
	UsedPercent float64
	Window      time.Duration
	ResetsAt    time.Time // zero when unknown
}

RateLimit is one usage window, e.g. the 5-hour and the weekly limit.

type Status

type Status struct {
	Installed bool   // the binary was found and ran
	Binary    string // resolved path, "" when not installed
	Version   string // e.g. "codex-cli 0.163.0"
	LoggedIn  bool
	AuthMode  string // "chatgpt", "apiKey", ... as the CLI reports it
	Email     string
	Plan      string // e.g. "plus", "pro"
	Limits    []RateLimit
	Credits   *Credits // nil when the CLI did not report credits
	Err       error    // a read that failed (status still says what is known)
}

Status is what `/codex status` shows. Fields the CLI did not report stay zero; Err explains why the rest could not be read.

func ReadStatus

func ReadStatus(ctx context.Context, bin string) Status

ReadStatus reports the installed version, the signed-in account, and the rate limits. It does not return an error: a read that fails is put in Status.Err, and the rest of the status is still filled in as far as it goes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL