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:
The wire protocol is JSON-RPC (request / response / notification / server-request) rather than NDJSON event-stream. See rpc.go.
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
- Variables
- func CheckCLIAvailable(ctx context.Context, binary string) (string, error)
- func DispatchCompletedItem(runID string, item ThreadItem, bufs *ItemBuffers) (envelopes []proto.Envelope, agentText string, err error)
- func DispatchStartedItem(runID string, item ThreadItem) ([]proto.Envelope, error)
- func FoldDeltaIntoBuffer(bufs *ItemBuffers, itemID, delta string) string
- func Installation() agent.Installation
- func NewExecutorFactory(stateRoot, runtimeRoot string) agent.ExecutorFactory
- func PrepareExecutor(ctx context.Context, stateRoot, runtimeRoot string, ...) (agent.Executor, error)
- func SupportsLocalEnvironment(version string) bool
- func SupportsNativeSessionRecovery(version string) bool
- type AgentMessageDeltaNotification
- type ErrorNotification
- type Executor
- type InitializeCapabilities
- type InitializeClientInfo
- type InitializeParams
- type InitializeResult
- type ItemBuffers
- type ItemCompletedNotification
- type ItemStartedNotification
- type JSONRPCClient
- func (c *JSONRPCClient) Alive() bool
- func (c *JSONRPCClient) Close() error
- func (c *JSONRPCClient) Done() <-chan struct{}
- func (c *JSONRPCClient) Notify(method string, params any) error
- func (c *JSONRPCClient) OnNotification(method string, h NotificationHandler)
- func (c *JSONRPCClient) OnServerRequest(method string, h ServerRequestHandler)
- func (c *JSONRPCClient) Request(ctx context.Context, method string, params any) (json.RawMessage, error)
- func (c *JSONRPCClient) SendServerError(id any, code int, message string, data any) error
- func (c *JSONRPCClient) SendServerReply(id any, result any) error
- func (c *JSONRPCClient) Start(ctx context.Context, init InitializeParams) (InitializeResult, error)
- type JSONRPCConfig
- type JsonRpcError
- type JsonRpcRequest
- type JsonRpcResponse
- type NotificationHandler
- type Prepared
- type ReasoningDeltaNotification
- type ServerRequestHandler
- type Session
- func (s *Session) AwaitSettlement(ctx context.Context) (agent.TurnSettlement, error)
- func (s *Session) Cancel(ctx context.Context) error
- func (s *Session) CancellationOutcome() proto.DonePayload
- func (s *Session) SteerWithReceipt(ctx context.Context, input proto.PromptSteerPayload, written func()) error
- func (s *Session) SubmitFunctionResult(ctx context.Context, result proto.FunctionResultPayload) error
- type SessionPlan
- type SkillsExtraRootsSetParams
- type Thread
- type ThreadItem
- type ThreadResumeParams
- type ThreadStartParams
- type ThreadStartResult
- type ThreadTokenUsageUpdatedNotification
- type Turn
- type TurnCompletedNotification
- type TurnError
- type TurnInterruptParams
- type TurnStartParams
- type TurnStartedNotification
- type TurnSteerParams
- type TurnUsage
- type UserInput
- type UserInputType
Constants ¶
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.
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.
Variables ¶
var Declaration = agent.Declaration{Declaration: declaration.Declaration, Discover: discover}
Declaration binds the shared Codex declaration to discovery and execution factories.
var DeferReply = deferReplySentinel{}
DeferReply, when returned from a ServerRequestHandler, signals that the handler will reply later via SendServerReply.
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 ¶
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. An agentMessage returns its text so the session can stamp it into DonePayload.Content; tool-call variants produce an "after" envelope so the UI gets a stage transition.
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; reasoning is reported by the Session
- error: surfaced by turn/completed.status="failed" instead
func FoldDeltaIntoBuffer ¶
func FoldDeltaIntoBuffer(bufs *ItemBuffers, itemID, delta string) string
FoldDeltaIntoBuffer accumulates an agentMessage delta under its itemId and returns the running text.
func Installation ¶
func Installation() agent.Installation
func NewExecutorFactory ¶
func NewExecutorFactory(stateRoot, runtimeRoot string) agent.ExecutorFactory
func PrepareExecutor ¶
func SupportsLocalEnvironment ¶
SupportsLocalEnvironment checks deployment prerequisites, not public admission.
Types ¶
type ErrorNotification ¶
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.
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 experimental thread/* fields and notification stream.
type InitializeClientInfo ¶
type InitializeParams ¶
type InitializeParams struct {
ClientInfo InitializeClientInfo `json:"clientInfo"`
Capabilities *InitializeCapabilities `json:"capabilities"`
}
type InitializeResult ¶
type ItemBuffers ¶
ItemBuffers holds per-itemId state for streamed notifications. agentMessage deltas drive incremental TypeDelta frames while the completed item anchors the final text. A reasoning item streams one of its two native channels, recorded here from its first delta.
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"`
}
type ItemStartedNotification ¶
type ItemStartedNotification struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Item ThreadItem `json:"item"`
}
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 ¶
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 ¶
func (c *JSONRPCClient) Start(ctx context.Context, init InitializeParams) (InitializeResult, error)
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 Prepared ¶
type Prepared struct {
// contains filtered or unexported fields
}
Prepared owns a connected native resource until an Executor takes it. It observes owner cancellation and RPC exit, not continuous executor readiness.
type ReasoningDeltaNotification ¶
type ReasoningDeltaNotification struct {
AgentMessageDeltaNotification
SummaryIndex int `json:"summaryIndex"`
ContentIndex int `json:"contentIndex"`
}
ReasoningDeltaNotification is a summaryTextDelta (SummaryIndex) or a textDelta (ContentIndex).
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:
- Preparation initializes RPC and verifies the selected environment.
- Start transfers that RPC and wires notification/server-request handlers.
- thread/start or thread/resume runs (resume falls back to start).
- turn/start delivers the user prompt; subsequent stream notifications fan out to proto.Envelope via session_items.go.
- turn/completed emits TypeDone + closes out. Cancel can short-cut this by killing the child early.
func (*Session) AwaitSettlement ¶
func (*Session) CancellationOutcome ¶
func (s *Session) CancellationOutcome() proto.DonePayload
CancellationOutcome remains readable after Cancel stops the native process.
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 ¶
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 and the entries
// of the env option.
Env []string
// ExtraConfig is a list of `-c key=value` overrides applied at the
// app-server CLI.
ExtraConfig [][2]string
// EnableFeatures / DisableFeatures forward to `--enable / --disable`
// flags for the profiles the adapter configures.
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
// ReasoningSummary reports that the Agent requested reasoning summaries.
ReasoningSummary bool
// OutputSchema is the frozen public JSON Schema sent as outputSchema on every
// native root Turn.
OutputSchema json.RawMessage
// 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(stateRoot, agentStateKey string, opts map[string]any, controls *proto.ExecutionControls) (SessionPlan, error)
BuildSessionPlan derives a SessionPlan from the request's agent_options and execution controls. It reads these agent_options keys:
model string codex model slug, e.g. "gpt-5.5" system_prompt string forwarded as developerInstructions model_provider object frozen upstream protocol, endpoint, credential and token limits harness_config object native parameters accepted by harnessconfig/codex
Execution controls map one to one to native settings; see applyExecutionControls. The codex binary itself is resolved via PATH only.
type SkillsExtraRootsSetParams ¶
type SkillsExtraRootsSetParams struct {
ExtraRoots []string `json:"extraRoots"`
}
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"`
// 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 ThreadStartParams ¶
type ThreadStartParams struct {
HistoryMode string `json:"historyMode,omitempty"`
Cwd string `json:"cwd"`
Model string `json:"model,omitempty"`
ModelProvider string `json:"modelProvider,omitempty"`
ApprovalPolicy string `json:"approvalPolicy"`
// Sandbox is the kebab-case mode string. Codex silently falls back to
// read-only for the legacy sandboxPolicy object.
Sandbox string `json:"sandbox"`
DeveloperInstructions string `json:"developerInstructions,omitempty"`
RuntimeWorkspaceRoots []string `json:"runtimeWorkspaceRoots,omitempty"`
DynamicTools []dynamicFunctionTool `json:"dynamicTools,omitempty"`
}
type ThreadStartResult ¶
type TurnError ¶
type TurnError struct {
Message string `json:"message,omitempty"`
CodexErrorInfo json.RawMessage `json:"codexErrorInfo,omitempty"`
}
CodexErrorInfo is a native enum with string and object variants.
type TurnInterruptParams ¶
type TurnStartParams ¶
type TurnStartParams struct {
ThreadID string `json:"threadId"`
Input []UserInput `json:"input"`
// OutputSchema constrains this Turn's final assistant message natively.
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
}
type TurnStartedNotification ¶
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 ¶
type UserInput ¶
type UserInput struct {
Type UserInputType `json:"type"`
// Text variant
Text string `json:"text,omitempty"`
TextElements []any `json:"text_elements,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" UserInputRemoteImg UserInputType = "image" )
Source Files
¶
- cancellation_outcome.go
- contracts.go
- declaration.go
- environment.go
- environment_local.go
- error_classification.go
- executor.go
- executor_turn.go
- function_receipts.go
- functions.go
- installation.go
- mcp_config.go
- mcp_http.go
- mcp_http_preflight.go
- message_input.go
- options.go
- permission_profile.go
- preparation.go
- prepared.go
- programmatic_tools.go
- protocol.go
- provider_config.go
- recovery.go
- resume.go
- rpc.go
- rpc_close.go
- rpc_request.go
- rpc_write.go
- session.go
- session_cancel.go
- session_command_output.go
- session_items.go
- session_messages.go
- session_notifications.go
- session_output.go
- session_plan.go
- session_run.go
- session_steering.go
- session_thread.go
- session_tools.go
- session_usage.go
- skills.go
- subagent_cancel.go
- subagent_coordination.go
- subagent_history.go
- subagent_metadata.go
- subagent_observations.go
- subagent_profile.go
- subagent_rollout.go
- subagent_snapshots.go
- subagents.go
- terminal_cleanup.go
- tool_observations.go
- trust.go
- version.go