codex

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package codex is the agent_kind="codex" adapter. It drives the OpenAI Codex CLI (codex-rs / @openai/codex) via `codex app-server --stdio`, speaking the JSON-RPC 2.0 protocol that the app-server exposes over stdio.

Codex uses an app-server transport:

  1. The wire protocol is JSON-RPC (request / response / notification / server-request) rather than NDJSON event-stream. See rpc.go.

  2. Multi-turn context lives in a Codex "thread" identified by the thread_id returned in the first `thread/started` notification. The daemon stamps that id into DonePayload.Metadata["agent_session_id"] so the connector's RememberSession path persists it. Subsequent turns spawn a fresh app-server and call `thread/resume` with that id to graft the prior turn's context back in.

Index

Constants

View Source
const InstallURL = "https://github.com/openai/codex"

InstallURL points operators at the Codex install instructions when the daemon can see the adapter but not the CLI binary.

View Source
const JsonRpcVersion = "2.0"

JsonRpcVersion is the JSON-RPC 2.0 marker carried on every outbound frame. Inbound frames omit the field per Codex's app-server convention, so the parser does not enforce it on responses.

View Source
const SupportsTextVerbosity = true

SupportsTextVerbosity requires bounded cancellation of the catalog probe.

Variables

View Source
var Declaration = agent.Declaration{Info: proto.SupportedAgentKind{
	Kind: "codex",
	Capabilities: proto.AgentKindCapabilities{
		SubagentObservations:           proto.CapabilitySupported,
		Streaming:                      proto.CapabilitySupported,
		Permissions:                    proto.CapabilitySupported,
		Usage:                          proto.CapabilitySupported,
		Resume:                         proto.CapabilitySupported,
		NativeSessionRecovery:          proto.CapabilityUnsupported,
		WorkspaceAuthoring:             proto.CapabilitySupported,
		Steering:                       proto.CapabilitySupported,
		MessageItems:                   proto.CapabilitySupported,
		ToolObservations:               proto.CapabilitySupported,
		EnvironmentNone:                proto.CapabilitySupported,
		LocalEnvironment:               proto.CapabilityUnsupported,
		Preparation:                    proto.CapabilityUnsupported,
		WorkspaceReadPreparation:       proto.CapabilityUnsupported,
		WorkspaceOutputExport:          proto.CapabilityUnsupported,
		ProgrammaticToolCallingDisable: proto.CapabilitySupported,
		WebSearchControl:               proto.CapabilitySupported,
		ExecutionControls:              proto.CapabilityFromBool(SupportsTextVerbosity),
		TextVerbosity:                  proto.CapabilityFromBool(SupportsTextVerbosity),
		StructuredOutput:               proto.CapabilityUnsupported,
		ToolSearch:                     proto.CapabilityUnsupported,
		MessageImages:                  proto.CapabilitySupported,
		FunctionResultImages:           proto.CapabilitySupported,
		SubagentControl:                proto.CapabilitySupported,
		DurableInputReceipts:           proto.CapabilitySupported,
		DurableTurns:                   proto.CapabilitySupported,
		FunctionTools:                  proto.CapabilitySupported,
		MCPHTTPTools:                   proto.CapabilitySupported,
		MCPHTTPRequired:                proto.CapabilityUnsupported,
		MCPHTTPBearerAuth:              proto.CapabilitySupported,
	},
}, Configuration: configuration.Configuration(), Discover: discover}

Declaration owns Codex discovery, configuration and execution factories.

View Source
var DeferReply = deferReplySentinel{}

DeferReply, when returned from a ServerRequestHandler, signals that the handler will reply later via SendServerReply.

View Source
var ErrCLINotFound = errors.New("codex CLI not found")

ErrCLINotFound is returned by CheckCLIAvailable when the binary cannot be located on PATH. Callers use errors.Is to distinguish an install problem from a present-but-broken CLI.

Functions

func CheckCLIAvailable

func CheckCLIAvailable(ctx context.Context, binary string) (string, error)

CheckCLIAvailable runs `<binary> --version` and returns the trimmed first line. The empty binary name defaults to defaultBinary(). Matches the CLI availability check signature so connect.go's preflight loop treats every engine uniformly.

func DispatchCompletedItem

func DispatchCompletedItem(runID string, item ThreadItem, bufs *ItemBuffers) (envelopes []proto.Envelope, agentText string, err error)

DispatchCompletedItem folds an item.completed payload into envelopes. Reasoning and agentMessage produce a final TypeThinking / TypeDelta (delta+sequence=0) so the buffer drained by upstream deltas can be flushed; tool-call variants produce an "after" envelope so the UI gets a stage transition.

emitFinalDelta=true asks the dispatch to emit a synthetic full-text TypeDelta whose Sequence will be set by the caller using a session- level monotonic counter; this is only needed when no deltas were observed (item.completed arrived without any item/agentMessage/delta).

Returns the agent text body for agentMessage items so the session can stamp it into DonePayload.Content. Empty string for everything else.

func DispatchStartedItem

func DispatchStartedItem(runID string, item ThreadItem) ([]proto.Envelope, error)

DispatchStartedItem maps the item.started variants we care about (tool_call surfaces) into proto envelopes. The function never returns terminal envelopes; per Codex, only item/completed + turn/completed can finish a turn.

item types we silence by intent:

  • reasoning / agentMessage / userMessage: text is streamed via deltas and re-stamped in item/completed
  • error: surfaced by turn/completed.status="failed" instead

func Factory

func Factory(ctx context.Context, req proto.PromptRequestPayload, out chan<- proto.Envelope) (agent.Session, error)

Factory implements agent.Factory for agent_kind="codex". Spawns one codex app-server child per prompt. The run stream closes when the turn completes; the router retains the child until the conversation's idle window expires or cancellation shuts it down sooner.

func FoldDeltaIntoBuffer

func FoldDeltaIntoBuffer(bufs *ItemBuffers, kind, itemID, delta string) string

FoldDeltaIntoBuffer accumulates a delta string under the matching itemId. Returns the running prefix so the caller can emit a progressive TypeDelta / TypeThinking envelope for streaming UI.

func Installation

func Installation() agent.Installation

func IsSilent

func IsSilent(p *AskForApproval) bool

IsSilent reports whether p suppresses every approval surface. The daemon logs this distinction when it starts a thread. Server-request handlers are always registered so explicit policy overrides cannot leave Codex waiting on an unhandled request.

A nil pointer is treated as silent — the safe default when callers forget to wire a policy.

func NewExecutorFactory

func NewExecutorFactory() agent.ExecutorFactory

func SupportsLocalEnvironment

func SupportsLocalEnvironment(version string) bool

SupportsLocalEnvironment checks deployment prerequisites, not public admission.

func SupportsNativeSessionRecovery

func SupportsNativeSessionRecovery(version string) bool

Types

type AgentMessageDeltaNotification

type AgentMessageDeltaNotification struct {
	ThreadID string `json:"threadId"`
	TurnID   string `json:"turnId"`
	ItemID   string `json:"itemId"`
	Delta    string `json:"delta"`
}

type ApprovalDecisionResult

type ApprovalDecisionResult struct {
	Decision CommandExecutionApprovalDecision `json:"decision"`
}

ApprovalDecisionResult is the result body for command-execution and file-change approvals. item/permissions/requestApproval uses the distinct PermissionsRequestApprovalResponse contract below.

type AskForApproval

type AskForApproval struct {
	String   string                  // "" when granular is set
	Granular *GranularAskForApproval // nil when string is set
}

AskForApproval is the discriminated union codex accepts on ThreadStartParams.approvalPolicy. The serialiser must emit EITHER {"granular": {...}} OR a bare string ("never" / "on-request" / "on-failure" / "untrusted"). See MarshalJSON in approval_policy.go.

func HumanApprovalPolicy

func HumanApprovalPolicy() AskForApproval

HumanApprovalPolicy lets Codex request sandbox escalation from Core.

func SilentGranularPolicy

func SilentGranularPolicy() AskForApproval

SilentGranularPolicy disables every granular Codex approval gate.

func (AskForApproval) MarshalJSON

func (a AskForApproval) MarshalJSON() ([]byte, error)

MarshalJSON emits codex-rs's discriminated union — either a bare string or the granular object. Producing both would deserialise to the granular branch on the codex side (it wins precedence in codex-rs/protocol.rs AskForApproval), but the wire would be wrong; we validate exclusivity here.

func (*AskForApproval) UnmarshalJSON

func (a *AskForApproval) UnmarshalJSON(data []byte) error

UnmarshalJSON is the inverse: codex's ThreadStartResult.approvalPolicy echoes back as either a string or {"granular":...}. Provided so tests can round-trip without surprises; production code only marshals.

type CollaborationMode

type CollaborationMode struct {
	Mode     CollaborationModeKind     `json:"mode"`
	Settings CollaborationModeSettings `json:"settings"`
}

type CollaborationModeKind

type CollaborationModeKind string
const (
	CollaborationModePlan    CollaborationModeKind = "plan"
	CollaborationModeDefault CollaborationModeKind = "default"
)

type CollaborationModeSettings

type CollaborationModeSettings struct {
	ReasoningEffort       string  `json:"reasoning_effort,omitempty"`
	Model                 string  `json:"model"`
	DeveloperInstructions *string `json:"developer_instructions"`
}

type CommandExecutionApprovalDecision

type CommandExecutionApprovalDecision = string

CommandExecutionApprovalDecision is the verdict the daemon writes back to a Codex approval ServerRequest. "accept" / "decline" / "cancel" / "acceptForSession".

type CommandExecutionRequestApprovalParams

type CommandExecutionRequestApprovalParams struct {
	ThreadID string  `json:"threadId"`
	TurnID   string  `json:"turnId"`
	ItemID   string  `json:"itemId"`
	Command  *string `json:"command,omitempty"`
	Cwd      *string `json:"cwd,omitempty"`
	Reason   *string `json:"reason,omitempty"`
}

type ErrorNotification

type ErrorNotification struct {
	ThreadID string     `json:"threadId"`
	TurnID   string     `json:"turnId"`
	Error    *TurnError `json:"error,omitempty"`
	Message  string     `json:"message,omitempty"`
}

type Executor

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

Executor owns the prepared process, fixed plan and native thread. Each StartTurn creates independent receipt, observation, cancellation and output ownership.

func (*Executor) Close

func (e *Executor) Close(ctx context.Context) error

func (*Executor) ListWorkspaceDirectory

func (s *Executor) ListWorkspaceDirectory(context.Context, string, int) (agent.WorkspaceDirectoryResult, error)

func (*Executor) ReadWorkspaceFile

func (s *Executor) ReadWorkspaceFile(context.Context, string, int) (agent.WorkspaceReadResult, error)

func (*Executor) StartTurn

func (e *Executor) StartTurn(ctx context.Context, runID string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error)

func (*Executor) WriteWorkspaceFile

func (s *Executor) WriteWorkspaceFile(context.Context, string, []byte) (agent.WorkspaceWriteResult, error)

type FileChangeRequestApprovalParams

type FileChangeRequestApprovalParams struct {
	ThreadID  string  `json:"threadId"`
	TurnID    string  `json:"turnId"`
	ItemID    string  `json:"itemId"`
	Reason    *string `json:"reason,omitempty"`
	GrantRoot *string `json:"grantRoot,omitempty"`
}

type GranularAskForApproval

type GranularAskForApproval struct {
	SandboxApproval    bool `json:"sandbox_approval"`
	Rules              bool `json:"rules"`
	SkillApproval      bool `json:"skill_approval"`
	RequestPermissions bool `json:"request_permissions"`
	MCPElicitations    bool `json:"mcp_elicitations"`
}

GranularAskForApproval names each approval gate the codex agent can surface. All-false produces a fully silent run; turning any single field true makes the corresponding ServerRequest reach the daemon for human approval.

JSON tags MUST stay snake_case — codex-rs deserialises this struct from a config TOML / RPC param with field names like sandbox_approval, and renaming silently breaks the wire.

type InitializeCapabilities

type InitializeCapabilities struct {
	ExperimentalAPI    bool      `json:"experimentalApi"`
	RequestAttestation bool      `json:"requestAttestation"`
	OptOutMethods      *[]string `json:"optOutNotificationMethods,omitempty"`
}

InitializeCapabilities mirrors codex-rs/app-server/src/protocol.rs. experimentalApi=true opts into the granular AskForApproval enum and the thread/* notification stream.

type InitializeClientInfo

type InitializeClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

type InitializeParams

type InitializeParams struct {
	ClientInfo   InitializeClientInfo    `json:"clientInfo"`
	Capabilities *InitializeCapabilities `json:"capabilities"`
}

type InitializeResult

type InitializeResult struct {
	UserAgent      string `json:"userAgent"`
	CodexHome      string `json:"codexHome"`
	PlatformFamily string `json:"platformFamily,omitempty"`
	PlatformOs     string `json:"platformOs,omitempty"`
}

type ItemBuffers

type ItemBuffers struct {
	Reasoning map[string]string
	AgentText map[string]string
}

ItemBuffers holds the per-itemId text accumulators used to fold delta notifications back into a single chunk on item/completed. Codex streams reasoning and agentMessage in two channels — the {reasoning,agentMessage}/delta notifications, plus the final item body on item/completed. We keep both: deltas drive incremental UI (TypeDelta / TypeThinking), and completed-item bodies anchor the final text for the done event.

func NewItemBuffers

func NewItemBuffers() *ItemBuffers

NewItemBuffers returns an empty buffer set.

type ItemCompletedNotification

type ItemCompletedNotification struct {
	ThreadID      string     `json:"threadId"`
	TurnID        string     `json:"turnId"`
	Item          ThreadItem `json:"item"`
	CompletedAtMs int64      `json:"completedAtMs,omitempty"`
}

type ItemStartedNotification

type ItemStartedNotification struct {
	ThreadID    string     `json:"threadId"`
	TurnID      string     `json:"turnId"`
	Item        ThreadItem `json:"item"`
	StartedAtMs int64      `json:"startedAtMs,omitempty"`
}

type JSONRPCClient

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

JSONRPCClient drives one `codex app-server --stdio` child process, speaking JSON-RPC 2.0 over stdin/stdout NDJSON. Three inbound message shapes are supported:

  • response (id + result|error) → matched to a pending request
  • notification (method + params, no id) → routed to a per-method handler
  • server request (id + method + params) → routed to a per-method handler, reply is sent automatically unless the handler returns DeferReply.

stderr is line-pumped to the logger and never merged with stdout.

func NewJSONRPCClient

func NewJSONRPCClient(cfg JSONRPCConfig) *JSONRPCClient

NewJSONRPCClient builds a client. The child is not spawned until Start is called.

func (*JSONRPCClient) Alive

func (c *JSONRPCClient) Alive() bool

Alive reports whether the child is still running and stdin is open.

func (*JSONRPCClient) Close

func (c *JSONRPCClient) Close() error

Close waits for the common owner to settle the native process and descendants.

func (*JSONRPCClient) Done

func (c *JSONRPCClient) Done() <-chan struct{}

Done is closed when the child exits. Use to coordinate teardown.

func (*JSONRPCClient) Notify

func (c *JSONRPCClient) Notify(method string, params any) error

Notify is fire-and-forget: no id, no reply.

func (*JSONRPCClient) OnNotification

func (c *JSONRPCClient) OnNotification(method string, h NotificationHandler)

OnNotification registers h for inbound notifications of method. Multiple handlers may register against the same method; all are invoked in registration order.

func (*JSONRPCClient) OnServerRequest

func (c *JSONRPCClient) OnServerRequest(method string, h ServerRequestHandler)

OnServerRequest registers h for inbound server requests with method. Only one handler per method is permitted; later Registers override.

func (*JSONRPCClient) Request

func (c *JSONRPCClient) Request(ctx context.Context, method string, params any) (json.RawMessage, error)

Request sends a JSON-RPC call and blocks until the response arrives, the deadline fires, or the child exits. Returns the raw result JSON so the caller can pick its decode shape.

func (*JSONRPCClient) SendServerError

func (c *JSONRPCClient) SendServerError(id any, code int, message string, data any) error

SendServerError sends an error reply for a deferred server request.

func (*JSONRPCClient) SendServerReply

func (c *JSONRPCClient) SendServerReply(id any, result any) error

SendServerReply is called by a ServerRequestHandler that returned DeferReply to send the response later.

func (*JSONRPCClient) Start

Start spawns the child, completes the JSON-RPC `initialize` handshake, and returns the server's InitializeResult.

Three failure paths:

  • exec.LookPath / Start failure → returns the spawn error verbatim
  • initialize timeout → kills the child, returns context.DeadlineExceeded
  • JSON-RPC error on initialize → kills the child, returns the error

type JSONRPCConfig

type JSONRPCConfig struct {
	// Binary is the codex executable to spawn. Defaults to defaultBinary():
	// the bare name "codex" for a PATH lookup, or the OAC_RUNTIME_CODEX_BIN
	// override.
	Binary string
	// Args added before "app-server --stdio". Useful for `-c key=value`
	// overrides without forcing CODEX_HOME indirection.
	ExtraArgs []string
	// EnableFeatures translates to repeated `--enable <feat>` flags.
	EnableFeatures []string
	// DisableFeatures translates to repeated `--disable <feat>` flags.
	DisableFeatures []string
	// Cwd is the working directory for the child process. Empty
	// inherits the daemon's cwd.
	Cwd string
	// Env is layered ON TOP of os.Environ() — set CODEX_HOME / OPENAI_API_KEY
	// here. Empty values are not filtered (codex distinguishes empty
	// from unset for some keys).
	Env []string
	// LogTag is the prefix carried on every internal log line.
	LogTag string
	// RequestTimeout overrides rpcDefaultRequestTimeout.
	RequestTimeout time.Duration
	// Logger is the structured logger to use. nil falls back to obslog.Bg().
	Logger *slog.Logger
}

JSONRPCConfig configures a JSONRPCClient. Zero-value fields fall through to sensible defaults.

type JsonRpcError

type JsonRpcError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

JsonRpcError carries a structured failure reply. Codes follow the JSON-RPC 2.0 spec (-32601 method-not-found, -32603 internal error, etc.).

func (*JsonRpcError) Error

func (e *JsonRpcError) Error() string

type JsonRpcRequest

type JsonRpcRequest struct {
	JsonRpc string `json:"jsonrpc"`
	ID      string `json:"id,omitempty"`
	Method  string `json:"method"`
	Params  any    `json:"params,omitempty"`
}

JsonRpcRequest is an outbound RPC call (client → codex). id is a daemon-minted 16-hex string; an empty id marks a notification (no response expected).

type JsonRpcResponse

type JsonRpcResponse struct {
	JsonRpc string        `json:"jsonrpc"`
	ID      any           `json:"id"`
	Result  any           `json:"result,omitempty"`
	Error   *JsonRpcError `json:"error,omitempty"`
}

JsonRpcResponse is an outbound reply to a server-initiated request. Either Result or Error must be non-nil.

type NotificationHandler

type NotificationHandler func(params json.RawMessage)

NotificationHandler is invoked for every inbound notification of a registered method. Returning an error logs but does not kill the session.

type PermissionsRequestApprovalParams

type PermissionsRequestApprovalParams struct {
	ThreadID    string         `json:"threadId"`
	TurnID      string         `json:"turnId"`
	ItemID      string         `json:"itemId"`
	Cwd         string         `json:"cwd"`
	Reason      *string        `json:"reason,omitempty"`
	Permissions map[string]any `json:"permissions,omitempty"`
}

type PermissionsRequestApprovalResponse

type PermissionsRequestApprovalResponse struct {
	Permissions map[string]any `json:"permissions"`
	Scope       string         `json:"scope,omitempty"`
}

PermissionsRequestApprovalResponse mirrors Codex app-server's dedicated response contract. Approving echoes the requested permission profile; denying returns an empty profile, which grants no additional capability.

type Prepared

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

Prepared owns a connected native resource until Start transfers it to a Session. It observes owner cancellation and RPC exit, not continuous executor readiness.

func Prepare

func Prepare(owner context.Context, req proto.PromptRequestPayload) (*Prepared, error)

Prepare connects the native harness without creating a thread or starting model work. req supplies configuration and a stable state key, but no RunID or Prompt. owner owns the entire harness lifetime, including the eventual Session; it must not be a disposable readiness-request context. Initialization/readiness use their existing operation-local deadlines. Close an unused preparation explicitly.

func (*Prepared) Cancel

func (p *Prepared) Cancel(ctx context.Context) error

Cancel fences Start and cancels the resource even after transfer.

func (*Prepared) CancellationOutcome

func (p *Prepared) CancellationOutcome() proto.DonePayload

CancellationOutcome returns observed state, not a guarantee of final output or quiescence.

func (*Prepared) Close

func (p *Prepared) Close() error

Close waits for unused teardown and plan cleanup, including another caller's ongoing Close. After successful Start it is inert; use the returned Session's cancellation path to release the transferred resource.

func (*Prepared) ListWorkspaceDirectory

func (s *Prepared) ListWorkspaceDirectory(context.Context, string, int) (agent.WorkspaceDirectoryResult, error)

func (*Prepared) ReadWorkspaceFile

func (s *Prepared) ReadWorkspaceFile(context.Context, string, int) (agent.WorkspaceReadResult, error)

func (*Prepared) Start

func (p *Prepared) Start(ctx context.Context, runID string, prompt proto.MessageInput, out chan<- proto.Envelope) (agent.Session, error)

Start consumes the preparation once. ctx bounds only this start operation; cancellation after return does not cancel the transferred Session. The original owner context remains its lifetime context. On success the Session owns out.

func (*Prepared) WriteWorkspaceFile

func (s *Prepared) WriteWorkspaceFile(context.Context, string, []byte) (agent.WorkspaceWriteResult, error)

type ReasoningDeltaNotification

type ReasoningDeltaNotification = AgentMessageDeltaNotification

type SandboxMode

type SandboxMode string

SandboxMode is the wire-level sandbox setting codex's v2 thread/start API accepts. Serializes to a kebab-case string per codex-rs/app-server-protocol/src/protocol/v2/shared.rs::SandboxMode.

Earlier (~0.137-era) the field on ThreadStartParams was named `sandboxPolicy` and took a tagged object `{type: "dangerFullAccess"}`. 0.141.0 renamed it to `sandbox` and flattened it to one of these three strings. Sending the old shape no longer errors loudly — codex just silently falls back to read-only, which makes prompts terminate immediately with no agent output. Keep the constants pinned exactly to the kebab values upstream serializes.

const (
	SandboxReadOnly        SandboxMode = "read-only"
	SandboxWorkspaceWrite  SandboxMode = "workspace-write"
	SandboxDangerFullAcces SandboxMode = "danger-full-access"
)

type SandboxPolicy

type SandboxPolicy struct {
	Type                SandboxMode `json:"type"`
	WritableRoots       []string    `json:"writableRoots,omitempty"`
	NetworkAccess       bool        `json:"networkAccess,omitempty"`
	ExcludeTmpdirEnvVar bool        `json:"excludeTmpdirEnvVar,omitempty"`
	ExcludeSlashTmp     bool        `json:"excludeSlashTmp,omitempty"`
}

SandboxPolicy is the legacy compound type kept for internal representation only — codex still echoes it back on some response shapes (turn_context inside rollout files, for example). It is NOT what ThreadStartParams.Sandbox takes on the wire.

type ServerRequestHandler

type ServerRequestHandler func(params json.RawMessage, id any) (any, error)

ServerRequestHandler handles a server-initiated request. Return (DeferReply, nil) to take ownership of the reply (e.g. when a human approval card sits between request and response). Otherwise, the returned value is marshalled into the JSON-RPC response. Returning an error sends a JSON-RPC error response with code -32603.

type Session

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

Session implements agent.Session. State lifecycle:

  1. Preparation initializes RPC and verifies the selected environment.
  2. Start transfers that RPC and wires notification/server-request handlers.
  3. thread/start or thread/resume runs (resume falls back to start).
  4. turn/start delivers the user prompt; subsequent stream notifications fan out to proto.Envelope via session_items.go.
  5. turn/completed emits TypeDone + closes out. Cancel can short-cut this by killing the child early.

func (*Session) AwaitSettlement

func (s *Session) AwaitSettlement(ctx context.Context) (agent.TurnSettlement, error)

func (*Session) Cancel

func (s *Session) Cancel(ctx context.Context) error

func (*Session) CancellationOutcome

func (s *Session) CancellationOutcome() proto.DonePayload

CancellationOutcome remains readable after Cancel stops the native process.

func (*Session) ListWorkspaceDirectory

func (s *Session) ListWorkspaceDirectory(context.Context, string, int) (agent.WorkspaceDirectoryResult, error)

func (*Session) ReadWorkspaceFile

func (s *Session) ReadWorkspaceFile(context.Context, string, int) (agent.WorkspaceReadResult, error)

func (*Session) Steer

func (s *Session) Steer(ctx context.Context, input proto.PromptSteerPayload) error

Steer returns success only after Codex accepts input for this native turn.

func (*Session) SteerWithReceipt

func (s *Session) SteerWithReceipt(ctx context.Context, input proto.PromptSteerPayload, written func()) error

SteerWithReceipt waits under the Run context after reporting the complete write.

func (*Session) SubmitFunctionResult

func (s *Session) SubmitFunctionResult(ctx context.Context, result proto.FunctionResultPayload) error

func (*Session) SubmitPermission

func (s *Session) SubmitPermission(_ context.Context, permID string, decision proto.PermissionDecisionPayload) error

SubmitPermission completes the deferred Codex app-server request that produced the Core permission envelope.

func (*Session) SubmitPromptForUserChoice

func (s *Session) SubmitPromptForUserChoice(_ context.Context, askID string, decision proto.PromptForUserChoiceDecisionPayload) error

SubmitPromptForUserChoice maps Core's header/answer pairs back to Codex's question-id keyed requestUserInput response.

func (*Session) WriteWorkspaceFile

func (s *Session) WriteWorkspaceFile(context.Context, string, []byte) (agent.WorkspaceWriteResult, error)

type SessionPlan

type SessionPlan struct {
	// Cwd is the working directory passed to codex and the spawned
	// app-server: the bound workspace root for an Environment request and
	// the Session's private CODEX_HOME for environment:none.
	Cwd string

	// Env is the full environment slice (KEY=value) to layer onto
	// os.Environ() before spawning. Includes CODEX_HOME, plus any
	// caller-provided OPENAI_API_KEY / CODEX_API_KEY / proxy vars.
	Env []string

	// ExtraConfig is a list of `-c key=value` overrides applied at the
	// app-server CLI. Used to layer model_reasoning_summary etc. without
	// editing config.toml.
	ExtraConfig [][2]string

	// EnableFeatures / DisableFeatures forward to `--enable / --disable`
	// flags. Today empty by default; reserved for future ARC opt-in.
	EnableFeatures  []string
	DisableFeatures []string

	// Model is the slug to request on thread/start. Empty inherits the
	// codex.config.toml default.
	Model string

	// ModelProvider is the slug pinned on thread/start so codex routes
	// the prompt through the [model_providers.<slug>] entry we wrote
	// into <CODEX_HOME>/config.toml. Empty leaves codex on its builtin
	// "openai" provider (only valid when the caller really wants
	// public api.openai.com + OPENAI_API_KEY env), so the normal path is
	// oacProviderSlug.
	ModelProvider string

	// SystemPrompt is forwarded as developerInstructions on thread/start.
	SystemPrompt string

	// CollaborationMode selects Codex's default or plan tool surface.
	CollaborationMode CollaborationModeKind

	// ModelReasoningEffort is frozen for launch and every native Turn.
	ModelReasoningEffort string

	// ApprovalPolicy + Sandbox apply to both new and resumed threads.
	ApprovalPolicy AskForApproval
	Sandbox        SandboxMode
	Permissions    string

	// Cleanup is the deferred housekeeping the session must run after the child exits.
	Cleanup func()
	// contains filtered or unexported fields
}

SessionPlan holds the resolved per-prompt launch plan derived from the daemon's PromptRequestPayload.

func BuildSessionPlan

func BuildSessionPlan(runID, agentStateKey string, opts map[string]any) (SessionPlan, error)

BuildSessionPlan derives a SessionPlan from PromptRequestPayload's fields. Options use a string-keyed map.

The agent_options keys this function reads:

model                 string          codex model slug, e.g. "gpt-5.5"
system_prompt         string          forwarded as developerInstructions
override_system_prompt string         replaces system_prompt entirely when
                                      non-empty
env                   map[string]any  extra env vars (KEY=string-value)
mcp_servers           map[string]any  rendered MCP server config — written
                                      to <CODEX_HOME>/config.toml [mcp_servers]
model_provider       object          frozen upstream protocol, endpoint, credential and token limits
reasoning_summary     string          one of auto/concise/detailed/none —
                                      routed via -c model_reasoning_summary
mode                  string          Codex collaboration mode: default/plan
enable_features       []any           string list, forwarded as --enable
disable_features      []any           string list, forwarded as --disable

The codex binary itself is resolved via PATH only — there's no per-prompt override knob. If a deployment needs a custom binary location, set it via the daemon's process environment (PATH / codexBinary in sessionConfig) rather than per-call.

Daemon-managed Codex sessions bypass approvals and the engine sandbox.

type SkillsExtraRootsSetParams

type SkillsExtraRootsSetParams struct {
	ExtraRoots []string `json:"extraRoots"`
}

type Thread

type Thread struct {
	ID         string `json:"id"`
	Cwd        string `json:"cwd,omitempty"`
	Preview    string `json:"preview,omitempty"`
	UpdatedAt  int64  `json:"updatedAt,omitempty"`
	CreatedAt  int64  `json:"createdAt,omitempty"`
	Status     any    `json:"status,omitempty"`
	Path       string `json:"path,omitempty"`
	CLIVersion string `json:"cliVersion,omitempty"`
}

type ThreadItem

type ThreadItem struct {
	Type string `json:"type"`
	ID   string `json:"id,omitempty"`

	// agentMessage / reasoning
	Phase       string   `json:"phase,omitempty"`
	Text        string   `json:"text,omitempty"`
	Summary     []string `json:"summary,omitempty"`
	Content     []string `json:"content,omitempty"`
	SummaryText string   `json:"summary_text,omitempty"`

	// commandExecution
	Command  string `json:"command,omitempty"`
	Cwd      string `json:"cwd,omitempty"`
	ExitCode *int   `json:"exitCode,omitempty"`
	Status   string `json:"status,omitempty"`

	// fileChange
	Changes []map[string]any `json:"changes,omitempty"`

	// mcpToolCall
	Server    string `json:"server,omitempty"`
	Tool      string `json:"tool,omitempty"`
	Arguments any    `json:"arguments,omitempty"`

	// dynamicToolCall
	Namespace string `json:"namespace,omitempty"`

	// webSearch
	Query string `json:"query,omitempty"`
}

ThreadItem is decoded loosely: parser keeps the raw JSON around so future fields can be inspected via a second unmarshal without round- tripping every variant through a hand-written struct.

type ThreadResumeParams

type ThreadResumeParams struct {
	Cwd                   string         `json:"cwd,omitempty"`
	DeveloperInstructions string         `json:"developerInstructions"`
	ThreadID              string         `json:"threadId"`
	ApprovalPolicy        AskForApproval `json:"approvalPolicy"`
	Sandbox               SandboxMode    `json:"sandbox,omitempty"`
	Permissions           string         `json:"permissions,omitempty"`
}

type ThreadStartParams

type ThreadStartParams struct {
	HistoryMode    string         `json:"historyMode,omitempty"`
	Cwd            string         `json:"cwd"`
	Model          string         `json:"model,omitempty"`
	ModelProvider  string         `json:"modelProvider,omitempty"`
	ApprovalPolicy AskForApproval `json:"approvalPolicy"`
	// Sandbox is the v0.141+ field name; previously called sandboxPolicy
	// and took a tagged-enum object. Wire format now is a kebab-case
	// string: "read-only" / "workspace-write" / "danger-full-access".
	// Sending the old object shape causes codex to silently default to
	// read-only, which terminates the turn before the model can reply.
	Sandbox               SandboxMode           `json:"sandbox,omitempty"`
	Permissions           string                `json:"permissions,omitempty"`
	DeveloperInstructions string                `json:"developerInstructions,omitempty"`
	RuntimeWorkspaceRoots []string              `json:"runtimeWorkspaceRoots,omitempty"`
	DynamicTools          []dynamicFunctionTool `json:"dynamicTools,omitempty"`
}

type ThreadStartResult

type ThreadStartResult struct {
	Thread         Thread          `json:"thread"`
	Model          string          `json:"model,omitempty"`
	ApprovalPolicy *AskForApproval `json:"approvalPolicy,omitempty"`
	Sandbox        *SandboxPolicy  `json:"sandbox,omitempty"`
}

type ThreadStartedNotification

type ThreadStartedNotification struct {
	Thread Thread `json:"thread"`
}

type ThreadTokenUsageUpdatedNotification

type ThreadTokenUsageUpdatedNotification struct {
	ThreadID   string     `json:"threadId"`
	TurnID     string     `json:"turnId"`
	Usage      *TurnUsage `json:"usage,omitempty"` // Legacy turn-level payload.
	TokenUsage *struct {
		Total *TurnUsage `json:"total"`
	} `json:"tokenUsage,omitempty"`
}

type ToolRequestUserInputAnswer

type ToolRequestUserInputAnswer struct {
	Answers []string `json:"answers"`
}

type ToolRequestUserInputOption

type ToolRequestUserInputOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
}

type ToolRequestUserInputParams

type ToolRequestUserInputParams struct {
	ThreadID         string                         `json:"threadId"`
	TurnID           string                         `json:"turnId"`
	ItemID           string                         `json:"itemId"`
	Questions        []ToolRequestUserInputQuestion `json:"questions"`
	AutoResolutionMs *uint64                        `json:"autoResolutionMs,omitempty"`
}

type ToolRequestUserInputQuestion

type ToolRequestUserInputQuestion struct {
	ID       string                       `json:"id"`
	Header   string                       `json:"header"`
	Question string                       `json:"question"`
	Options  []ToolRequestUserInputOption `json:"options,omitempty"`
	IsOther  bool                         `json:"isOther,omitempty"`
	IsSecret bool                         `json:"isSecret,omitempty"`
}

type ToolRequestUserInputResponse

type ToolRequestUserInputResponse struct {
	Answers map[string]ToolRequestUserInputAnswer `json:"answers"`
}

type Turn

type Turn struct {
	CompletedAt *int64     `json:"completedAt,omitempty"`
	ID          string     `json:"id"`
	Usage       *TurnUsage `json:"usage,omitempty"`
	Status      string     `json:"status,omitempty"`
	// Failed Turns carry the native provider error here.
	Error *TurnError `json:"error,omitempty"`
}

type TurnCompletedNotification

type TurnCompletedNotification struct {
	ThreadID string `json:"threadId"`
	Turn     Turn   `json:"turn"`
}

type TurnError

type TurnError struct {
	Message           string          `json:"message,omitempty"`
	CodexErrorInfo    json.RawMessage `json:"codexErrorInfo,omitempty"`
	AdditionalDetails *string         `json:"additionalDetails,omitempty"`
}

CodexErrorInfo is a native enum with string and object variants.

type TurnInterruptParams

type TurnInterruptParams struct {
	ThreadID string `json:"threadId"`
	TurnID   string `json:"turnId"`
}

type TurnStartParams

type TurnStartParams struct {
	ThreadID          string             `json:"threadId"`
	Input             []UserInput        `json:"input"`
	CollaborationMode *CollaborationMode `json:"collaborationMode,omitempty"`
}

type TurnStartedNotification

type TurnStartedNotification struct {
	ThreadID string `json:"threadId"`
	Turn     Turn   `json:"turn"`
}

type TurnSteerParams

type TurnSteerParams struct {
	ThreadID       string      `json:"threadId"`
	ExpectedTurnID string      `json:"expectedTurnId"`
	Input          []UserInput `json:"input"`
}

TurnSteerParams mirrors the native Codex app-server turn/steer request.

type TurnUsage

type TurnUsage struct {
	ReasoningOutputTokens int `json:"reasoningOutputTokens,omitempty"`
	InputTokens           int `json:"inputTokens,omitempty"`
	OutputTokens          int `json:"outputTokens,omitempty"`
	CachedInputTokens     int `json:"cachedInputTokens,omitempty"`
	CacheReadInputTokens  int `json:"cacheReadInputTokens,omitempty"`
	TotalTokens           int `json:"totalTokens,omitempty"`
	// contains filtered or unexported fields
}

func (*TurnUsage) UnmarshalJSON

func (u *TurnUsage) UnmarshalJSON(raw []byte) error

type UserInput

type UserInput struct {
	Type UserInputType `json:"type"`
	// Text variant
	Text         string `json:"text,omitempty"`
	TextElements []any  `json:"text_elements,omitempty"`
	// LocalImage variant
	Path string `json:"path,omitempty"`
	// Image (remote URL) variant
	URL string `json:"url,omitempty"`
}

UserInput is one element of TurnStartParams.Input. Each variant uses a distinct field set; producers must populate only the fields that match Type.

type UserInputType

type UserInputType string

UserInputType discriminates a UserInput element. Codex accepts mixed arrays of text + image entries on a single turn.

const (
	UserInputText       UserInputType = "text"
	UserInputLocalImage UserInputType = "localImage"
	UserInputRemoteImg  UserInputType = "image"
)

Jump to

Keyboard shortcuts

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