godex

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2025 License: MIT Imports: 14 Imported by: 0

README

godex – Go SDK for Codex

godex is an idiomatic Go wrapper around the Codex CLI. It mirrors the ergonomics of the official TypeScript SDK so that you can integrate Codex agents into Go applications with just a few calls.

Installation

go get github.com/activadee/godex

godex automatically downloads the Codex CLI into your user cache the first time it is needed. The cached build is keyed by platform and release tag so upgrades are seamless. Advanced users can override the cache directory or release tag via the GODEX_CLI_CACHE and GODEX_CLI_RELEASE_TAG environment variables. If you prefer to use a self-managed binary, set CodexOptions.CodexPathOverride or ensure the CLI is already available on your PATH (e.g. which codex). Authentication is handled entirely by the CLI; reuse whichever credentials you already configured (environment variables, codex auth login, etc.) or set CodexOptions.APIKey to override the API key programmatically:

export CODEX_API_KEY=sk-...
# or configure the CLI interactively
codex auth login

Override service endpoints (for self-hosted deployments) with CodexOptions.BaseURL.

Quick start

package main

import (
 "context"
 "fmt"

 "github.com/activadee/godex"
)

func main() {
 c, err := godex.New(godex.CodexOptions{})
 if err != nil {
  panic(err)
 }

 thread := c.StartThread(godex.ThreadOptions{
  Model: "gpt-5",
 })

 turn, err := thread.Run(context.Background(), "List three quick wins to speed up CI?", nil)
 if err != nil {
  panic(err)
 }

 fmt.Println("Assistant:", turn.FinalResponse)
}

Streaming events

ctx := context.Background()
result, err := thread.RunStreamed(ctx, "Summarize the latest changes.", nil)
if err != nil {
 log.Fatal(err)
}
defer result.Close()

for event := range result.Events() {
 switch e := event.(type) {
 case godex.ItemStartedEvent:
  log.Printf("item started: %T", e.Item)
 case godex.ItemCompletedEvent:
  log.Printf("item completed: %T", e.Item)
 case godex.TurnCompletedEvent:
  log.Printf("usage: %+v", e.Usage)
 }
}

if err := result.Wait(); err != nil {
 log.Fatal(err)
}
Streaming callbacks

Set TurnOptions.Callbacks to receive typed updates without writing a switch over ThreadEvent. The SDK invokes OnEvent first, followed by any matching typed callbacks, and finally forwards the raw event through Events(). Callbacks run on the streaming goroutine, so long-running work should be offloaded to avoid stalling the stream. You must continue draining the Events() channel (an empty for range loop works) to honour the CLI's backpressure expectations.

callbacks := &godex.StreamCallbacks{
	OnMessage: func(evt godex.StreamMessageEvent) {
		if evt.Stage == godex.StreamItemStageCompleted {
			log.Printf("assistant: %s", evt.Message.Text)
		}
	},
	OnCommand: func(evt godex.StreamCommandEvent) {
		log.Printf("command %s: %s", evt.Command.Status, evt.Command.Command)
	},
	OnPatch: func(evt godex.StreamPatchEvent) {
		log.Printf("patch %s: %s", evt.Patch.ID, evt.Patch.Status)
	},
	OnFileChange: func(evt godex.StreamFileChangeEvent) {
		log.Printf("  file %s (%s)", evt.Change.Path, evt.Change.Kind)
	},
}

result, err := thread.RunStreamed(ctx, "Summarize the latest changes.", &godex.TurnOptions{
	Callbacks: callbacks,
})
if err != nil {
	log.Fatal(err)
}
defer result.Close()

for range result.Events() {
	// Drain events; callbacks handled the typed work already.
}

if err := result.Wait(); err != nil {
	log.Fatal(err)
}

See examples/streaming_callbacks for a complete runnable sample.

Structured output

Pass a JSON schema in TurnOptions.OutputSchema and the SDK writes a temporary file for the CLI:

schema := map[string]any{
 "type": "object",
 "properties": map[string]any{
  "summary": map[string]any{"type": "string"},
 },
 "required": []string{"summary"},
}

turn, err := thread.Run(ctx, "Write a one sentence update.", &godex.TurnOptions{
 OutputSchema: schema,
})
Typed helpers

Generate and decode structured JSON into Go types with RunJSON / RunStreamedJSON. Provide your own schema or allow the helpers to infer one from T:

type Update struct {
 Headline string `json:"headline"`
 NextStep string `json:"next_step"`
}

result, err := godex.RunJSON[Update](ctx, thread, "Provide a concise update.", nil)
if err != nil {
 log.Fatal(err)
}
log.Printf("update: %+v", result)

Multi-part input and images

Mix text segments and local image paths by using RunInputs / RunStreamedInputs with InputSegment helpers. Text segments are joined with blank lines and each image path is forwarded to the CLI via --image:

segments := []godex.InputSegment{
 godex.TextSegment("Describe the image differences"),
 godex.LocalImageSegment("/tmp/baseline.png"),
 godex.LocalImageSegment("/tmp/current.png"),
}

turn, err := thread.RunInputs(ctx, segments, nil)
if err != nil {
 log.Fatal(err)
}

fmt.Println("Assistant:", turn.FinalResponse)

For remote assets or in-memory data, reach for the convenience constructors:

segment, err := godex.URLImageSegment(ctx, "https://example.com/image.png")
if err != nil {
 log.Fatal(err)
}

rawBytes := loadThumbnailBytes() // your own code that returns []byte

bytesSegment, err := godex.BytesImageSegment("thumbnail", rawBytes)
if err != nil {
 log.Fatal(err)
}

turn, err := thread.RunInputs(ctx, []godex.InputSegment{
 godex.TextSegment("Describe both images."),
 segment,
 bytesSegment,
}, nil)

URLImageSegment downloads the image to a temp file, verifies that the server returned an image/* content type, and schedules the file for cleanup once the run completes. Use BytesImageSegment when you already have the image bytes; it writes them to a temporary file with a suitable extension and cleans the file up automatically.

Examples

  • examples/basic: single-turn conversation (go run ./examples/basic)
  • examples/streaming: step-by-step event streaming demo (go run ./examples/streaming)
  • examples/schema: structured JSON output with schema validation (go run ./examples/schema)
  • examples/structured_output: typed structured output helpers (go run ./examples/structured_output)
  • examples/images: multi-part prompt mixing text and a local image (go run ./examples/images)

Thread persistence

Threads expose their ID once the thread.started event arrives. Store it and recreate a thread later:

savedID := thread.ID()
resumed := c.ResumeThread(savedID, godex.ThreadOptions{})

Sandbox settings

Configure the CLI sandbox, working directory, and git guardrails via ThreadOptions:

thread := c.StartThread(godex.ThreadOptions{
 SandboxMode:      godex.SandboxModeWorkspaceWrite,
 WorkingDirectory: "/tmp/workspace",
 SkipGitRepoCheck: true,
})

Selecting a profile programmatically

Set CLI configuration overrides on CodexOptions.ConfigOverrides. Any key named profile is forwarded as --profile, while the rest become -c key=value pairs:

client, err := godex.New(godex.CodexOptions{
 ConfigOverrides: map[string]any{
  "profile":        "production",
  "feature.toggle": true,
 },
})
if err != nil {
 log.Fatal(err)
}

Development

Run the tests locally:

go test ./...

Because the CLI is not bundled with the repository, integration tests that spawn Codex are not included. Use CodexOptions.CodexPathOverride to point at a custom binary when exercising end-to-end flows.

Error handling

Thread.Run and Thread.RunStreamed surface failures in a few ways:

  • Turn-level errors (turn.failed events) return a Go error whose message mirrors the CLI output.
  • Stream-level errors (error events) abort the stream with a *godex.ThreadStreamError, exposing the reported message and allowing errors.As checks.
  • Process failures (non-zero CLI exit) propagate the exit code and stderr via Runner.Run.

Always check the returned error when the agent turn completes.

Documentation

Overview

Package godex provides an idiomatic Go SDK for orchestrating Codex agents through the Codex CLI.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoStructuredOutput indicates that the turn completed without returning a structured
	// response that could be decoded into the requested type.
	ErrNoStructuredOutput = errors.New("structured output not returned")
)

Functions

func RunJSON added in v0.0.6

func RunJSON[T any](ctx context.Context, thread *Thread, input string, options *RunJSONOptions[T]) (T, error)

RunJSON executes a turn expecting a structured JSON response that can be decoded into T.

Types

type AgentMessageItem

type AgentMessageItem struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	Text string `json:"text"`
}

AgentMessageItem contains the model's response payload (natural language or structured JSON).

type ApprovalMode

type ApprovalMode string

ApprovalMode describes how the Codex CLI should request approval for actions that might require user consent. The Codex CLI itself interprets these values, the SDK merely forwards them when provided.

const (
	ApprovalModeNever     ApprovalMode = "never"
	ApprovalModeOnRequest ApprovalMode = "on-request"
	ApprovalModeOnFailure ApprovalMode = "on-failure"
	ApprovalModeUntrusted ApprovalMode = "untrusted"
)

type Codex

type Codex struct {
	// contains filtered or unexported fields
}

Codex is the entrypoint for interacting with the Codex agent via the CLI.

func New

func New(options CodexOptions) (*Codex, error)

New constructs a Codex SDK instance. The Codex binary is discovered automatically unless CodexOptions.CodexPathOverride is provided.

func (*Codex) ResumeThread

func (c *Codex) ResumeThread(id string, options ThreadOptions) *Thread

ResumeThread recreates a thread using a previously obtained thread identifier.

func (*Codex) StartThread

func (c *Codex) StartThread(options ThreadOptions) *Thread

StartThread opens a new thread with the agent.

type CodexOptions

type CodexOptions struct {
	// CodexPathOverride allows specifying the path to a Codex binary instead of the bundled one.
	CodexPathOverride string
	// BaseURL overrides the service endpoint used by the Codex CLI.
	BaseURL string
	// APIKey optionally overrides authentication for the Codex CLI. When empty, the CLI
	// falls back to its own configured credentials (e.g. environment variables or auth login).
	APIKey string
	// ConfigOverrides forwards CLI configuration overrides as `-c key=value` pairs. When
	// the `profile` key is present it is emitted as `--profile <value>` instead.
	ConfigOverrides map[string]any
}

CodexOptions configure the SDK itself rather than an individual thread.

type CommandExecutionItem

type CommandExecutionItem struct {
	ID               string                 `json:"id"`
	Type             string                 `json:"type"`
	Command          string                 `json:"command"`
	AggregatedOutput string                 `json:"aggregated_output"`
	ExitCode         *int                   `json:"exit_code,omitempty"`
	Status           CommandExecutionStatus `json:"status"`
}

CommandExecutionItem captures a command execution requested by the agent.

type CommandExecutionStatus

type CommandExecutionStatus string

CommandExecutionStatus represents the lifecycle stage of a command started by the agent.

const (
	CommandExecutionStatusInProgress CommandExecutionStatus = "in_progress"
	CommandExecutionStatusCompleted  CommandExecutionStatus = "completed"
	CommandExecutionStatusFailed     CommandExecutionStatus = "failed"
)

type ErrorItem

type ErrorItem struct {
	ID      string `json:"id"`
	Type    string `json:"type"`
	Message string `json:"message"`
}

ErrorItem captures non-fatal errors emitted by the agent.

type FileChangeItem

type FileChangeItem struct {
	ID      string             `json:"id"`
	Type    string             `json:"type"`
	Changes []FileUpdateChange `json:"changes"`
	Status  PatchApplyStatus   `json:"status"`
}

FileChangeItem aggregates the set of file updates that comprise a patch.

type FileUpdateChange

type FileUpdateChange struct {
	Path string          `json:"path"`
	Kind PatchChangeKind `json:"kind"`
}

FileUpdateChange represents a single file edit made by the agent.

type InputSegment added in v0.0.2

type InputSegment struct {
	// Text holds a natural-language prompt fragment. Leave empty to indicate the
	// segment references an image instead.
	Text string

	// LocalImagePath contains a filesystem path to an image that should be
	// forwarded to the CLI via --image. Leave empty for text segments.
	LocalImagePath string
	// contains filtered or unexported fields
}

InputSegment represents a piece of user-provided input sent to the Codex CLI. Exactly one of Text or LocalImagePath must be populated.

func BytesImageSegment added in v0.0.6

func BytesImageSegment(name string, data []byte) (InputSegment, error)

BytesImageSegment writes the provided image bytes to a temporary file and returns a segment that references it. The file is cleaned up automatically when the run finishes.

func LocalImageSegment added in v0.0.2

func LocalImageSegment(path string) InputSegment

LocalImageSegment creates an input segment pointing at a local image file. The path is forwarded to the Codex CLI using repeated --image flags.

func TextSegment added in v0.0.2

func TextSegment(text string) InputSegment

TextSegment creates a textual input segment. Multiple text segments are concatenated with blank lines between them, matching the TypeScript SDK's behaviour.

func URLImageSegment added in v0.0.6

func URLImageSegment(ctx context.Context, rawURL string) (InputSegment, error)

URLImageSegment downloads an image from the provided URL into a temporary file and returns an input segment that references it. The file is cleaned up automatically when the run finishes.

type ItemCompletedEvent

type ItemCompletedEvent struct {
	Type ThreadEventType `json:"type"`
	Item ThreadItem      `json:"item"`
}

ItemCompletedEvent signals an item reaching a terminal state.

func (ItemCompletedEvent) EventType

func (e ItemCompletedEvent) EventType() ThreadEventType

type ItemStartedEvent

type ItemStartedEvent struct {
	Type ThreadEventType `json:"type"`
	Item ThreadItem      `json:"item"`
}

ItemStartedEvent emits when a thread item is created.

func (ItemStartedEvent) EventType

func (e ItemStartedEvent) EventType() ThreadEventType

type ItemUpdatedEvent

type ItemUpdatedEvent struct {
	Type ThreadEventType `json:"type"`
	Item ThreadItem      `json:"item"`
}

ItemUpdatedEvent emits as an item transitions between intermediate states.

func (ItemUpdatedEvent) EventType

func (e ItemUpdatedEvent) EventType() ThreadEventType

type McpToolCallItem

type McpToolCallItem struct {
	ID     string            `json:"id"`
	Type   string            `json:"type"`
	Server string            `json:"server"`
	Tool   string            `json:"tool"`
	Status McpToolCallStatus `json:"status"`
}

McpToolCallItem represents activity relating to a single MCP tool call.

type McpToolCallStatus

type McpToolCallStatus string

McpToolCallStatus describes the status of an MCP tool invocation.

const (
	McpToolCallStatusInProgress McpToolCallStatus = "in_progress"
	McpToolCallStatusCompleted  McpToolCallStatus = "completed"
	McpToolCallStatusFailed     McpToolCallStatus = "failed"
)

type PatchApplyStatus

type PatchApplyStatus string

PatchApplyStatus indicates whether the patch was applied successfully.

const (
	PatchApplyStatusCompleted PatchApplyStatus = "completed"
	PatchApplyStatusFailed    PatchApplyStatus = "failed"
)

type PatchChangeKind

type PatchChangeKind string

PatchChangeKind indicates how a file changed.

const (
	PatchChangeKindAdd    PatchChangeKind = "add"
	PatchChangeKindDelete PatchChangeKind = "delete"
	PatchChangeKindUpdate PatchChangeKind = "update"
)

type ReasoningItem

type ReasoningItem struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	Text string `json:"text"`
}

ReasoningItem provides insight into the agent's intermediate reasoning.

type RunJSONOptions added in v0.0.6

type RunJSONOptions[T any] struct {
	// TurnOptions forwards additional options for the turn. When nil a zero TurnOptions
	// value is used.
	TurnOptions *TurnOptions
	// Schema provides an explicit JSON schema for the structured output. When nil the
	// helper attempts schema inference unless DisableSchemaInference is true.
	Schema any
	// DisableSchemaInference prevents automatic schema inference from T when Schema is nil.
	DisableSchemaInference bool
}

RunJSONOptions configure a typed JSON turn.

type RunResult

type RunResult = Turn

RunResult is an alias for Turn to mirror the TypeScript SDK naming.

type RunStreamedJSONResult added in v0.0.6

type RunStreamedJSONResult[T any] struct {
	// contains filtered or unexported fields
}

RunStreamedJSONResult exposes the streaming lifecycle for a typed structured output turn.

func RunStreamedJSON added in v0.0.6

func RunStreamedJSON[T any](ctx context.Context, thread *Thread, input string, options *RunJSONOptions[T]) (RunStreamedJSONResult[T], error)

RunStreamedJSON executes a turn expecting structured JSON output and streams raw events alongside typed snapshots decoded into T.

func (RunStreamedJSONResult[T]) Close added in v0.0.6

func (r RunStreamedJSONResult[T]) Close() error

Close cancels the turn and waits for shutdown.

func (RunStreamedJSONResult[T]) Events added in v0.0.6

func (r RunStreamedJSONResult[T]) Events() <-chan ThreadEvent

Events returns the stream of raw thread events produced by the turn.

func (RunStreamedJSONResult[T]) Updates added in v0.0.6

func (r RunStreamedJSONResult[T]) Updates() <-chan RunStreamedJSONUpdate[T]

Updates yields typed structured output snapshots. The channel closes once the turn finishes.

func (RunStreamedJSONResult[T]) Wait added in v0.0.6

func (r RunStreamedJSONResult[T]) Wait() error

Wait blocks until the turn finishes and returns the terminal error, if any.

type RunStreamedJSONUpdate added in v0.0.6

type RunStreamedJSONUpdate[T any] struct {
	Value T
	Raw   string
	Final bool
}

RunStreamedJSONUpdate captures a typed snapshot of the structured output as the turn progresses.

type RunStreamedResult

type RunStreamedResult struct {
	// contains filtered or unexported fields
}

RunStreamedResult is returned by Thread.RunStreamed and exposes the event stream.

func (RunStreamedResult) Close

func (r RunStreamedResult) Close() error

Close cancels the stream context and waits for shutdown.

func (RunStreamedResult) Events

func (r RunStreamedResult) Events() <-chan ThreadEvent

Events returns the channel that yields events sequentially as they arrive.

func (RunStreamedResult) Wait

func (r RunStreamedResult) Wait() error

Wait blocks until the stream finishes and returns the terminal error, if any.

type SandboxMode

type SandboxMode string

SandboxMode mirrors the CLI sandbox configuration that controls which filesystem operations the agent may perform.

const (
	SandboxModeReadOnly         SandboxMode = "read-only"
	SandboxModeWorkspaceWrite   SandboxMode = "workspace-write"
	SandboxModeDangerFullAccess SandboxMode = "danger-full-access"
)

type SchemaViolationError added in v0.0.6

type SchemaViolationError struct {
	Message string
}

SchemaViolationError indicates that the structured output failed schema validation.

func (*SchemaViolationError) Error added in v0.0.6

func (e *SchemaViolationError) Error() string

Error implements the error interface.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is an internal helper that coordinates the lifecycle of a streaming turn.

func (*Stream) Close

func (s *Stream) Close() error

func (*Stream) Events

func (s *Stream) Events() <-chan ThreadEvent

func (*Stream) Wait

func (s *Stream) Wait() error

type StreamCallbacks added in v0.0.7

type StreamCallbacks struct {
	// OnEvent fires for every event before any type-specific callback.
	OnEvent func(ThreadEvent)

	OnThreadStarted func(ThreadStartedEvent)
	OnTurnStarted   func(TurnStartedEvent)
	OnTurnCompleted func(TurnCompletedEvent)
	OnTurnFailed    func(TurnFailedEvent)
	OnThreadError   func(ThreadErrorEvent)

	OnMessage    func(StreamMessageEvent)
	OnReasoning  func(StreamReasoningEvent)
	OnCommand    func(StreamCommandEvent)
	OnPatch      func(StreamPatchEvent)
	OnFileChange func(StreamFileChangeEvent)
	OnWebSearch  func(StreamWebSearchEvent)
	OnToolCall   func(StreamToolCallEvent)
	OnTodoList   func(StreamTodoListEvent)
	OnErrorItem  func(StreamErrorItemEvent)
}

StreamCallbacks enumerates optional hooks invoked when streaming events are delivered.

type StreamCommandEvent added in v0.0.7

type StreamCommandEvent struct {
	Stage   StreamItemStage
	Command CommandExecutionItem
}

StreamCommandEvent describes a callback payload for command execution items.

type StreamErrorItemEvent added in v0.0.7

type StreamErrorItemEvent struct {
	Stage StreamItemStage
	Error ErrorItem
}

StreamErrorItemEvent describes a callback payload for non-fatal error items.

type StreamFileChangeEvent added in v0.0.7

type StreamFileChangeEvent struct {
	Stage  StreamItemStage
	Patch  FileChangeItem
	Change FileUpdateChange
}

StreamFileChangeEvent describes a callback payload for each file updated within a patch.

type StreamItemStage added in v0.0.7

type StreamItemStage string

StreamItemStage indicates which phase of the lifecycle produced a callback.

const (
	StreamItemStageStarted   StreamItemStage = "started"
	StreamItemStageUpdated   StreamItemStage = "updated"
	StreamItemStageCompleted StreamItemStage = "completed"
)

type StreamMessageEvent added in v0.0.7

type StreamMessageEvent struct {
	Stage   StreamItemStage
	Message AgentMessageItem
}

StreamMessageEvent describes a callback payload for agent message items.

type StreamPatchEvent added in v0.0.7

type StreamPatchEvent struct {
	Stage StreamItemStage
	Patch FileChangeItem
}

StreamPatchEvent describes a callback payload for patch/file change items.

type StreamReasoningEvent added in v0.0.7

type StreamReasoningEvent struct {
	Stage     StreamItemStage
	Reasoning ReasoningItem
}

StreamReasoningEvent describes a callback payload for reasoning items.

type StreamTodoListEvent added in v0.0.7

type StreamTodoListEvent struct {
	Stage StreamItemStage
	List  TodoListItem
}

StreamTodoListEvent describes a callback payload for todo list items.

type StreamToolCallEvent added in v0.0.7

type StreamToolCallEvent struct {
	Stage    StreamItemStage
	ToolCall McpToolCallItem
}

StreamToolCallEvent describes a callback payload for MCP tool call items.

type StreamWebSearchEvent added in v0.0.7

type StreamWebSearchEvent struct {
	Stage  StreamItemStage
	Search WebSearchItem
}

StreamWebSearchEvent describes a callback payload for web search items.

type Thread

type Thread struct {
	// contains filtered or unexported fields
}

Thread encapsulates a conversation with the Codex agent. It is safe to reuse a Thread across sequential turns, but concurrent Run/RunStreamed calls on the same Thread are not supported.

func (*Thread) ID

func (t *Thread) ID() string

ID returns the identifier of the thread. For new threads this becomes available after the first `thread.started` event is received.

func (*Thread) Run

func (t *Thread) Run(ctx context.Context, input string, turnOptions *TurnOptions) (RunResult, error)

Run submits the input to the agent and waits for the turn to finish, returning the final response.

func (*Thread) RunInputs added in v0.0.2

func (t *Thread) RunInputs(ctx context.Context, segments []InputSegment, turnOptions *TurnOptions) (RunResult, error)

RunInputs mirrors Run but accepts structured input segments.

func (*Thread) RunStreamed

func (t *Thread) RunStreamed(ctx context.Context, input string, turnOptions *TurnOptions) (RunStreamedResult, error)

RunStreamed submits the provided input to the agent and streams events as they occur.

func (*Thread) RunStreamedInputs added in v0.0.2

func (t *Thread) RunStreamedInputs(ctx context.Context, segments []InputSegment, turnOptions *TurnOptions) (RunStreamedResult, error)

RunStreamedInputs behaves like RunStreamed but accepts structured input segments, allowing callers to mix multiple text fragments and local image paths.

type ThreadError

type ThreadError struct {
	Message string `json:"message"`
}

ThreadError represents a fatal error emitted for the turn.

type ThreadErrorEvent

type ThreadErrorEvent struct {
	Type    ThreadEventType `json:"type"`
	Message string          `json:"message"`
}

ThreadErrorEvent is emitted when the stream itself experiences an unrecoverable error.

func (ThreadErrorEvent) EventType

func (e ThreadErrorEvent) EventType() ThreadEventType

type ThreadEvent

type ThreadEvent interface {
	EventType() ThreadEventType
	// contains filtered or unexported methods
}

ThreadEvent is the interface implemented by all event variants returned by the CLI.

type ThreadEventType

type ThreadEventType string

ThreadEventType enumerates the JSON event types streamed by the Codex CLI.

const (
	ThreadEventTypeThreadStarted ThreadEventType = "thread.started"
	ThreadEventTypeTurnStarted   ThreadEventType = "turn.started"
	ThreadEventTypeTurnCompleted ThreadEventType = "turn.completed"
	ThreadEventTypeTurnFailed    ThreadEventType = "turn.failed"
	ThreadEventTypeItemStarted   ThreadEventType = "item.started"
	ThreadEventTypeItemUpdated   ThreadEventType = "item.updated"
	ThreadEventTypeItemCompleted ThreadEventType = "item.completed"
	ThreadEventTypeError         ThreadEventType = "error"
)

type ThreadItem

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

ThreadItem is the polymorphic representation of all items that can appear on a thread.

type ThreadItemType

type ThreadItemType string

ThreadItemType enumerates all valid thread item type strings.

const (
	ThreadItemTypeAgentMessage     ThreadItemType = "agent_message"
	ThreadItemTypeReasoning        ThreadItemType = "reasoning"
	ThreadItemTypeCommandExecution ThreadItemType = "command_execution"
	ThreadItemTypeFileChange       ThreadItemType = "file_change"
	ThreadItemTypeMcpToolCall      ThreadItemType = "mcp_tool_call"
	ThreadItemTypeWebSearch        ThreadItemType = "web_search"
	ThreadItemTypeTodoList         ThreadItemType = "todo_list"
	ThreadItemTypeError            ThreadItemType = "error"
)

ThreadItemType constants.

type ThreadOptions

type ThreadOptions struct {
	// Model specifies the model identifier to use for the thread.
	Model string
	// SandboxMode controls the CLI sandbox setting (equivalent to `--sandbox` flag).
	SandboxMode SandboxMode
	// WorkingDirectory sets the working directory for the agent (`--cd` flag).
	WorkingDirectory string
	// SkipGitRepoCheck mirrors the CLI flag `--skip-git-repo-check`.
	SkipGitRepoCheck bool
}

ThreadOptions configure how the CLI executes a particular thread.

type ThreadStartedEvent

type ThreadStartedEvent struct {
	Type     ThreadEventType `json:"type"`
	ThreadID string          `json:"thread_id"`
}

ThreadStartedEvent is emitted when a new thread is created.

func (ThreadStartedEvent) EventType

func (e ThreadStartedEvent) EventType() ThreadEventType

type ThreadStreamError added in v0.0.3

type ThreadStreamError struct {
	ThreadError
}

ThreadStreamError wraps a thread-level error emitted by the Codex CLI. It is returned when Run/RunInputs encounter a `thread.error` event or when RunStreamedResult.Wait is invoked after such an event.

func (*ThreadStreamError) Error added in v0.0.3

func (e *ThreadStreamError) Error() string

Error implements the error interface.

type TodoItem

type TodoItem struct {
	Text      string `json:"text"`
	Completed bool   `json:"completed"`
}

TodoItem represents a single task within the agent's to-do list.

type TodoListItem

type TodoListItem struct {
	ID    string     `json:"id"`
	Type  string     `json:"type"`
	Items []TodoItem `json:"items"`
}

TodoListItem tracks the set of tasks managed by the agent during a turn.

type Turn

type Turn struct {
	Items         []ThreadItem
	FinalResponse string
	Usage         *Usage
}

Turn represents a fully completed turn from the Codex agent.

type TurnCompletedEvent

type TurnCompletedEvent struct {
	Type  ThreadEventType `json:"type"`
	Usage Usage           `json:"usage"`
}

TurnCompletedEvent indicates a successful completion of a turn.

func (TurnCompletedEvent) EventType

func (e TurnCompletedEvent) EventType() ThreadEventType

type TurnFailedEvent

type TurnFailedEvent struct {
	Type  ThreadEventType `json:"type"`
	Error ThreadError     `json:"error"`
}

TurnFailedEvent signals that a turn ended due to a fatal error.

func (TurnFailedEvent) EventType

func (e TurnFailedEvent) EventType() ThreadEventType

type TurnOptions

type TurnOptions struct {
	// OutputSchema is an optional JSON schema describing the structured response to
	// collect from the agent. Must serialize to a JSON object (not an array or primitive).
	OutputSchema any
	// Callbacks attaches optional streaming callbacks invoked as events arrive.
	Callbacks *StreamCallbacks
}

TurnOptions configure a single turn executed within a thread.

type TurnStartedEvent

type TurnStartedEvent struct {
	Type ThreadEventType `json:"type"`
}

TurnStartedEvent marks the beginning of a new turn.

func (TurnStartedEvent) EventType

func (e TurnStartedEvent) EventType() ThreadEventType

type Usage

type Usage struct {
	InputTokens       int `json:"input_tokens"`
	CachedInputTokens int `json:"cached_input_tokens"`
	OutputTokens      int `json:"output_tokens"`
}

Usage captures token consumption metrics for a completed turn.

type WebSearchItem

type WebSearchItem struct {
	ID    string `json:"id"`
	Type  string `json:"type"`
	Query string `json:"query"`
}

WebSearchItem denotes a web search performed by the agent.

Directories

Path Synopsis
examples
basic command
images command
schema command
streaming command
internal

Jump to

Keyboard shortcuts

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