Documentation
¶
Overview ¶
Package codex provides a Go SDK for interacting with OpenAI's codex CLI.
Similar to the official OpenAI TypeScript SDK, this package allows developers to integrate codex capabilities into their Go applications. Please be aware that this SDK is unofficial and not endorsed by OpenAI, but it aims to provide a similar level of functionality and ease of use.
https://github.com/openai/codex/tree/main/sdk/typescript/src
Index ¶
- func EventStream(ctx context.Context, stream *ExecStream) iter.Seq2[*ThreadEvent, error]
- func Run(ctx context.Context, args Args) iter.Seq2[*ThreadEvent, error]
- type AgentMessageItem
- type ApprovalMode
- type Args
- type CommandExecutionItem
- type CommandExecutionStatus
- type ErrorItem
- type EventType
- type Exec
- type ExecStream
- type FileChangeItem
- type FileUpdateChange
- type Input
- type InputType
- type ItemType
- type McpToolCallItem
- type McpToolCallStatus
- type Options
- type PatchApplyStatus
- type PatchChangeKind
- type ReasoningItem
- type RunResult
- type RunStreamedResult
- type SandboxMode
- type StreamedTurn
- type Thread
- func (t *Thread) ID() string
- func (t *Thread) Run(ctx context.Context, input Input, turnOptions *TurnOptions) (Turn, error)
- func (t *Thread) RunStreamed(ctx context.Context, input Input, turnOptions *TurnOptions) (*StreamedTurn, error)
- func (t *Thread) RunStreamedText(ctx context.Context, prompt string, turnOptions *TurnOptions) (*StreamedTurn, error)
- func (t *Thread) RunText(ctx context.Context, prompt string, turnOptions *TurnOptions) (Turn, error)
- type ThreadError
- type ThreadEvent
- type ThreadItem
- type ThreadOptions
- type TodoItem
- type TodoListItem
- type Turn
- type TurnOptions
- type UnknownThreadItem
- type Usage
- type UserInput
- type WebSearchItem
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EventStream ¶
func EventStream(ctx context.Context, stream *ExecStream) iter.Seq2[*ThreadEvent, error]
EventStream returns an iterator that yields ThreadEvents decoded from the provided ExecStream. The iterator yields (*ThreadEvent, nil) for each event, and (nil, error) if an error occurs.
This is a convenience function for consuming events from a Codex execution stream. It decodes JSON-encoded events from the stream's stdout until EOF or an error occurs. The context can be used to cancel the iteration early, and the stream's Wait method is called at the end to ensure proper cleanup. The stream is also closed when iteration ends.
func Run ¶
Run executes a codex command with the specified arguments and returns an iterator that yields ThreadEvents from the execution stream.
This is a high-level convenience function that combines creating an Exec, running it with the provided arguments, and streaming the resulting events. It handles proper cleanup of the execution stream.
Types ¶
type AgentMessageItem ¶
type AgentMessageItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Text string `json:"text"`
}
AgentMessageItem contains the assistant's text response.
func (*AgentMessageItem) ItemType ¶
func (i *AgentMessageItem) ItemType() ItemType
type ApprovalMode ¶
type ApprovalMode string
ApprovalMode mirrors the codex CLI approval modes.
const ( ApprovalModeNever ApprovalMode = "never" ApprovalModeOnRequest ApprovalMode = "on-request" ApprovalModeOnFailure ApprovalMode = "on-failure" ApprovalModeUntrusted ApprovalMode = "untrusted" )
type CommandExecutionItem ¶
type CommandExecutionItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Command string `json:"command"`
AggregatedOutput string `json:"aggregated_output"`
ExitCode *int `json:"exit_code,omitempty"`
Status CommandExecutionStatus `json:"status"`
}
CommandExecutionItem records a shell command executed by the agent.
func (*CommandExecutionItem) ItemType ¶
func (i *CommandExecutionItem) ItemType() ItemType
type CommandExecutionStatus ¶
type CommandExecutionStatus string
CommandExecutionStatus represents a command execution state.
const ( CommandExecutionStatusInProgress CommandExecutionStatus = "in_progress" CommandExecutionStatusCompleted CommandExecutionStatus = "completed" CommandExecutionStatusFailed CommandExecutionStatus = "failed" )
type ErrorItem ¶
type ErrorItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Message string `json:"message"`
}
ErrorItem reflects a non-fatal error surfaced to the user.
type EventType ¶
type EventType string
EventType enumerates the JSON events emitted by `codex exec`.
const ( EventTypeThreadStarted EventType = "thread.started" EventTypeTurnStarted EventType = "turn.started" EventTypeTurnCompleted EventType = "turn.completed" EventTypeTurnFailed EventType = "turn.failed" EventTypeItemStarted EventType = "item.started" EventTypeItemUpdated EventType = "item.updated" EventTypeItemCompleted EventType = "item.completed" EventTypeError EventType = "error" )
type ExecStream ¶
type ExecStream struct {
// contains filtered or unexported fields
}
func (*ExecStream) Close ¶
func (s *ExecStream) Close() error
func (*ExecStream) Stdout ¶
func (s *ExecStream) Stdout() io.ReadCloser
func (*ExecStream) Wait ¶
func (s *ExecStream) Wait() error
type FileChangeItem ¶
type FileChangeItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Changes []FileUpdateChange `json:"changes"`
Status PatchApplyStatus `json:"status"`
}
FileChangeItem aggregates a set of file modifications.
func (*FileChangeItem) ItemType ¶
func (i *FileChangeItem) ItemType() ItemType
type FileUpdateChange ¶
type FileUpdateChange struct {
Path string `json:"path"`
Kind PatchChangeKind `json:"kind"`
}
FileUpdateChange describes an individual file operation.
type Input ¶
type Input struct {
// Prompt is the base textual prompt sent to the CLI.
Prompt string
// Parts augments the prompt with additional inputs such as local images.
Parts []UserInput
}
Input represents the user-provided content for a single agent turn. Use TextInput to send a plain string prompt, or ComposeInput with individual parts when mixing text and local images.
func ComposeInput ¶
ComposeInput creates an Input from a set of user inputs. Parts are copied so the caller can reuse the provided slice.
type ItemType ¶
type ItemType string
ItemType identifies the kind of thread item.
const ( ItemTypeAgentMessage ItemType = "agent_message" ItemTypeReasoning ItemType = "reasoning" ItemTypeCommandExecution ItemType = "command_execution" ItemTypeFileChange ItemType = "file_change" ItemTypeMcpToolCall ItemType = "mcp_tool_call" ItemTypeWebSearch ItemType = "web_search" ItemTypeTodoList ItemType = "todo_list" ItemTypeError ItemType = "error" ItemTypeUnknown ItemType = "unknown" )
type McpToolCallItem ¶
type McpToolCallItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Server string `json:"server"`
Tool string `json:"tool"`
Status McpToolCallStatus `json:"status"`
}
McpToolCallItem represents an MCP tool call.
func (*McpToolCallItem) ItemType ¶
func (i *McpToolCallItem) ItemType() ItemType
type McpToolCallStatus ¶
type McpToolCallStatus string
McpToolCallStatus reflects the state of an MCP tool invocation.
const ( McpToolCallStatusInProgress McpToolCallStatus = "in_progress" McpToolCallStatusCompleted McpToolCallStatus = "completed" McpToolCallStatusFailed McpToolCallStatus = "failed" )
type Options ¶
type Options struct {
// CodexPathOverride points to a specific codex binary. When empty the SDK searches
// for the bundled binary that ships with this module.
CodexPathOverride string
// BaseURL overrides the default API base URL used by the codex CLI. When empty,
// the CLI's default value is used.
BaseURL string
// APIKey overrides the API key used by the codex CLI. When empty, the CLI falls
// back to the CODEX_API_KEY environment variable.
APIKey string
}
Options configure a Codex client.
type PatchApplyStatus ¶
type PatchApplyStatus string
PatchApplyStatus indicates the result of applying a patch.
const ( PatchApplyStatusCompleted PatchApplyStatus = "completed" PatchApplyStatusFailed PatchApplyStatus = "failed" )
type PatchChangeKind ¶
type PatchChangeKind string
PatchChangeKind indicates the type of file change.
const ( PatchChangeKindAdd PatchChangeKind = "add" PatchChangeKindDelete PatchChangeKind = "delete" PatchChangeKindUpdate PatchChangeKind = "update" )
type ReasoningItem ¶
type ReasoningItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Text string `json:"text"`
}
ReasoningItem captures an agent's reasoning summary.
func (*ReasoningItem) ItemType ¶
func (i *ReasoningItem) ItemType() ItemType
type RunStreamedResult ¶
type RunStreamedResult = StreamedTurn
RunStreamedResult aliases StreamedTurn for parity with the TypeScript SDK.
type SandboxMode ¶
type SandboxMode string
SandboxMode mirrors the codex CLI sandboxing options.
const ( SandboxModeReadOnly SandboxMode = "read-only" SandboxModeWorkspaceWrite SandboxMode = "workspace-write" SandboxModeDangerFullAccess SandboxMode = "danger-full-access" )
type StreamedTurn ¶
type StreamedTurn struct {
// Events yields parsed events in the order emitted by the CLI.
Events <-chan ThreadEvent
// contains filtered or unexported fields
}
StreamedTurn streams thread events as they are produced during a run.
func (*StreamedTurn) Wait ¶
func (s *StreamedTurn) Wait() error
Wait blocks until the underlying run completes and returns the terminal error, if any.
type Thread ¶
type Thread struct {
// contains filtered or unexported fields
}
Thread represents a conversation with an agent. A thread can span multiple turns.
func (*Thread) Run ¶
Run executes a complete agent turn with the provided input and returns its result. The call blocks until the CLI exits or the context is cancelled.
func (*Thread) RunStreamed ¶
func (t *Thread) RunStreamed(ctx context.Context, input Input, turnOptions *TurnOptions) (*StreamedTurn, error)
RunStreamed streams events for a single agent turn. Callers should drain Events and then invoke Wait to retrieve any terminal error from the CLI.
func (*Thread) RunStreamedText ¶
func (t *Thread) RunStreamedText(ctx context.Context, prompt string, turnOptions *TurnOptions) (*StreamedTurn, error)
RunStreamedText is a convenience wrapper for RunStreamed with a text prompt.
type ThreadError ¶
type ThreadError struct {
Message string `json:"message"`
}
ThreadError describes a fatal error emitted by a turn.
type ThreadEvent ¶
type ThreadEvent struct {
// Type identifies the event kind.
Type EventType `json:"type"`
// ThreadID is populated on thread.started events with the server-issued identifier.
ThreadID string `json:"thread_id,omitempty"`
// Usage is populated on turn.completed events with token usage.
Usage *Usage `json:"usage,omitempty"`
// Error is populated on turn.failed events with the failure message.
Error *ThreadError `json:"error,omitempty"`
// Item contains the thread item payload for item.* events. It is nil for other event types.
Item ThreadItem `json:"item,omitempty"`
// Message is populated on top-level error events.
Message string `json:"message,omitempty"`
}
ThreadEvent represents a single line event emitted by codex exec.
func (ThreadEvent) String ¶
func (e ThreadEvent) String() string
String renders a human-readable description of the event for debugging and tests.
func (*ThreadEvent) UnmarshalJSON ¶
func (e *ThreadEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON customizes decoding to handle the polymorphic item payload.
type ThreadItem ¶
type ThreadItem interface {
ItemType() ItemType
}
ThreadItem is implemented by all concrete thread item types.
func UnmarshalThreadItem ¶
func UnmarshalThreadItem(data []byte) (ThreadItem, error)
UnmarshalThreadItem decodes a thread item into the corresponding Go type.
type ThreadOptions ¶
type ThreadOptions struct {
// Model selects the model identifier to run the agent with.
Model string
// SandboxMode controls the filesystem sandbox granted to the agent.
SandboxMode SandboxMode
// WorkingDirectory sets the directory provided to --cd when launching the CLI.
WorkingDirectory string
// SkipGitRepoCheck mirrors --skip-git-repo-check on the CLI.
SkipGitRepoCheck bool
}
ThreadOptions configure how a thread interacts with the codex CLI once created.
type TodoListItem ¶
type TodoListItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Items []TodoItem `json:"items"`
}
TodoListItem models the agent's running plan.
func (*TodoListItem) ItemType ¶
func (i *TodoListItem) ItemType() ItemType
type Turn ¶
type Turn struct {
// Items are the completed thread items emitted during the turn.
Items []ThreadItem
// FinalResponse is the assistant's last agent_message, when present.
FinalResponse string
// Usage reports token consumption for the turn. A nil value indicates the CLI
// did not emit usage information.
Usage *Usage
}
Turn contains the result of a completed agent turn.
type TurnOptions ¶
type TurnOptions struct {
// OutputSchema describes the expected JSON structure when requesting structured output.
// The value must marshal to a JSON object; validation occurs before each run.
OutputSchema any
}
TurnOptions configure a single turn when running the agent.
type UnknownThreadItem ¶
type UnknownThreadItem struct {
// Type holds the raw item type returned by the CLI.
Type ItemType `json:"type"`
// Raw retains the original JSON payload for callers that want to decode the item manually.
Raw json.RawMessage `json:"-"`
}
UnknownThreadItem preserves unrecognized item payloads.
func (*UnknownThreadItem) ItemType ¶
func (i *UnknownThreadItem) ItemType() ItemType
type Usage ¶
type Usage struct {
InputTokens int `json:"input_tokens"`
CachedInputTokens int `json:"cached_input_tokens"`
OutputTokens int `json:"output_tokens"`
}
Usage reports token usage for a turn.
type UserInput ¶
type UserInput struct {
// Type differentiates the payload stored in the other fields.
Type InputType `json:"type"`
// Text contains the textual prompt for InputTypeText entries.
Text string `json:"text,omitempty"`
// Path contains the local filesystem path for InputTypeLocalImage entries.
Path string `json:"path,omitempty"`
}
UserInput captures an individual segment of user supplied input.
func LocalImagePart ¶
LocalImagePart constructs a local image user input segment.
type WebSearchItem ¶
type WebSearchItem struct {
ID string `json:"id"`
Type ItemType `json:"type"`
Query string `json:"query"`
}
WebSearchItem captures a web search initiated by the agent.
func (*WebSearchItem) ItemType ¶
func (i *WebSearchItem) ItemType() ItemType