Documentation
¶
Overview ¶
Package codex provides a Go wrapper for the OpenAI Codex CLI.
The wrapper is designed for headless/non-interactive execution using `codex exec --json` and includes adaptive parsing for modern JSONL events like thread/turn/item lifecycle messages.
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: "Summarize this repo"}},
})
Headless Configuration ¶
client := codex.NewCodexCLI(
codex.WithProfile("ci"),
codex.WithSandboxMode(codex.SandboxWorkspaceWrite),
codex.WithApprovalMode(codex.ApprovalNever),
codex.WithWebSearchMode(codex.WebSearchCached),
codex.WithConfigOverride("model_reasoning_effort", "medium"),
codex.WithEnabledFeatures([]string{"project_doc"}),
)
Session Resume ¶
Resume a specific session or the most recent session via WithSessionID:
client := codex.NewCodexCLI(codex.WithSessionID("thread_abc123"))
resp, err := client.Complete(ctx, codex.CompletionRequest{Messages: ...})
The session ID is passed through buildExecArgs which emits `exec resume <id>`. Flags unsupported by `exec resume` are automatically filtered out.
Provider Interface ¶
The codex package registers itself with the provider registry:
import (
"github.com/randalmurphal/llmkit/provider"
_ "github.com/randalmurphal/llmkit/codex"
)
client, err := provider.New("codex", provider.Config{
Model: "gpt-5-codex",
Options: map[string]any{
"sandbox": "workspace-write",
"ask_for_approval": "never",
"web_search": "cached",
},
})
Index ¶
- Variables
- func GetBoolOption(key string, defaultVal bool) bool
- func GetStringOption(key, defaultVal string) string
- type ApprovalMode
- 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) 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 WithColorMode(mode string) CodexOption
- func WithConfigOverride(key string, value any) CodexOption
- func WithConfigOverrides(overrides map[string]any) CodexOption
- func WithDangerouslyBypassApprovalsAndSandbox() CodexOption
- func WithDisabledFeatures(features []string) CodexOption
- func WithEnabledFeatures(features []string) CodexOption
- func WithEnv(env map[string]string) CodexOption
- func WithEnvVar(key, value string) CodexOption
- func WithFullAuto() CodexOption
- func WithHideAgentReasoning() CodexOption
- func WithImage(imagePath string) CodexOption
- func WithImages(imagePaths []string) CodexOption
- func WithLocalProvider(provider string) CodexOption
- func WithModel(model string) CodexOption
- func WithOSS() CodexOption
- func WithOutputLastMessage(path string) CodexOption
- func WithOutputSchema(path string) CodexOption
- func WithProfile(profile string) CodexOption
- func WithReasoningEffort(effort string) CodexOption
- func WithResumeAll() CodexOption
- func WithSandboxMode(mode SandboxMode) CodexOption
- func WithSearch() CodexOption
- func WithSessionID(id string) CodexOption
- func WithSkipGitRepoCheck() CodexOption
- func WithTimeout(d time.Duration) CodexOption
- func WithWebSearchMode(mode WebSearchMode) 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
- type WebSearchMode
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 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) 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 WithColorMode ¶ added in v1.5.0
func WithColorMode(mode string) CodexOption
WithColorMode sets output color mode: auto, always, or never.
func WithConfigOverride ¶ added in v1.5.0
func WithConfigOverride(key string, value any) CodexOption
WithConfigOverride adds a single -c key=value override.
func WithConfigOverrides ¶ added in v1.5.0
func WithConfigOverrides(overrides map[string]any) CodexOption
WithConfigOverrides adds multiple -c key=value overrides.
func WithDangerouslyBypassApprovalsAndSandbox ¶ added in v1.5.0
func WithDangerouslyBypassApprovalsAndSandbox() CodexOption
WithDangerouslyBypassApprovalsAndSandbox enables Codex YOLO mode.
func WithDisabledFeatures ¶ added in v1.5.0
func WithDisabledFeatures(features []string) CodexOption
WithDisabledFeatures disables one or more codex feature flags.
func WithEnabledFeatures ¶ added in v1.5.0
func WithEnabledFeatures(features []string) CodexOption
WithEnabledFeatures enables one or more codex feature flags.
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 WithHideAgentReasoning ¶ added in v1.5.0
func WithHideAgentReasoning() CodexOption
WithHideAgentReasoning hides internal reasoning via -c override.
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 WithLocalProvider ¶ added in v1.5.0
func WithLocalProvider(provider string) CodexOption
WithLocalProvider selects the local OSS provider backend (e.g., "lmstudio", "ollama").
func WithOSS ¶ added in v1.5.0
func WithOSS() CodexOption
WithOSS enables the local OSS backend mode.
func WithOutputLastMessage ¶ added in v1.5.0
func WithOutputLastMessage(path string) CodexOption
WithOutputLastMessage sets --output-last-message.
func WithOutputSchema ¶ added in v1.5.0
func WithOutputSchema(path string) CodexOption
WithOutputSchema sets --output-schema.
func WithProfile ¶ added in v1.5.0
func WithProfile(profile string) CodexOption
WithProfile sets the codex profile name.
func WithReasoningEffort ¶ added in v1.5.0
func WithReasoningEffort(effort string) CodexOption
WithReasoningEffort sets model_reasoning_effort via -c override.
func WithResumeAll ¶ added in v1.5.0
func WithResumeAll() CodexOption
WithResumeAll includes all previous conversation turns when resuming. Only applies when session is "last" or resume mode is active.
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 WithSearch ¶
func WithSearch() CodexOption
WithSearch enables live web search capabilities. Deprecated compatibility alias for WithWebSearchMode(WebSearchLive).
func WithSessionID ¶
func WithSessionID(id string) CodexOption
WithSessionID sets the session ID for resuming sessions. Use "last" to resume the most recent session.
func WithSkipGitRepoCheck ¶ added in v1.5.0
func WithSkipGitRepoCheck() CodexOption
WithSkipGitRepoCheck allows execution outside a git repository.
func WithTimeout ¶
func WithTimeout(d time.Duration) CodexOption
WithTimeout sets the default timeout for commands.
func WithWebSearchMode ¶ added in v1.5.0
func WithWebSearchMode(mode WebSearchMode) CodexOption
WithWebSearchMode sets the web search mode.
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"`
// WebSearchMode overrides the client-level web search mode for this request.
// Options: "cached", "live", "disabled"
WebSearchMode WebSearchMode `json:"web_search_mode,omitempty"`
// OutputSchemaPath overrides the client-level --output-schema path.
OutputSchemaPath string `json:"output_schema_path,omitempty"`
// OutputLastMessagePath overrides the client-level --output-last-message path.
OutputLastMessagePath string `json:"output_last_message_path,omitempty"`
// ConfigOverrides are applied as repeated -c key=value flags for this request.
// Request-level overrides take precedence over client-level overrides.
ConfigOverrides map[string]any `json:"config_overrides,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"
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"`
// DangerouslyBypassApprovalsAndSandbox bypasses both approvals and sandboxing.
// Equivalent to --dangerously-bypass-approvals-and-sandbox / --yolo.
DangerouslyBypassApprovalsAndSandbox bool `` /* 151-byte string literal not displayed */
// SessionID is the session ID for resuming sessions.
SessionID string `json:"session_id" yaml:"session_id" mapstructure:"session_id"`
// ResumeAll includes all previous turns when resuming `last`.
ResumeAll bool `json:"resume_all" yaml:"resume_all" mapstructure:"resume_all"`
// EnableSearch enables web search capabilities.
// Deprecated alias for WebSearchMode=live.
EnableSearch bool `json:"enable_search" yaml:"enable_search" mapstructure:"enable_search"`
// WebSearchMode controls web search strategy.
// Options: "cached", "live", "disabled"
WebSearchMode WebSearchMode `json:"web_search_mode" yaml:"web_search_mode" mapstructure:"web_search_mode"`
// ReasoningEffort controls model reasoning effort for models that support it.
// Common values: "minimal", "low", "medium", "high".
ReasoningEffort string `json:"reasoning_effort" yaml:"reasoning_effort" mapstructure:"reasoning_effort"`
// HideAgentReasoning hides internal agent reasoning in output.
// Applied via -c hide_agent_reasoning=true.
HideAgentReasoning bool `json:"hide_agent_reasoning" yaml:"hide_agent_reasoning" mapstructure:"hide_agent_reasoning"`
// UseOSS enables local OSS backend mode.
UseOSS bool `json:"use_oss" yaml:"use_oss" mapstructure:"use_oss"`
// EnabledFeatures enables experimental codex features (--enable).
EnabledFeatures []string `json:"enabled_features" yaml:"enabled_features" mapstructure:"enabled_features"`
// DisabledFeatures disables codex features (--disable).
DisabledFeatures []string `json:"disabled_features" yaml:"disabled_features" mapstructure:"disabled_features"`
// ColorMode sets output color mode: "auto", "always", "never".
ColorMode string `json:"color_mode" yaml:"color_mode" mapstructure:"color_mode"`
// Profile selects a codex profile from config.toml.
Profile string `json:"profile" yaml:"profile" mapstructure:"profile"`
// LocalProvider selects OSS local provider backend (e.g., "lmstudio", "ollama").
LocalProvider string `json:"local_provider" yaml:"local_provider" mapstructure:"local_provider"`
// ConfigOverrides are applied as repeated -c key=value flags.
ConfigOverrides map[string]any `json:"config_overrides" yaml:"config_overrides" mapstructure:"config_overrides"`
// SkipGitRepoCheck allows running outside a git repository.
SkipGitRepoCheck bool `json:"skip_git_repo_check" yaml:"skip_git_repo_check" mapstructure:"skip_git_repo_check"`
// OutputSchemaPath sets --output-schema to enforce final output JSON schema.
OutputSchemaPath string `json:"output_schema_path" yaml:"output_schema_path" mapstructure:"output_schema_path"`
// OutputLastMessagePath sets --output-last-message file output path.
OutputLastMessagePath string `json:"output_last_message_path" yaml:"output_last_message_path" mapstructure:"output_last_message_path"`
// 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.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
}
Tool defines an available tool for the LLM.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
ToolCall represents a tool invocation request from the LLM.
type WebSearchMode ¶ added in v1.5.0
type WebSearchMode string
WebSearchMode controls how Codex should perform web search.
const ( WebSearchCached WebSearchMode = "cached" WebSearchLive WebSearchMode = "live" WebSearchDisabled WebSearchMode = "disabled" )
Web search mode constants.