codex

package module
v0.147.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 16 Imported by: 2

README

Codex Go SDK

Go Reference Codecov

Embed the Codex app-server in Go workflows.

This SDK speaks JSON-RPC to the codex app-server process. By default it spawns the CLI and communicates over stdio.

Requirements

  • Go 1.25.12 or newer
  • codex available on your PATH

Install

go get github.com/pmenglund/codex-sdk-go

Quickstart

package main

import (
    "context"
    "fmt"
    "log/slog"
    "os"

    "github.com/pmenglund/codex-sdk-go"
)

func main() {
    ctx := context.Background()
    logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
    prompt := "Diagnose the test failure and propose a fix"

    client, err := codex.New(ctx, codex.Options{Logger: logger})
    if err != nil {
        panic(err)
    }
    defer client.Close()

    thread, err := client.StartThread(ctx, codex.ThreadStartOptions{})
    if err != nil {
        panic(err)
    }

    result, err := thread.Run(ctx, prompt, nil)
    if err != nil {
        panic(err)
    }

    fmt.Println(result.FinalResponse)
}

New uses its context.Context for initialization requests (initialize/initialized). After New returns successfully, the spawned app-server lifetime is managed by Close, so canceling the constructor context later does not terminate the process.

Streaming

Use RunStreamed to receive notifications as the turn progresses.

prompt := "Inspect the repo"
stream, err := thread.RunStreamed(ctx, []codex.Input{codex.TextInput(prompt)}, nil)
if err != nil {
    panic(err)
}

defer stream.Close()

for {
    note, err := stream.Next(ctx)
    if err != nil {
		panic(err)
    }
    fmt.Printf("%s\n", note.Method)
	if note.Method == "turn/failed" {
		panic("turn failed")
	}
	if note.Method == "turn/completed" {
		if completed, ok := note.Params.(protocol.TurnCompletedNotification); ok &&
			completed.Turn != nil && completed.Turn.Status == protocol.TurnStatusFailed {
			panic(fmt.Errorf("turn failed: %v", completed.Turn.Error))
		}
		break
    }
}

RunStreamed returns thread-scoped events plus notifications that omit threadId (for example account/session updates) so global events are not silently dropped.

Turn handles

Use StartTurn when you need to steer or interrupt a running turn.

handle, err := thread.StartTurn(ctx, []codex.Input{codex.TextInput("Inspect the repo")}, nil)
if err != nil {
    panic(err)
}

if _, err := handle.Steer(ctx, []codex.Input{codex.TextInput("Focus on tests")}); err != nil {
    panic(err)
}

result, err := handle.Run(ctx)
if err != nil {
    panic(err)
}

fmt.Println(result.FinalResponse)

TurnHandle owns its notification subscription. Call Close if you stop before Run returns.

Choose exactly one consumption style per handle: Run, repeated Next calls, or the stream returned by Stream. Mixing styles or consuming concurrently returns codex.ErrTurnConsumptionMode immediately.

If a turn fails, Run returns both the partial result and a *codex.TurnError. Use errors.Is(err, codex.ErrTurnFailed) to classify the failure and errors.As to inspect its structured details, retry metadata, and raw payload:

result, err := handle.Run(ctx)
if errors.Is(err, codex.ErrTurnFailed) {
    var turnErr *codex.TurnError
    if errors.As(err, &turnErr) {
        fmt.Printf("received %d items before failure: %v\n", len(result.Items), turnErr.Detail)
    }
}

FinalResponse is populated only by completed agentMessage items. Plan, reasoning, and commentary items remain available in Items but are never reported as the final assistant answer.

Canceling or expiring the context passed to Run, RunInputs, or TurnHandle.Run best-effort interrupts the remote turn before returning the original context error. Cleanup is bounded to two seconds. To detach without interrupting remote work, use RunStreamed (or StartTurn plus manual Next) and close only the local stream or handle.

Low-level rpc.Client.SubscribeNotifications buffers at most the requested number of pending notifications (64 by default). If a consumer falls behind, only that iterator closes and Next returns an rpc.NotificationOverflowError; JSON-RPC responses and other subscribers continue normally.

note, err := iterator.Next(ctx)
var overflow *rpc.NotificationOverflowError
if errors.As(err, &overflow) {
    // Events were lost. Increase the capacity, drain faster, and subscribe
    // again; overflow.Capacity reports the exhausted hard limit.
}

Account, models, and threads

High-level helpers wrap common app-server operations without requiring direct JSON-RPC calls.

account, err := client.Account(ctx, codex.AccountOptions{})
models, err := client.ListModels(ctx, codex.ListModelsOptions{})
threads, err := client.ListThreads(ctx, codex.ThreadListOptions{})

Thread list, read, fork, and unarchive helpers return concrete protocol values. List sorting uses protocol.SortDirection and protocol.ThreadSortKey rather than arbitrary strings.

Thread values also expose lifecycle helpers:

if _, err := thread.SetName(ctx, "Investigation"); err != nil {
    panic(err)
}

forked, _, err := thread.Fork(ctx, codex.ThreadForkOptions{})
if err != nil {
    panic(err)
}

_ = forked

For lower-level or less stable protocol features, use client.Client() and the generated rpc package.

Low-level union migration

Discriminated protocol unions are concrete generated wrapper types rather than interface{}. Construct values with functions such as protocol.NewUserInput, inspect the typed Kind, and use RawJSON when a variant-specific payload is needed:

input, err := protocol.NewUserInput(map[string]any{
    "type": "text",
    "text": "Inspect the repository",
})
if err != nil {
    return err
}
if input.Kind() == protocol.UserInputKindText {
    var payload struct {
        Text string `json:"text"`
    }
    if err := json.Unmarshal(input.RawJSON(), &payload); err != nil {
        return err
    }
}

Constructors validate JSON encoding, the required non-empty discriminator, and required-field presence for known variants. Field value types and other schema constraints remain server-validated. Known variants have generated kind constants; a well-formed future discriminator remains round-trippable and reports IsKnown() == false. Existing opaque schemas remain interface{} only through reviewed generator allowlists, and generation fails when a new weak fallback appears. The 31 affected wrappers—including UserInput, ResponseItem, SandboxPolicy, ThreadStatus, and LoginAccountParams—are listed in protocol/unions_gen.go.

Generated protocol declarations use Go initialisms consistently, including MCP, OAuth, ID, URL, and JSON. Older Mcp.../Oauth... spellings and Sanitized...JSON implementation names remain deprecated aliases for a migration window. Prefer canonical declarations such as protocol.MCPServerOAuthLoginParams and canonical methods such as rpc.Client.MCPServerOAuthLogin.

These API changes are currently unreleased and require the first SDK release after v0.145.0; protocol.GeneratedCodexVersion continues to describe the upstream wire schema, not the SDK release number. This API-hardening work also includes Options.CompatibilityPolicy and changes StartLogin to accept JSON-marshalable login parameters; code using unkeyed Options literals, interface method sets, or assigned StartLogin method values must be updated.

Approvals

Configure app-server requests with optional callbacks. Unset callbacks return rpc.ErrServerRequestUnsupported, so adding a future server request does not break existing applications at compile time.

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
client, err := codex.New(ctx, codex.Options{
    Logger:         logger,
    RequestHandler: codex.RejectingApprovalCallbacks(),
})

For custom logic, set only the callbacks your application supports:

callbacks := &codex.ServerRequestCallbacks{
    ApproveFileChange: func(ctx context.Context, request protocol.FileChangeRequestApprovalParams) (*protocol.FileChangeRequestApprovalResponse, error) {
        return &protocol.FileChangeRequestApprovalResponse{
            Decision: protocol.FileChangeApprovalDecisionDecline,
        }, nil
    },
}
client, err := codex.New(ctx, codex.Options{RequestHandler: callbacks})

Options.ApprovalHandler and the broad generated rpc.ServerRequestHandler remain as deprecated compatibility surfaces. Low-level handlers that must implement only selected methods can embed rpc.UnimplementedServerRequestHandler. For methods whose historical Go spelling used non-canonical initialisms, such as McpServerElicitationRequest, implement the exported canonical capability interface (for example, rpc.MCPServerElicitationRequestHandler); dispatch prefers that method over the legacy spelling. The client may invoke different server-request callbacks concurrently, so callbacks that share state must be concurrency-safe.

AutoApproveHandler accepts command, file-change, and permission requests and must only be used in a trusted environment. Its default logs are redacted. If sensitive command and path logging is explicitly required, construct NewUnsafeLoggingAutoApproveHandler(logger) and protect those logs accordingly. Use codex.AutoApproveCallbacks(codex.AutoApproveHandler{Logger: logger}) to attach a safe auto-approver through the preferred callback API. The unsafe handler can be passed to the same adapter when explicitly required.

Codex CLI compatibility

When the SDK spawns codex, it requires the CLI major/minor version to match the generated protocol version; patch differences are accepted. A mismatch, missing binary, or unparseable version returns *codex.CodexCompatibilityError before the process starts. Set CompatibilityPolicy: codex.Warn only after validating compatibility (and provide a logger to see the warning), or codex.Ignore to skip the probe. Custom transports are never probed.

Structured Output

Provide a JSON Schema to constrain the final assistant message.

prompt := "Summarize repo status"
schema := codex.MustJSON(map[string]any{
    "type": "object",
    "properties": map[string]any{
        "summary": map[string]any{"type": "string"},
        "status": map[string]any{"type": "string", "enum": []string{"ok", "action_required"}},
    },
    "required": []string{"summary", "status"},
    "additionalProperties": false,
})

_, err := thread.RunInputs(ctx, []codex.Input{codex.TextInput(prompt)}, &codex.TurnOptions{
    OutputSchema: schema,
})

JSON-typed options

Fields like ApprovalPolicy, SandboxPolicy, Effort, Summary, and OutputSchema accept any JSON-marshalable value. If you already have raw JSON, pass a json.RawMessage (or codex.MustJSON(...)) to avoid double encoding.

For common values, prefer typed constants from this package:

  • codex.ApprovalPolicyNever, codex.ApprovalPolicyOnFailure, codex.ApprovalPolicyOnRequest, codex.ApprovalPolicyUntrusted
  • codex.SandboxModeReadOnly, codex.SandboxModeWorkspaceWrite, codex.SandboxModeDangerFullAccess
  • codex.ReasoningEffortNone, codex.ReasoningEffortMinimal, codex.ReasoningEffortLow, codex.ReasoningEffortMedium, codex.ReasoningEffortHigh, codex.ReasoningEffortXHigh

Inputs and overload errors

Use helpers to build structured inputs:

inputs := []codex.Input{
    codex.TextInput("Inspect this file"),
    codex.MentionInput("AGENTS.md"),
}

Overload classification uses ordinary Go errors:

if codex.IsOverloaded(err) && operationIsIdempotent {
    // Retry according to your caller policy.
}

IsOverloaded classifies structured overload failures; it does not prove that repeating an operation is safe. Base retries on idempotency or an application-level idempotency key. IsRetryable remains as a deprecated alias for source compatibility.

Low-level RPC

Use the RPC client directly for full control.

rpcClient := client.Client()
models, err := rpcClient.ModelList(ctx, protocol.ModelListParams{})

Use checked constructors such as rpc.NewClientChecked, rpc.NewConnTransportChecked, and rpc.NewReplayTransportChecked when a dependency is dynamic. Their legacy counterparts panic immediately on invalid programmer input instead of failing later in a background goroutine.

All outbound writes are serialized through a bounded queue. Call and Notify return when their contexts end; with a legacy rpc.Transport, the underlying write may remain blocked until Close. Implement rpc.ContextTransport when writes themselves must observe cancellation. App-server request handling defaults to four workers and a queue of 64; tune rpc.ClientOptions.ServerRequestWorkers and ServerRequestQueueCapacity when using the low-level client.

Inbound JSON-RPC messages are limited to 8 MiB by default. Set rpc.ClientOptions.MaxMessageBytes to apply a smaller client-side acceptance limit. Built-in line transports retain the 8 MiB allocation ceiling even if the client option is larger. Custom transports return an already allocated string, so they must enforce their own read/allocation limit; the client option then rejects oversized returned values. Oversized messages close the client with an error matching rpc.ErrMessageTooLarge.

Documentation

Overview

Package codex provides an idiomatic Go SDK for the Codex app-server.

The SDK spawns the `codex app-server` process (or uses a custom transport) and exposes a high-level facade for accounts, models, threads, turns, and streaming turn control. For lower-level access, you can reach the JSON-RPC client via (*Codex).Client().

Typical usage:

ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
prompt := "Diagnose the test failure and propose a fix"
client, err := codex.New(ctx, codex.Options{Logger: logger})
if err != nil {
	panic(err)
}
defer client.Close()

The constructor context is used for initialization only. Once New returns successfully, the spawned app-server lifetime is managed by Close.

thread, err := client.StartThread(ctx, codex.ThreadStartOptions{})
if err != nil {
	panic(err)
}

result, err := thread.Run(ctx, prompt, nil)
if err != nil {
	panic(err)
}
fmt.Println(result.FinalResponse)

For a running turn that needs steering or interruption, start a turn handle:

handle, err := thread.StartTurn(ctx, []codex.Input{codex.TextInput("Inspect the repo")}, nil)
if err != nil {
	panic(err)
}
defer handle.Close()
_, err = handle.Steer(ctx, []codex.Input{codex.TextInput("Focus on tests")})
if err != nil {
	panic(err)
}
result, err = handle.Run(ctx)
if err != nil {
	panic(err)
}

Account, model, and thread lifecycle helpers cover common app-server calls:

account, err := client.Account(ctx, codex.AccountOptions{})
models, err := client.ListModels(ctx, codex.ListModelsOptions{})
threads, err := client.ListThreads(ctx, codex.ThreadListOptions{})
_ = account
_ = models
_ = threads

JSON-typed options (approval policies, sandbox policies, output schemas, etc.) accept any JSON-marshalable value. If you already have raw JSON, pass json.RawMessage or codex.MustJSON(...) to avoid double encoding.

For common values, prefer typed constants:

  • codex.ApprovalPolicyNever / codex.ApprovalPolicyOnRequest / ...
  • codex.SandboxModeReadOnly / codex.SandboxModeWorkspaceWrite / ...
  • codex.ReasoningEffortLow / codex.ReasoningEffortMedium / ...

Overload errors can be classified with codex.IsOverloaded. The helper works with wrapped errors, but callers must decide retry safety from the operation's idempotency; classification alone cannot prove that a retry is safe.

A TurnHandle has one notification consumer. Choose Run, repeated Next calls, or Stream; mixing styles returns ErrTurnConsumptionMode. Failed turns return both their partial TurnResult and a *TurnError that matches ErrTurnFailed. FinalResponse is derived only from completed agentMessage items.

App-server requests should normally be configured with Options.RequestHandler and ServerRequestCallbacks. Unset callbacks report rpc.ErrServerRequestUnsupported. Options.ApprovalHandler and the broad rpc.ServerRequestHandler remain deprecated compatibility surfaces.

The protocol package uses canonical Go initialisms and concrete lifecycle response types. Prefer MCP... and OAuth... declarations and the typed thread sort and approval decision values; legacy spellings remain deprecated aliases.

Index

Constants

View Source
const (
	// InputTypeText represents a plain text input.
	InputTypeText = "text"
	// InputTypeImage represents a remote image input.
	InputTypeImage = "image"
	// InputTypeLocalImage represents a local image input.
	InputTypeLocalImage = "localImage"
	// InputTypeAudio represents a remote audio input.
	InputTypeAudio = "audio"
	// InputTypeLocalAudio represents a local audio input.
	InputTypeLocalAudio = "localAudio"
	// InputTypeSkill represents a skill invocation input.
	InputTypeSkill = "skill"
)

Variables

View Source
var ErrOverloaded = errors.New("codex overloaded")

ErrOverloaded identifies retryable overload or server-busy failures.

View Source
var ErrTurnConsumptionMode = errors.New("turn handle already has a consumer")

ErrTurnConsumptionMode identifies attempts to mix Run, Next, and Stream on the same TurnHandle or to consume it concurrently.

View Source
var ErrTurnFailed = errors.New("turn failed")

ErrTurnFailed identifies a terminal turn failure.

Functions

func IsOverloaded

func IsOverloaded(err error) bool

IsOverloaded reports whether err indicates an overload or server-busy failure.

func IsRetryable deprecated

func IsRetryable(err error) bool

IsRetryable reports whether err is classified as an overload failure. It does not determine whether retrying a particular operation is safe.

Deprecated: use IsOverloaded and decide retry safety based on whether the operation is idempotent or has an application-level idempotency key.

Types

type AccountOptions

type AccountOptions struct {
	// RefreshToken requests a proactive token refresh before account data is returned.
	RefreshToken bool
}

AccountOptions configures an account/read request.

type ApprovalCallbackHandler added in v0.147.0

ApprovalCallbackHandler is the stable subset needed to adapt approval policies to ServerRequestCallbacks. Both AutoApproveHandler and UnsafeLoggingAutoApproveHandler implement it.

type ApprovalPolicy

type ApprovalPolicy = string

ApprovalPolicy is a typed alias for common approval policy values.

const (
	ApprovalPolicyNever     ApprovalPolicy = "never"
	ApprovalPolicyOnFailure ApprovalPolicy = "on-failure"
	ApprovalPolicyOnRequest ApprovalPolicy = "on-request"
	ApprovalPolicyUntrusted ApprovalPolicy = "untrusted"
)

type AutoApproveHandler

type AutoApproveHandler struct {
	Logger *slog.Logger
}

AutoApproveHandler accepts every approval request it can. Use it only in a trusted environment. Logger controls redacted approval logging. Command bodies, paths, working directories, and permission payloads are never logged. When Logger is nil, logs are discarded.

func (AutoApproveHandler) AccountChatgptAuthTokensRefresh

AccountChatgptAuthTokensRefresh returns an error for auth refresh requests.

func (AutoApproveHandler) ApplyPatchApproval

ApplyPatchApproval approves legacy patch requests.

func (AutoApproveHandler) AttestationGenerate

AttestationGenerate returns an error for attestation generation requests.

func (AutoApproveHandler) ExecCommandApproval

ExecCommandApproval approves legacy command requests.

func (AutoApproveHandler) ItemCommandExecutionRequestApproval

ItemCommandExecutionRequestApproval approves command execution requests.

func (AutoApproveHandler) ItemFileChangeRequestApproval

ItemFileChangeRequestApproval approves file change requests.

func (AutoApproveHandler) ItemPermissionsRequestApproval

ItemPermissionsRequestApproval approves permission escalation requests.

func (AutoApproveHandler) ItemToolCall

ItemToolCall returns an error for dynamic tool calls.

func (AutoApproveHandler) ItemToolRequestUserInput

ItemToolRequestUserInput returns an error for tool user input prompts.

func (AutoApproveHandler) MCPServerElicitationRequest added in v0.147.0

MCPServerElicitationRequest returns an error for MCP elicitation prompts.

func (AutoApproveHandler) McpServerElicitationRequest deprecated

McpServerElicitationRequest preserves the legacy method spelling.

Deprecated: use MCPServerElicitationRequest.

type Codex

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

Codex is the main entrypoint for the Go SDK.

func New

func New(ctx context.Context, opts Options) (*Codex, error)

New creates a new Codex client and performs the initialize handshake.

func (*Codex) Account

Account returns account state from the app-server.

func (*Codex) ArchiveThread

func (c *Codex) ArchiveThread(ctx context.Context, threadID string) (*protocol.ThreadArchiveResponse, error)

ArchiveThread archives a thread by id.

func (*Codex) CancelLogin

func (c *Codex) CancelLogin(ctx context.Context, loginID string) (*protocol.CancelLoginAccountResponse, error)

CancelLogin cancels an in-progress account login flow.

func (*Codex) Client

func (c *Codex) Client() *rpc.Client

Client exposes the underlying RPC client for low-level access.

func (*Codex) Close

func (c *Codex) Close() error

Close closes the underlying transport.

func (*Codex) CompactThread

func (c *Codex) CompactThread(ctx context.Context, threadID string, opts ThreadCompactOptions) (*protocol.ThreadCompactStartResponse, error)

CompactThread starts compaction for a thread by id.

func (*Codex) ForkThread

func (c *Codex) ForkThread(ctx context.Context, threadID string, opts ThreadForkOptions) (*Thread, protocol.ThreadForkResponse, error)

ForkThread forks a thread by id and returns the newly forked thread.

func (*Codex) ListModels

func (c *Codex) ListModels(ctx context.Context, opts ListModelsOptions) (*protocol.ModelListResponse, error)

ListModels returns available models from the app-server.

func (*Codex) ListThreads

func (c *Codex) ListThreads(ctx context.Context, opts ThreadListOptions) (*protocol.ThreadListResponse, error)

ListThreads returns persisted threads visible to the app-server.

func (*Codex) Logout

Logout logs out the current account.

func (*Codex) ReadThread

func (c *Codex) ReadThread(ctx context.Context, threadID string, opts ThreadReadOptions) (*protocol.ThreadReadResponse, error)

ReadThread reads a persisted thread by id.

func (*Codex) ResumeThread

func (c *Codex) ResumeThread(ctx context.Context, options ThreadResumeOptions) (*Thread, error)

ResumeThread resumes an existing thread.

func (*Codex) SetThreadName

func (c *Codex) SetThreadName(ctx context.Context, threadID, name string) (*protocol.ThreadSetNameResponse, error)

SetThreadName sets the display name for a thread by id.

func (*Codex) StartLogin

func (c *Codex) StartLogin(ctx context.Context, params any) (*protocol.LoginAccountResponse, error)

StartLogin starts an app-server account login flow using JSON-marshalable protocol login params.

func (*Codex) StartThread

func (c *Codex) StartThread(ctx context.Context, options ThreadStartOptions) (*Thread, error)

StartThread starts a new thread using the app-server.

func (*Codex) UnarchiveThread

func (c *Codex) UnarchiveThread(ctx context.Context, threadID string) (*protocol.ThreadUnarchiveResponse, error)

UnarchiveThread unarchives a thread by id.

type CodexCompatibilityError added in v0.145.0

type CodexCompatibilityError struct {
	Path             string
	RuntimeVersion   string
	GeneratedVersion string
	GeneratedCommit  string
	Reason           string
	Hint             string
	Cause            error
}

CodexCompatibilityError reports why a spawned Codex CLI could not be proven compatible with the generated protocol package.

func (*CodexCompatibilityError) Error added in v0.145.0

func (e *CodexCompatibilityError) Error() string

func (*CodexCompatibilityError) Unwrap added in v0.145.0

func (e *CodexCompatibilityError) Unwrap() error

Unwrap exposes a version-probe failure, when present.

type CompatibilityPolicy added in v0.145.0

type CompatibilityPolicy uint8

CompatibilityPolicy controls spawned Codex CLI version validation.

const (
	// RequireMajorMinor requires the runtime and generated protocol to have the
	// same major and minor version. Patch differences are allowed.
	RequireMajorMinor CompatibilityPolicy = iota
	// Warn logs compatibility failures and continues. Supply Options.Logger to
	// observe the warning.
	Warn
	// Ignore disables the Codex CLI version probe.
	Ignore
)

type Input

type Input struct {
	// Type must be one of the InputType* constants.
	Type         string                 `json:"type"`
	Text         string                 `json:"text,omitempty"`
	TextElements []protocol.TextElement `json:"text_elements,omitempty"`
	URL          string                 `json:"url,omitempty"`
	Path         string                 `json:"path,omitempty"`
	Name         string                 `json:"name,omitempty"`
}

Input represents a structured user input message.

func AudioInput added in v0.147.0

func AudioInput(url string) Input

AudioInput creates a remote audio input entry.

func ImageInput

func ImageInput(url string) Input

ImageInput creates a remote image input entry.

func LocalAudioInput added in v0.147.0

func LocalAudioInput(path string) Input

LocalAudioInput creates a local audio input entry.

func LocalImageInput

func LocalImageInput(path string) Input

LocalImageInput creates a local image input entry.

func MentionInput

func MentionInput(name string) Input

MentionInput creates a text input containing a single mention placeholder.

func SkillInput

func SkillInput(name, path string) Input

SkillInput creates a skill input entry.

func TextInput

func TextInput(text string) Input

TextInput creates a text input entry.

type ListModelsOptions

type ListModelsOptions struct {
	// Cursor continues listing after a previous response cursor.
	Cursor string
	// IncludeHidden includes models hidden from the default picker list.
	IncludeHidden *bool
	// Limit caps the number of models returned by the app-server.
	Limit *int
}

ListModelsOptions configures a model/list request.

type Options

type Options struct {
	// Transport overrides the default stdio spawn.
	Transport rpc.Transport

	// Spawn controls how the default stdio process is launched.
	Spawn SpawnOptions

	// Logger receives SDK logs. If nil, logging is disabled.
	Logger *slog.Logger

	// ClientInfo identifies this SDK to the app-server.
	ClientInfo protocol.ClientInfo

	// ApprovalHandler handles server approval requests.
	//
	// Deprecated: use RequestHandler. ApprovalHandler requires the broad legacy
	// rpc.ServerRequestHandler interface.
	//lint:ignore SA1019 retained for source compatibility during the deprecation window
	ApprovalHandler rpc.ServerRequestHandler

	// RequestHandler provides optional, forward-compatible app-server callbacks.
	// It conflicts with ApprovalHandler when both are configured. The client may
	// invoke different callbacks concurrently, so callbacks that share state must
	// synchronize access to it.
	RequestHandler *ServerRequestCallbacks

	// CompatibilityPolicy controls validation of a spawned Codex CLI. The zero
	// value, RequireMajorMinor, rejects binaries whose major/minor version cannot
	// be verified against the generated protocol. Custom transports are not probed.
	CompatibilityPolicy CompatibilityPolicy
}

Options configures the Codex client.

type RawJSON

type RawJSON = json.RawMessage

RawJSON represents a pre-serialized JSON value.

func JSON

func JSON(value any) (RawJSON, error)

JSON marshals a value into RawJSON.

func MustJSON

func MustJSON(value any) RawJSON

MustJSON marshals a value into RawJSON and panics on error.

type ReasoningEffort

type ReasoningEffort = protocol.ReasoningEffort

ReasoningEffort is a typed alias for standard effort values.

const (
	ReasoningEffortNone    ReasoningEffort = "none"
	ReasoningEffortMinimal ReasoningEffort = "minimal"
	ReasoningEffortLow     ReasoningEffort = "low"
	ReasoningEffortMedium  ReasoningEffort = "medium"
	ReasoningEffortHigh    ReasoningEffort = "high"
	ReasoningEffortXHigh   ReasoningEffort = "xhigh"
)

type RejectingApprovalHandler added in v0.145.0

type RejectingApprovalHandler struct{}

RejectingApprovalHandler rejects approval requests and returns errors for interactive requests that require an application-specific policy. Its zero value is ready for use.

func (RejectingApprovalHandler) AccountChatgptAuthTokensRefresh added in v0.145.0

func (RejectingApprovalHandler) ApplyPatchApproval added in v0.145.0

func (RejectingApprovalHandler) AttestationGenerate added in v0.145.0

func (RejectingApprovalHandler) ExecCommandApproval added in v0.145.0

func (RejectingApprovalHandler) ItemFileChangeRequestApproval added in v0.145.0

func (RejectingApprovalHandler) ItemPermissionsRequestApproval added in v0.145.0

func (RejectingApprovalHandler) ItemToolCall added in v0.145.0

func (RejectingApprovalHandler) ItemToolRequestUserInput added in v0.145.0

func (RejectingApprovalHandler) McpServerElicitationRequest deprecated added in v0.145.0

McpServerElicitationRequest preserves the legacy method spelling.

Deprecated: use MCPServerElicitationRequest.

type SandboxMode

type SandboxMode = protocol.SandboxMode

SandboxMode is a typed alias for simple sandbox mode values.

const (
	SandboxModeReadOnly         SandboxMode = protocol.SandboxModeReadOnly
	SandboxModeWorkspaceWrite   SandboxMode = protocol.SandboxModeWorkspaceWrite
	SandboxModeDangerFullAccess SandboxMode = protocol.SandboxModeDangerFullAccess
)

type ServerRequestCallbacks added in v0.147.0

type ServerRequestCallbacks struct {
	// RefreshAuthTokens handles account/chatgptAuthTokens/refresh.
	RefreshAuthTokens func(context.Context, protocol.ChatgptAuthTokensRefreshParams) (*protocol.ChatgptAuthTokensRefreshResponse, error)
	// ApprovePatch handles the legacy applyPatchApproval request.
	ApprovePatch func(context.Context, protocol.ApplyPatchApprovalParams) (*protocol.ApplyPatchApprovalResponse, error)
	// GenerateAttestation handles attestation/generate.
	GenerateAttestation func(context.Context, protocol.AttestationGenerateParams) (*protocol.AttestationGenerateResponse, error)
	// ApproveCommand handles the legacy execCommandApproval request.
	ApproveCommand func(context.Context, protocol.ExecCommandApprovalParams) (*protocol.ExecCommandApprovalResponse, error)
	// ApproveCommandExecution handles item/commandExecution/requestApproval.
	ApproveCommandExecution func(context.Context, protocol.CommandExecutionRequestApprovalParams) (*protocol.CommandExecutionRequestApprovalResponse, error)
	// ApproveFileChange handles item/fileChange/requestApproval.
	ApproveFileChange func(context.Context, protocol.FileChangeRequestApprovalParams) (*protocol.FileChangeRequestApprovalResponse, error)
	// ApprovePermissions handles item/permissions/requestApproval.
	ApprovePermissions func(context.Context, protocol.PermissionsRequestApprovalParams) (*protocol.PermissionsRequestApprovalResponse, error)
	// CallTool handles item/tool/call.
	CallTool func(context.Context, protocol.DynamicToolCallParams) (*protocol.DynamicToolCallResponse, error)
	// RequestUserInput handles item/tool/requestUserInput.
	RequestUserInput func(context.Context, protocol.ToolRequestUserInputParams) (*protocol.ToolRequestUserInputResponse, error)
	// RequestMCPServerElicitation handles mcpServer/elicitation/request.
	RequestMCPServerElicitation func(context.Context, protocol.MCPServerElicitationRequestParams) (*protocol.MCPServerElicitationRequestResponse, error)
}

ServerRequestCallbacks is a forward-compatible set of optional callbacks for requests initiated by the app-server. Unset callbacks report rpc.ErrServerRequestUnsupported. The client may invoke different callbacks concurrently; callbacks that share state must synchronize access to it.

func AutoApproveCallbacks added in v0.147.0

func AutoApproveCallbacks(handler ApprovalCallbackHandler) *ServerRequestCallbacks

AutoApproveCallbacks adapts the approval methods of handler to the preferred optional-callback API. Non-approval server requests remain unsupported.

func RejectingApprovalCallbacks added in v0.147.0

func RejectingApprovalCallbacks() *ServerRequestCallbacks

RejectingApprovalCallbacks returns preferred optional callbacks that reject command, patch, file-change, and permission approval requests.

func (ServerRequestCallbacks) AccountChatgptAuthTokensRefresh added in v0.147.0

func (ServerRequestCallbacks) ApplyPatchApproval added in v0.147.0

func (ServerRequestCallbacks) AttestationGenerate added in v0.147.0

func (ServerRequestCallbacks) ExecCommandApproval added in v0.147.0

func (ServerRequestCallbacks) ItemCommandExecutionRequestApproval added in v0.147.0

func (ServerRequestCallbacks) ItemFileChangeRequestApproval added in v0.147.0

func (ServerRequestCallbacks) ItemPermissionsRequestApproval added in v0.147.0

func (ServerRequestCallbacks) ItemToolCall added in v0.147.0

func (ServerRequestCallbacks) ItemToolRequestUserInput added in v0.147.0

func (ServerRequestCallbacks) MCPServerElicitationRequest added in v0.147.0

func (ServerRequestCallbacks) McpServerElicitationRequest deprecated added in v0.147.0

McpServerElicitationRequest preserves the legacy method spelling.

Deprecated: use MCPServerElicitationRequest.

type SpawnOptions

type SpawnOptions struct {
	// CodexPath is the path to the codex binary (defaults to "codex").
	CodexPath string
	// ConfigOverrides are passed as --config key=value flags.
	ConfigOverrides []string
	// ExtraArgs are appended to the command line.
	ExtraArgs []string
	// Stderr captures stderr from the codex process (defaults to os.Stderr).
	Stderr io.Writer
}

SpawnOptions configures the spawned codex app-server process.

type Thread

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

Thread represents an active conversation thread.

func (*Thread) Archive

Archive archives this thread.

func (*Thread) Compact

Compact starts compaction for this thread.

func (*Thread) Fork

Fork forks this thread and returns the newly forked thread.

func (*Thread) ID

func (t *Thread) ID() string

ID returns the thread id.

func (*Thread) Read

Read reads this thread from the app-server.

func (*Thread) Run

func (t *Thread) Run(ctx context.Context, prompt string, opts *TurnOptions) (*TurnResult, error)

Run sends a text prompt and waits for the turn to finish.

func (*Thread) RunInputs

func (t *Thread) RunInputs(ctx context.Context, inputs []Input, opts *TurnOptions) (*TurnResult, error)

RunInputs sends structured inputs and waits for the turn to finish. If ctx is canceled or expires, it best-effort interrupts the remote turn before returning the original context error. Use RunStreamed to retain manual control over whether remote work is interrupted.

func (*Thread) RunStreamed

func (t *Thread) RunStreamed(ctx context.Context, inputs []Input, opts *TurnOptions) (*TurnStream, error)

RunStreamed sends structured inputs and returns a streaming iterator. The iterator includes thread-scoped events and any notifications that omit threadId (for example account/session updates).

func (*Thread) SetName

func (t *Thread) SetName(ctx context.Context, name string) (*protocol.ThreadSetNameResponse, error)

SetName sets the display name for this thread.

func (*Thread) StartTurn

func (t *Thread) StartTurn(ctx context.Context, inputs []Input, opts *TurnOptions) (*TurnHandle, error)

StartTurn sends structured inputs and returns a handle for the running turn.

func (*Thread) Unarchive

Unarchive unarchives this thread.

type ThreadCompactOptions

type ThreadCompactOptions struct{}

ThreadCompactOptions configures a thread/compact/start request.

type ThreadForkOptions

type ThreadForkOptions struct {
	Model                 string
	ModelProvider         string
	ServiceTier           string
	LastTurnID            string
	Cwd                   string
	ApprovalPolicy        any
	Sandbox               any
	Config                map[string]any
	BaseInstructions      string
	DeveloperInstructions string
	Ephemeral             *bool
	// Deprecated: exclude turns is no longer supported by the app-server protocol.
	ExcludeTurns *bool
}

ThreadForkOptions configures a thread/fork request.

type ThreadListOptions

type ThreadListOptions struct {
	Archived *bool
	Cursor   string
	Cwd      any
	// IsPinned is retained for source compatibility with Codex versions before
	// 0.147. Codex 0.147 replaces pinned-thread organization with sections.
	//
	// Deprecated: use SectionID or Unsectioned.
	IsPinned       *bool
	Limit          *int
	ModelProviders []string
	SearchTerm     string
	// SectionID limits results to one persisted section. It cannot be combined
	// with Unsectioned.
	SectionID     string
	SortDirection protocol.SortDirection
	SortKey       protocol.ThreadSortKey
	SourceKinds   []protocol.ThreadSourceKind
	// Unsectioned limits results to threads that do not belong to a section. It
	// cannot be combined with SectionID.
	Unsectioned    bool
	UseStateDBOnly *bool
}

ThreadListOptions configures a thread/list request.

type ThreadReadOptions

type ThreadReadOptions struct {
	IncludeTurns bool
}

ThreadReadOptions configures a thread/read request.

type ThreadResumeHistoryElem deprecated

type ThreadResumeHistoryElem = json.RawMessage

ThreadResumeHistoryElem keeps the old unstable history field compilable for callers, but the current app-server protocol no longer accepts history-based thread resume.

Deprecated: history-based thread resume is no longer supported.

type ThreadResumeOptions

type ThreadResumeOptions struct {
	// ThreadID resumes a persisted thread by id.
	ThreadID string
	// History is retained for source compatibility, but the current app-server
	// protocol no longer supports history-based resume. Passing History returns an
	// error from toParams.
	//
	// Deprecated: history-based thread resume is no longer supported.
	History []ThreadResumeHistoryElem
	// Path is retained for source compatibility, but the current app-server
	// protocol no longer supports path-based resume. Passing Path returns an error
	// from toParams.
	//
	// Deprecated: path-based thread resume is no longer supported.
	Path          string
	Model         string
	ModelProvider string
	ServiceTier   string
	Cwd           string
	// ApprovalPolicy is marshaled as JSON and sent as "approvalPolicy".
	// Prefer ApprovalPolicy* constants for simple policies.
	ApprovalPolicy any
	// Sandbox is marshaled as JSON and sent as "sandbox".
	// Prefer SandboxMode* constants for simple policies.
	Sandbox               any
	Config                map[string]any
	BaseInstructions      string
	DeveloperInstructions string
}

ThreadResumeOptions configures a thread/resume request.

type ThreadStartOptions

type ThreadStartOptions struct {
	Model         string
	ModelProvider string
	ServiceTier   string
	Cwd           string
	// ApprovalPolicy is marshaled as JSON and sent as "approvalPolicy".
	// Prefer ApprovalPolicy* constants for simple policies.
	ApprovalPolicy any
	// SandboxPolicy is marshaled as JSON and sent as "sandbox".
	// Prefer SandboxMode* constants for simple policies.
	SandboxPolicy         any
	Config                map[string]any
	ServiceName           string
	BaseInstructions      string
	DeveloperInstructions string
	Ephemeral             *bool
	// ExperimentalRawEvents is retained for source compatibility, but the current
	// app-server protocol no longer supports this option. Setting it returns an
	// error from toParams.
	//
	// Deprecated: raw events are no longer supported by the app-server protocol.
	ExperimentalRawEvents bool
}

ThreadStartOptions configures a thread/start request.

type TurnError added in v0.147.0

type TurnError struct {
	Result    *TurnResult
	Method    string
	Detail    *protocol.TurnError
	WillRetry bool
	Raw       json.RawMessage
}

TurnError describes a terminal turn failure and retains the partial result and complete structured wire details available at failure time.

func (*TurnError) Error added in v0.147.0

func (e *TurnError) Error() string

func (*TurnError) Is added in v0.147.0

func (e *TurnError) Is(target error) bool

Is allows errors.Is(err, ErrTurnFailed).

type TurnHandle

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

TurnHandle controls a running turn.

func (*TurnHandle) Close

func (h *TurnHandle) Close()

Close releases the handle's notification subscription.

func (*TurnHandle) ID added in v0.145.0

func (h *TurnHandle) ID() string

ID returns the server-assigned turn ID when it is known.

func (*TurnHandle) Interrupt

Interrupt interrupts the active turn.

func (*TurnHandle) Next

func (h *TurnHandle) Next(ctx context.Context) (rpc.Notification, error)

Next returns the next notification for this turn and updates the handle state.

func (*TurnHandle) Run

func (h *TurnHandle) Run(ctx context.Context) (*TurnResult, error)

Run waits for this turn to complete and returns its aggregated result. It best-effort interrupts remote work after context cancellation, deadline, or notification overflow; cleanup is bounded and the original error is returned.

func (*TurnHandle) Steer

func (h *TurnHandle) Steer(ctx context.Context, inputs []Input) (*protocol.TurnSteerResponse, error)

Steer sends additional input to the active turn.

func (*TurnHandle) Stream

func (h *TurnHandle) Stream() (*TurnStream, error)

Stream returns the handle's notification stream.

type TurnOptions

type TurnOptions struct {
	ClientUserMessageID string
	Cwd                 string
	// ApprovalPolicy is marshaled as JSON and sent as "approvalPolicy".
	// Prefer ApprovalPolicy* constants for simple policies.
	ApprovalPolicy any
	// SandboxPolicy is marshaled as JSON and sent as "sandboxPolicy".
	// Prefer SandboxMode* constants for simple policies.
	SandboxPolicy any
	Model         string
	ServiceTier   string
	// Effort is marshaled as JSON and sent as "effort".
	// Prefer ReasoningEffort* constants for standard values.
	Effort any
	// Summary is marshaled as JSON and sent as "summary".
	Summary any
	// OutputSchema is marshaled as JSON and sent as "outputSchema".
	OutputSchema any
	// CollaborationMode is retained for source compatibility, but the current
	// app-server protocol no longer supports this option. Setting it returns an
	// error from buildTurnParams.
	//
	// Deprecated: collaboration mode is no longer supported by the app-server protocol.
	CollaborationMode any
}

TurnOptions configures a turn/start request.

type TurnResult

type TurnResult struct {
	TurnID        string
	Status        string
	ErrorMessage  string
	Notifications []rpc.Notification
	// Items holds the raw JSON payloads for completed items.
	Items         []json.RawMessage
	FinalResponse string
	TokenUsage    *protocol.ThreadTokenUsage
	CreatedAt     *time.Time
	CompletedAt   *time.Time
}

TurnResult aggregates notifications for a completed turn.

type TurnStream

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

TurnStream iterates notifications for a running turn. Notifications that omit threadId are still emitted to avoid dropping global events sent during the turn.

func (*TurnStream) Close

func (s *TurnStream) Close()

Close stops the iterator.

func (*TurnStream) Next

func (s *TurnStream) Next(ctx context.Context) (rpc.Notification, error)

Next returns the next notification for this turn. Notifications without threadId are treated as belonging to the active stream.

type UnsafeLoggingAutoApproveHandler added in v0.145.0

type UnsafeLoggingAutoApproveHandler struct {
	AutoApproveHandler
}

UnsafeLoggingAutoApproveHandler opts into logging sensitive approval payloads. Use only when logs have access controls appropriate for command text and paths.

func NewUnsafeLoggingAutoApproveHandler added in v0.145.0

func NewUnsafeLoggingAutoApproveHandler(logger *slog.Logger) UnsafeLoggingAutoApproveHandler

NewUnsafeLoggingAutoApproveHandler returns an auto-approver that logs sensitive command and path details.

func (UnsafeLoggingAutoApproveHandler) ApplyPatchApproval added in v0.145.0

func (UnsafeLoggingAutoApproveHandler) ExecCommandApproval added in v0.145.0

func (UnsafeLoggingAutoApproveHandler) ItemCommandExecutionRequestApproval added in v0.145.0

func (UnsafeLoggingAutoApproveHandler) ItemFileChangeRequestApproval added in v0.145.0

func (UnsafeLoggingAutoApproveHandler) ItemPermissionsRequestApproval added in v0.145.0

Directories

Path Synopsis
examples
approvals command
lifecycle command
low_level_rpc command
quickstart command
streaming command
internal
codegen command
Package protocol contains the app-server wire model generated from the Codex release identified by GeneratedCodexVersion and GeneratedCodexCommit.
Package protocol contains the app-server wire model generated from the Codex release identified by GeneratedCodexVersion and GeneratedCodexCommit.
Package rpc provides a minimal JSON-RPC client tailored to the Codex app-server.
Package rpc provides a minimal JSON-RPC client tailored to the Codex app-server.

Jump to

Keyboard shortcuts

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