codex

package module
v0.143.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: Apache-2.0 Imports: 15 Imported by: 2

README

Codex Go SDK

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+
  • 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 {
        break
    }
    fmt.Printf("%s\n", note.Method)
    if note.Method == "turn/completed" {
        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.

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 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.

Approvals

Configure approval handling by supplying a handler when constructing the client.

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

For custom approval logic, implement rpc.ServerRequestHandler (from rpc).

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 retryable errors

Use helpers to build structured inputs:

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

Retry classification uses ordinary Go errors:

if codex.IsRetryable(err) {
    // Retry according to your caller policy.
}

Low-level RPC

Use the RPC client directly for full control.

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

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 / ...

Retryable overload errors can be detected with codex.IsRetryable or codex.IsOverloaded. Both helpers work with wrapped errors.

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"
	// 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.

Functions

func IsOverloaded

func IsOverloaded(err error) bool

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

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether err is safe for SDK callers to retry.

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 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. Logger controls approval logging. When 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

McpServerElicitationRequest returns an error for MCP elicitation prompts.

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

StartLogin starts an app-server account login flow using 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 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:"textElements,omitempty"`
	URL          string                 `json:"url,omitempty"`
	Path         string                 `json:"path,omitempty"`
	Name         string                 `json:"name,omitempty"`
}

Input represents a structured user input message.

func ImageInput

func ImageInput(url string) Input

ImageInput creates a remote image 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.
	ApprovalHandler rpc.ServerRequestHandler
}

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 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 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.

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
	Cwd                   string
	ApprovalPolicy        any
	Sandbox               any
	Config                map[string]any
	BaseInstructions      string
	DeveloperInstructions string
	Ephemeral             *bool
	ExcludeTurns          *bool
}

ThreadForkOptions configures a thread/fork request.

type ThreadListOptions

type ThreadListOptions struct {
	Archived       *bool
	Cursor         string
	Cwd            any
	Limit          *int
	ModelProviders []string
	SearchTerm     string
	SortDirection  any
	SortKey        any
	SourceKinds    []protocol.ThreadSourceKind
	UseStateDBOnly *bool
}

ThreadListOptions configures a thread/list request.

type ThreadReadOptions

type ThreadReadOptions struct {
	IncludeTurns bool
}

ThreadReadOptions configures a thread/read request.

type ThreadResumeHistoryElem

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.

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.
	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.
	Path          string
	Model         string
	ModelProvider 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
	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
	BaseInstructions      string
	DeveloperInstructions string
	// ExperimentalRawEvents is retained for source compatibility, but the current
	// app-server protocol no longer supports this option. Setting it returns an
	// error from toParams.
	ExperimentalRawEvents bool
}

ThreadStartOptions configures a thread/start request.

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) 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.

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 {
	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
	// 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.
	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.

Directories

Path Synopsis
examples
approvals command
lifecycle command
low_level_rpc command
quickstart command
streaming command
internal
codegen command
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