config

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: GPL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package config provides configuration types for the Codex SDK.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureToolPermissionPolicy

func ConfigureToolPermissionPolicy(opts *Options) error

ConfigureToolPermissionPolicy prepares callback/tool-related options for both Query and Client flows. It preserves existing callback behavior and adds emulation for AllowedTools/DisallowedTools/ToolsList in app-server mode.

func EnabledOptionFields

func EnabledOptionFields(opts *Options) map[string]bool

EnabledOptionFields returns option fields explicitly set by the caller.

func ValidateOptionsForBackend

func ValidateOptionsForBackend(opts *Options, backend QueryBackend) error

ValidateOptionsForBackend returns ErrUnsupportedOption if any set option is not supported for the selected backend.

Types

type AgentDefinition

type AgentDefinition struct {
	Description string   `json:"description"`
	Prompt      string   `json:"prompt"`
	Tools       []string `json:"tools,omitempty"`
	Model       *string  `json:"model,omitempty"`
}

AgentDefinition defines a custom agent configuration.

type Beta

type Beta string

Beta represents a beta feature flag for the SDK.

const (
	// BetaContext1M enables 1 million token context window.
	BetaContext1M Beta = "context-1m"
)

type DynamicTool

type DynamicTool struct {
	Name        string
	Description string
	InputSchema map[string]any
	Handler     func(ctx context.Context, input map[string]any) (map[string]any, error)
}

DynamicTool defines a tool registered via the dynamicTools API. The Codex CLI discovers these tools at thread/start and calls them back via item/tool/call RPC using the plain tool name.

type Effort

type Effort string

Effort controls thinking depth.

const (
	// EffortLow uses minimal thinking.
	EffortLow Effort = "low"
	// EffortMedium uses moderate thinking.
	EffortMedium Effort = "medium"
	// EffortHigh uses deep thinking.
	EffortHigh Effort = "high"
	// EffortMax uses maximum thinking depth.
	EffortMax Effort = "xhigh"
	// EffortNone disables reasoning entirely.
	EffortNone Effort = "none"
	// EffortMinimal uses minimal reasoning.
	EffortMinimal Effort = "minimal"
)

type OptionCapability

type OptionCapability struct {
	Field      string
	Exec       SupportLevel
	AppServer  SupportLevel
	Notes      string
	OptionName string
}

OptionCapability defines support by backend for one option field.

func OptionCapabilities

func OptionCapabilities() []OptionCapability

OptionCapabilities returns all option capabilities.

type Options

type Options struct {
	// Logger is the slog logger for debug output.
	// If nil, logging is disabled (silent operation).
	Logger *slog.Logger

	// SystemPrompt is the system message to send to the agent.
	SystemPrompt string

	// SystemPromptPreset specifies a preset system prompt configuration.
	// If set, this takes precedence over SystemPrompt.
	SystemPromptPreset *SystemPromptPreset

	// Model specifies which model to use.
	Model string

	// PermissionMode controls how permissions are handled.
	// Supported values are "default", "acceptEdits", "plan", and
	// "bypassPermissions".
	PermissionMode string

	// MaxTurns sets the maximum number of conversation turns.
	MaxTurns int

	// Cwd sets the working directory for the CLI process.
	Cwd string

	// CliPath is the explicit path to the codex CLI binary.
	// If empty, the CLI will be searched in PATH.
	CliPath string

	// Env provides additional environment variables for the CLI process.
	Env map[string]string

	// Hooks configures event hooks for tool interception.
	// Hooks are registered via protocol session and dispatched when Codex CLI sends
	// hooks/callback requests.
	Hooks map[hook.Event][]*hook.Matcher

	// Effort controls thinking depth.
	// Passed to CLI via initialization; support depends on Codex CLI version.
	Effort *Effort

	// Personality controls the agent's response personality.
	// Valid values: "none", "friendly", "pragmatic".
	Personality string

	// ServiceTier controls the service tier for API requests.
	// Valid values: "fast", "flex".
	ServiceTier string

	// DeveloperInstructions provides additional instructions for the agent.
	// This is separate from SystemPrompt and is passed as developerInstructions
	// in the thread/start payload.
	DeveloperInstructions string

	// MCPServers configures external MCP servers to connect to.
	// SDK MCP servers are registered and respond to mcp_message requests from CLI.
	MCPServers map[string]mcp.ServerConfig

	// SDKTools holds dynamic tools registered via WithSDKTools.
	// These are serialized as dynamicTools in the thread/start payload and
	// dispatched via item/tool/call RPC using plain tool names.
	SDKTools []*DynamicTool

	// CanUseTool is called before each tool use for permission checking.
	// Permission callback invoked when CLI sends can_use_tool requests via protocol.
	CanUseTool permission.Callback

	// OnUserInput is called when the CLI sends item/tool/requestUserInput requests.
	// This callback allows the SDK consumer to answer questions posed by the agent
	// (e.g., multiple-choice or free-text prompts in plan mode).
	OnUserInput userinput.Callback

	// OnElicitation is called when the CLI sends mcpServer/elicitation/request.
	// If nil, elicitation requests are auto-declined.
	OnElicitation elicitation.Callback

	// Tools specifies which tools are available.
	Tools ToolsConfig

	// AllowedTools is a list of pre-approved tools.
	AllowedTools []string

	// DisallowedTools is a list of explicitly blocked tools.
	DisallowedTools []string

	// PermissionPromptToolName specifies the tool name for permission prompts.
	PermissionPromptToolName string

	// AddDirs is a list of additional directories to make accessible.
	AddDirs []string

	// ExtraArgs provides arbitrary CLI flags.
	ExtraArgs map[string]*string

	// Stderr is a callback function for handling stderr output.
	Stderr func(string)

	// ContinueConversation indicates whether to continue an existing conversation.
	ContinueConversation bool

	// Resume is a session ID to resume from.
	Resume string

	// ForkSession indicates whether to fork the resumed session.
	ForkSession bool

	// OutputFormat specifies a JSON schema for structured output.
	OutputFormat map[string]any

	// InitializeTimeout is the timeout for the initialize control request.
	InitializeTimeout *time.Duration

	// Transport allows injecting a custom transport implementation.
	// If nil, the default CLITransport is created automatically.
	Transport Transport `json:"-"`

	// Sandbox sets the Codex sandbox mode (read-only, workspace-write, danger-full-access).
	Sandbox string

	// Images lists file paths for image inputs (passed via -i flags).
	Images []string

	// Config holds key=value pairs for Codex CLI configuration (passed via -c flags).
	Config map[string]string

	// OutputSchema sets the --output-schema flag for structured Codex output.
	OutputSchema string

	// SkipVersionCheck disables CLI version validation during discovery.
	SkipVersionCheck bool

	// IncludePartialMessages controls whether streaming deltas are emitted
	// as StreamEvent messages. When false (default), only completed
	// AssistantMessage and ResultMessage are emitted. When true, token-by-token
	// deltas are emitted as StreamEvent with content_block_delta/text_delta shape.
	IncludePartialMessages bool

	// CodexHome overrides the Codex home directory (default ~/.codex).
	// Used by StatSession to locate the session database.
	CodexHome string

	// MeterProvider is the OTel meter provider for recording SDK metrics.
	// When nil, all metric recording is noop (zero-cost).
	MeterProvider metric.MeterProvider

	// TracerProvider is the OTel tracer provider for recording SDK spans.
	// When nil, all trace recording is noop (zero-cost).
	TracerProvider trace.TracerProvider

	// PrometheusRegisterer provides a Prometheus registerer for SDK metrics.
	// This is sugar: when set and MeterProvider is nil, an OTel MeterProvider
	// is created automatically from the registerer via the OTel→Prometheus bridge.
	// If MeterProvider is also set, MeterProvider takes precedence.
	PrometheusRegisterer prometheus.Registerer

	// MetricsRecorder is the internal observability recorder created from OTel providers.
	// This field is set by the SDK at runtime; users should not set it directly.
	MetricsRecorder SessionMetricsRecorder `json:"-"`

	// Observer is the shared observability helper used for SDK-level span and
	// duration instrumentation beyond message-based recording (hook dispatch,
	// explicit tool spans, etc.). Set by the SDK at runtime alongside
	// MetricsRecorder; consumers should not set this directly.
	Observer *observability.Observer `json:"-"`
}

Options configures the behavior of the Codex agent.

type PluginConfig

type PluginConfig struct {
	Type string `json:"type"` // "local"
	Path string `json:"path"`
}

PluginConfig configures a plugin to load.

type QueryBackend

type QueryBackend string

QueryBackend describes the built-in backend selected for one-shot Query.

const (
	// QueryBackendExec uses `codex exec`.
	QueryBackendExec QueryBackend = "exec"
	// QueryBackendAppServer uses `codex app-server` through the adapter.
	QueryBackendAppServer QueryBackend = "app-server"
)

func SelectQueryBackend

func SelectQueryBackend(opts *Options) QueryBackend

SelectQueryBackend chooses which built-in backend Query should use.

type QueryLifecycleNotifier added in v0.0.12

type QueryLifecycleNotifier interface {
	MarkQueryStart()
}

QueryLifecycleNotifier is optionally implemented by SessionMetricsRecorder to receive query lifecycle events (e.g., TTFT start time).

type SessionMetricsRecorder added in v0.0.12

type SessionMetricsRecorder interface {
	Observe(ctx context.Context, msg message.Message)
}

SessionMetricsRecorder is the narrow observability interface used by the SDK runtime. The otelRecorder in the root package implements this, keeping the internal layer decoupled from the specific recorder implementation.

type SettingSource

type SettingSource string

SettingSource represents where settings should be loaded from.

const (
	// SettingSourceUser loads from user-level settings.
	SettingSourceUser SettingSource = "user"
	// SettingSourceProject loads from project-level settings.
	SettingSourceProject SettingSource = "project"
	// SettingSourceLocal loads from local-level settings.
	SettingSourceLocal SettingSource = "local"
)

type SupportLevel

type SupportLevel string

SupportLevel describes how a backend handles an option.

const (
	// SupportSupported means native/direct support.
	SupportSupported SupportLevel = "supported"
	// SupportEmulated means behavior is supported with constraints or emulation.
	SupportEmulated SupportLevel = "emulated"
	// SupportUnsupported means the option is not supported on that backend.
	SupportUnsupported SupportLevel = "unsupported"
)

type SystemPromptPreset

type SystemPromptPreset struct {
	Type   string  `json:"type"`
	Preset string  `json:"preset"`
	Append *string `json:"append,omitempty"`
}

SystemPromptPreset defines a system prompt preset configuration.

type ThinkingConfig

type ThinkingConfig interface {
	// contains filtered or unexported methods
}

ThinkingConfig controls extended thinking behavior. Implementations: ThinkingConfigAdaptive, ThinkingConfigEnabled, ThinkingConfigDisabled.

type ThinkingConfigAdaptive

type ThinkingConfigAdaptive struct{}

ThinkingConfigAdaptive enables adaptive thinking mode.

type ThinkingConfigDisabled

type ThinkingConfigDisabled struct{}

ThinkingConfigDisabled disables extended thinking.

type ThinkingConfigEnabled

type ThinkingConfigEnabled struct {
	BudgetTokens int
}

ThinkingConfigEnabled enables thinking with a specific token budget.

type ToolsConfig

type ToolsConfig interface {
	// contains filtered or unexported methods
}

ToolsConfig is an interface for configuring available tools. It represents either a list of tool names or a preset configuration.

type ToolsList

type ToolsList []string

ToolsList is a list of tool names to make available.

type ToolsPreset

type ToolsPreset struct {
	Type   string `json:"type"`   // "preset"
	Preset string `json:"preset"` // e.g. "codex_default"
}

ToolsPreset represents a preset configuration for available tools.

type Transport

type Transport interface {
	// Start initializes the transport and prepares it for communication.
	Start(ctx context.Context) error

	// ReadMessages returns channels for receiving messages and errors.
	// The message channel yields parsed JSON objects from the CLI.
	// The error channel yields any errors that occur during reading.
	// Both channels are closed when reading completes or an error occurs.
	ReadMessages(ctx context.Context) (<-chan map[string]any, <-chan error)

	// SendMessage sends a JSON message to the CLI.
	// The data should be a complete JSON message (newline is appended if missing).
	// This method must be safe for concurrent use.
	SendMessage(ctx context.Context, data []byte) error

	// Close terminates the transport and releases resources.
	// It's safe to call Close multiple times.
	Close() error

	// IsReady returns true if the transport is ready for communication.
	IsReady() bool

	// EndInput signals that no more input will be sent.
	// For process-based transports, this typically closes stdin.
	EndInput() error
}

Transport defines the interface for Codex CLI communication. Implement this to provide custom transports for testing, mocking, or alternative communication methods.

The default implementation is CLITransport which spawns a subprocess. Custom transports can be injected via Options.Transport.

Jump to

Keyboard shortcuts

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