Documentation
¶
Overview ¶
Package codex provides a Go wrapper for the OpenAI Codex CLI.
The Codex CLI is an AI coding assistant that provides file operations, shell execution, and web search capabilities. This package wraps the CLI to provide a programmatic Go interface.
Installation ¶
The Codex CLI must be installed separately:
npm install -g @openai/codex
Basic Usage ¶
client := codex.NewCodexCLI(
codex.WithModel("gpt-5-codex"),
codex.WithTimeout(5*time.Minute),
)
resp, err := client.Complete(ctx, codex.CompletionRequest{
Messages: []codex.Message{
{Role: codex.RoleUser, Content: "What files are in this directory?"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Content)
Sandbox Modes ¶
Codex supports three sandbox modes that control file system access:
- SandboxReadOnly: Only read operations allowed
- SandboxWorkspaceWrite: Can write to workspace directory (default)
- SandboxDangerFullAccess: Full file system access
Example:
client := codex.NewCodexCLI(
codex.WithSandboxMode(codex.SandboxReadOnly),
)
Approval Modes ¶
Control when Codex asks for user approval:
- ApprovalUntrusted: Ask for all operations (most restrictive)
- ApprovalOnFailure: Ask only when operations fail
- ApprovalOnRequest: Ask only when explicitly requested
- ApprovalNever: Never ask for approval (least restrictive)
For non-interactive usage, use WithFullAuto():
client := codex.NewCodexCLI(
codex.WithFullAuto(),
)
Session Resume ¶
Resume a previous session:
client := codex.NewCodexCLI() resp, err := client.Resume(ctx, "session-id", "Continue with the task")
Image Attachments ¶
Attach images to requests:
client := codex.NewCodexCLI(
codex.WithImages([]string{"/path/to/screenshot.png"}),
)
Provider Interface ¶
The codex package registers itself with the provider registry:
import (
"github.com/randalmurphal/llmkit/provider"
_ "github.com/randalmurphal/llmkit/codex" // Register provider
)
client, err := provider.New("codex", provider.Config{
Model: "gpt-5-codex",
WorkDir: "/path/to/project",
Options: map[string]any{
"sandbox": "workspace-write",
"ask_for_approval": "never",
},
})
Index ¶
- Variables
- func GetBoolOption(key string, defaultVal bool) bool
- func GetStringOption(key, defaultVal string) string
- type ApprovalMode
- type CLIEvent
- type CLIToolCall
- type CLIUsage
- type Capabilities
- type CodexCLI
- func (c *CodexCLI) Capabilities() Capabilities
- func (c *CodexCLI) Close() error
- func (c *CodexCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
- func (c *CodexCLI) Provider() string
- func (c *CodexCLI) Resume(ctx context.Context, sessionID, prompt string) (*CompletionResponse, error)
- func (c *CodexCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
- type CodexOption
- func WithAddDir(dir string) CodexOption
- func WithAddDirs(dirs []string) CodexOption
- func WithApprovalMode(mode ApprovalMode) CodexOption
- func WithCodexPath(path string) CodexOption
- func WithEnv(env map[string]string) CodexOption
- func WithEnvVar(key, value string) CodexOption
- func WithFullAuto() CodexOption
- func WithImage(imagePath string) CodexOption
- func WithImages(imagePaths []string) CodexOption
- func WithModel(model string) CodexOption
- func WithSandboxMode(mode SandboxMode) CodexOption
- func WithSearch() CodexOption
- func WithSessionID(id string) CodexOption
- func WithTimeout(d time.Duration) CodexOption
- func WithWorkdir(dir string) CodexOption
- type CompletionRequest
- type CompletionResponse
- type Config
- type Error
- type Message
- type Role
- type SandboxMode
- type StreamChunk
- type TokenUsage
- type Tool
- type ToolCall
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnavailable = errors.New("LLM service unavailable") // ErrContextTooLong indicates the input exceeds the context window. ErrContextTooLong = errors.New("context exceeds maximum length") // ErrRateLimited indicates the request was rate limited. ErrRateLimited = errors.New("rate limited") // ErrInvalidRequest indicates the request is malformed. ErrInvalidRequest = errors.New("invalid request") // ErrTimeout indicates the request timed out. ErrTimeout = errors.New("request timed out") // ErrSessionNotFound indicates the session ID was not found. ErrSessionNotFound = errors.New("session not found") )
Sentinel errors for LLM operations.
Functions ¶
func GetBoolOption ¶
GetBoolOption retrieves a bool from environment with fallback.
func GetStringOption ¶
GetStringOption retrieves a string from environment with fallback.
Types ¶
type ApprovalMode ¶
type ApprovalMode string
ApprovalMode specifies when to ask for user approval.
const ( ApprovalUntrusted ApprovalMode = "untrusted" ApprovalOnFailure ApprovalMode = "on-failure" ApprovalOnRequest ApprovalMode = "on-request" ApprovalNever ApprovalMode = "never" )
Approval mode constants.
type CLIEvent ¶
type CLIEvent struct {
Type string `json:"type"`
SessionID string `json:"session_id,omitempty"`
Message string `json:"message,omitempty"`
Content string `json:"content,omitempty"`
Error string `json:"error,omitempty"`
Usage *CLIUsage `json:"usage,omitempty"`
ToolCall *CLIToolCall `json:"tool_call,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
}
CLIEvent represents a JSON event from Codex CLI output.
type CLIToolCall ¶
type CLIToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
CLIToolCall represents a tool call event.
type CLIUsage ¶
type CLIUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
}
CLIUsage contains token usage from the CLI response.
type Capabilities ¶
type Capabilities struct {
Streaming bool `json:"streaming"`
Tools bool `json:"tools"`
MCP bool `json:"mcp"`
Sessions bool `json:"sessions"`
Images bool `json:"images"`
NativeTools []string `json:"native_tools"`
ContextFile string `json:"context_file,omitempty"`
}
Capabilities describes what a provider natively supports.
func (Capabilities) HasTool ¶
func (c Capabilities) HasTool(name string) bool
HasTool checks if a native tool is available by name.
type CodexCLI ¶
type CodexCLI struct {
// contains filtered or unexported fields
}
CodexCLI implements Client using the Codex CLI binary.
func NewCodexCLI ¶
func NewCodexCLI(opts ...CodexOption) *CodexCLI
NewCodexCLI creates a new Codex CLI client. Assumes "codex" is available in PATH unless overridden with WithCodexPath.
func (*CodexCLI) Capabilities ¶
func (c *CodexCLI) Capabilities() Capabilities
Capabilities returns Codex CLI's native capabilities.
func (*CodexCLI) Complete ¶
func (c *CodexCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
Complete implements Client.
func (*CodexCLI) Resume ¶
func (c *CodexCLI) Resume(ctx context.Context, sessionID, prompt string) (*CompletionResponse, error)
Resume resumes a previous session by ID. Uses `codex exec resume <SESSION_ID>` for non-interactive mode.
func (*CodexCLI) Stream ¶
func (c *CodexCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
Stream implements Client.
type CodexOption ¶
type CodexOption func(*CodexCLI)
CodexOption configures CodexCLI.
func WithAddDir ¶
func WithAddDir(dir string) CodexOption
WithAddDir adds an additional directory to the accessible paths.
func WithAddDirs ¶
func WithAddDirs(dirs []string) CodexOption
WithAddDirs adds multiple additional directories to the accessible paths.
func WithApprovalMode ¶
func WithApprovalMode(mode ApprovalMode) CodexOption
WithApprovalMode sets when to ask for user approval. Options: "untrusted", "on-failure", "on-request", "never"
func WithCodexPath ¶
func WithCodexPath(path string) CodexOption
WithCodexPath sets the path to the codex binary.
func WithEnv ¶
func WithEnv(env map[string]string) CodexOption
WithEnv adds additional environment variables to the CLI process.
func WithEnvVar ¶
func WithEnvVar(key, value string) CodexOption
WithEnvVar adds a single environment variable to the CLI process.
func WithFullAuto ¶
func WithFullAuto() CodexOption
WithFullAuto enables automatic approvals (equivalent to --full-auto).
func WithImage ¶
func WithImage(imagePath string) CodexOption
WithImage adds an image to attach to the request.
func WithImages ¶
func WithImages(imagePaths []string) CodexOption
WithImages adds multiple images to attach to the request.
func WithSandboxMode ¶
func WithSandboxMode(mode SandboxMode) CodexOption
WithSandboxMode sets the sandbox mode for file system operations. Options: "read-only", "workspace-write", "danger-full-access"
func WithSessionID ¶
func WithSessionID(id string) CodexOption
WithSessionID sets the session ID for resuming sessions.
func WithTimeout ¶
func WithTimeout(d time.Duration) CodexOption
WithTimeout sets the default timeout for commands.
func WithWorkdir ¶
func WithWorkdir(dir string) CodexOption
WithWorkdir sets the working directory for codex commands.
type CompletionRequest ¶
type CompletionRequest struct {
// SystemPrompt sets the system message that guides the model's behavior.
SystemPrompt string `json:"system_prompt,omitempty"`
// Messages is the conversation history to send to the model.
Messages []Message `json:"messages"`
// Model specifies which model to use.
Model string `json:"model,omitempty"`
// MaxTokens limits the response length.
MaxTokens int `json:"max_tokens,omitempty"`
// Temperature controls response randomness (0.0 = deterministic, 1.0 = creative).
Temperature float64 `json:"temperature,omitempty"`
// Tools lists available tools the model can invoke.
Tools []Tool `json:"tools,omitempty"`
// Options holds provider-specific configuration not covered by standard fields.
Options map[string]any `json:"options,omitempty"`
}
CompletionRequest configures an LLM completion call.
type CompletionResponse ¶
type CompletionResponse struct {
Content string `json:"content"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage TokenUsage `json:"usage"`
Model string `json:"model"`
FinishReason string `json:"finish_reason"`
Duration time.Duration `json:"duration"`
// Codex CLI specific fields
SessionID string `json:"session_id,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
NumTurns int `json:"num_turns,omitempty"`
}
CompletionResponse is the output of a completion call.
type Config ¶
type Config struct {
// Model is the primary model to use.
// Default depends on OpenAI account configuration.
Model string `json:"model" yaml:"model" mapstructure:"model"`
// Timeout is the maximum duration for a completion request.
// 0 uses the default (5 minutes).
Timeout time.Duration `json:"timeout" yaml:"timeout" mapstructure:"timeout"`
// WorkDir is the working directory for file operations.
// Default: current directory.
WorkDir string `json:"work_dir" yaml:"work_dir" mapstructure:"work_dir"`
// SandboxMode controls file system access.
// Options: "read-only", "workspace-write", "danger-full-access"
// Default: "workspace-write"
SandboxMode SandboxMode `json:"sandbox_mode" yaml:"sandbox_mode" mapstructure:"sandbox_mode"`
// ApprovalMode controls when to ask for user approval.
// Options: "untrusted", "on-failure", "on-request", "never"
ApprovalMode ApprovalMode `json:"approval_mode" yaml:"approval_mode" mapstructure:"approval_mode"`
// FullAuto enables automatic approvals for all operations.
// Equivalent to --full-auto flag.
FullAuto bool `json:"full_auto" yaml:"full_auto" mapstructure:"full_auto"`
// SessionID is the session ID for resuming sessions.
SessionID string `json:"session_id" yaml:"session_id" mapstructure:"session_id"`
// EnableSearch enables web search capabilities.
EnableSearch bool `json:"enable_search" yaml:"enable_search" mapstructure:"enable_search"`
// AddDirs adds directories to Codex's file access scope.
AddDirs []string `json:"add_dirs" yaml:"add_dirs" mapstructure:"add_dirs"`
// Images lists image paths to attach to requests.
Images []string `json:"images" yaml:"images" mapstructure:"images"`
// Env provides additional environment variables.
Env map[string]string `json:"env" yaml:"env" mapstructure:"env"`
// CodexPath is the path to the codex CLI binary.
// Default: "codex" (found via PATH).
CodexPath string `json:"codex_path" yaml:"codex_path" mapstructure:"codex_path"`
}
Config holds configuration for a Codex client. Zero values use sensible defaults where noted.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func FromEnv ¶
func FromEnv() Config
FromEnv creates a Config from environment variables with defaults.
func (*Config) LoadFromEnv ¶
func (c *Config) LoadFromEnv()
LoadFromEnv populates config fields from environment variables. Environment variables use CODEX_ prefix and take precedence over existing values.
func (*Config) ToOptions ¶
func (c *Config) ToOptions() []CodexOption
ToOptions converts the config to functional options.
type Error ¶
type Error struct {
Op string // Operation that failed ("complete", "stream", "resume")
Err error // Underlying error
Retryable bool // Whether the error is likely transient
}
Error wraps LLM errors with context.
type Message ¶
type Message struct {
Role Role `json:"role"`
Content string `json:"content"`
Name string `json:"name,omitempty"` // For tool results
}
Message is a conversation turn.
type SandboxMode ¶
type SandboxMode string
SandboxMode specifies the sandbox level for file system operations.
const ( SandboxReadOnly SandboxMode = "read-only" SandboxWorkspaceWrite SandboxMode = "workspace-write" SandboxDangerFullAccess SandboxMode = "danger-full-access" )
Sandbox mode constants.
type StreamChunk ¶
type StreamChunk struct {
Content string `json:"content,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"` // Only set in final chunk
Done bool `json:"done"`
Error error `json:"-"` // Non-nil if streaming failed
}
StreamChunk is a piece of a streaming response.
type TokenUsage ¶
type TokenUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
}
TokenUsage tracks token consumption.
func (*TokenUsage) Add ¶
func (u *TokenUsage) Add(other TokenUsage)
Add calculates total tokens and adds to existing usage.