codex

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EnvCodexHome = "CODEX_HOME"
	EnvHome      = "HOME"
)

Native environment variables Codex reads for its home.

View Source
const (
	RequestCommandApproval     = "item/commandExecution/requestApproval"
	RequestFileChangeApproval  = "item/fileChange/requestApproval"
	RequestPermissionsApproval = "item/permissions/requestApproval"
	RequestToolUserInput       = "item/tool/requestUserInput"
	RequestMCPElicitation      = "mcpServer/elicitation/request"
)

Server request methods the adapter answers.

View Source
const (
	RowTypeSessionMeta  = "session_meta"
	RowTypeEventMsg     = "event_msg"
	RowTypeResponseItem = "response_item"
	RowTypeCompacted    = "compacted"
)

Rollout row types the adapter reads.

View Source
const AccountTypeChatGPT = "chatgpt"

AccountTypeChatGPT is the one account type with allowance windows; the app-server refuses the rate-limit read for an API-key or Bedrock login.

View Source
const InternalEnvPrefix = "ACP_GO_CODEX_INTERNAL_"

InternalEnvPrefix names the adapter's private child-process markers.

View Source
const ThreadUnloadDelayKey = "thread_unload_delay_secs"

ThreadUnloadDelayKey is the config key the launch sets to unload idle unsubscribed threads at once; overrides may not set it.

Variables

View Source
var ErrElicitationSecret = errors.New("codex elicitation marks a field as a secret")

ErrElicitationSecret reports a form that asks the host to collect a credential. The adapter refuses the whole form; the error names no property and carries no schema content.

View Source
var ErrTransportClosed = errors.New("codex app-server transport closed")

ErrTransportClosed reports that the app-server stdout stream ended before a call received its response.

View Source
var ErrUnsupportedContentBlock = fmt.Errorf("unsupported prompt content block")

ErrUnsupportedContentBlock reports a prompt content block Codex cannot accept. Nothing is silently dropped.

Functions

func ActiveGatewayRoute

func ActiveGatewayRoute(home string, overrides map[string]any, lookup func(string) (string, bool)) (gateway.Route, bool, error)

ActiveGatewayRoute is the route of the model provider Codex sends turns to: the launch override's model_provider, else config.toml's, when that provider declares its own base URL.

func ApprovalContent

func ApprovalContent(method string, params map[string]any) []acp.ToolCallContent

ApprovalContent renders the host-facing content of an approval request.

func ApprovalKind

func ApprovalKind(method string) acp.ToolKind

ApprovalKind is the ACP tool kind of an approval request.

func ApprovalOptions

func ApprovalOptions(params map[string]any) []acp.PermissionOption

ApprovalOptions maps a command or file-change approval's native decisions onto ACP permission options.

func ApprovalResponse

func ApprovalResponse(selected *acp.PermissionOptionId, params map[string]any) map[string]any

ApprovalResponse maps the selected option back onto the native decision. A nil selection is the native cancel.

func ApprovalTitle

func ApprovalTitle(method string, params map[string]any) string

ApprovalTitle renders the host-facing title of an approval request.

func CodexHome

func CodexHome(home string, lookup func(string) (string, bool)) string

CodexHome resolves the home the app-server uses under an environment: an explicit home, else CODEX_HOME, else $HOME/.codex.

func ElicitationCancelResponse

func ElicitationCancelResponse() map[string]any

ElicitationCancelResponse is the native cancel of an MCP elicitation.

func ElicitationResponse

func ElicitationResponse(resp acp.UnstableCreateElicitationResponse) map[string]any

ElicitationResponse maps an ACP elicitation answer onto the native action.

func GatewayRoutes

func GatewayRoutes(home string, overrides map[string]any, lookup func(string) (string, bool)) ([]gateway.Route, error)

GatewayRoutes lists the model providers declared with their own base URL, by config.toml under home and by the launch overrides, which win: the routes Codex sends requests through, each with the key the environment holds under the provider's env_key.

func IsMCPToolApproval

func IsMCPToolApproval(params map[string]any) bool

IsMCPToolApproval reports whether an MCP elicitation is a tool-call approval, which the host answers as a permission.

func IsMissingThread

func IsMissingThread(err error, threadID string) bool

IsMissingThread recognizes the native refusal for a thread with no rollout.

func LockHome

func LockHome(home string) (*process.FileLock, error)

LockHome reserves this native home until the app-server has been waited on.

func MCPElicitationRequest

func MCPElicitationRequest(params map[string]any, meta map[string]any) (acp.UnstableCreateElicitationRequest, error)

MCPElicitationRequest renders an MCP elicitation as an ACP elicitation in url or form mode, or refuses with ErrElicitationSecret.

func MCPToolApprovalOptions

func MCPToolApprovalOptions() []acp.PermissionOption

MCPToolApprovalOptions is the option set of an MCP tool approval.

func MCPToolApprovalResponse

func MCPToolApprovalResponse(selected *acp.PermissionOptionId) map[string]any

MCPToolApprovalResponse maps the selected option onto the native action.

func MCPToolApprovalTitle

func MCPToolApprovalTitle(params map[string]any) string

MCPToolApprovalTitle renders the host-facing title of an MCP tool approval.

func PermissionsOptions

func PermissionsOptions() []acp.PermissionOption

PermissionsOptions is the option set of a permissions approval request.

func PermissionsResponse

func PermissionsResponse(selected *acp.PermissionOptionId, params map[string]any) map[string]any

PermissionsResponse maps the selected option back onto the native grant. A nil selection or a rejection grants nothing.

func RefusesInvalidArguments

func RefusesInvalidArguments(message string) bool

RefusesInvalidArguments reports whether a turn failure message is a provider's refusal of a request whose history holds a function call with arguments that are not JSON, such as "function_call call_1 has invalid JSON arguments". Every later request on the thread resends the call, so the thread cannot continue until the call is repaired. The message must name a function or tool call, its arguments, and JSON that does not parse.

func RelocateRollout

func RelocateRollout(home string, recorded string, threadID string) (string, bool)

RelocateRollout is the path under home of the rollout a recorded location names. The recorded file name must be threadID's rollout; its start time places the file in its day directory. It reports false for any other name.

func RepairCallArguments

func RepairCallArguments(rows [][]byte) ([][]byte, int, error)

RepairCallArguments returns rows with the arguments of every function call whose arguments are not JSON replaced by an empty object, and how many calls it repaired. Every other row is returned unchanged.

func RequestItemID

func RequestItemID(params map[string]any) string

RequestItemID returns the item a server request concerns.

func RequestThreadID

func RequestThreadID(params map[string]any) string

RequestThreadID returns the thread a server request addresses.

func RolloutPath

func RolloutPath(home string, threadID string, stamp time.Time) string

RolloutPath is the path a rollout for threadID started at stamp occupies under home. Codex names the file in local time, so the reconstruction does too.

func ToolUserInputForm

func ToolUserInputForm(params map[string]any, meta map[string]any) (*acp.UnstableCreateElicitationForm, error)

ToolUserInputForm renders the tool questions as an ACP form elicitation, or refuses with ErrElicitationSecret when a question asks for a secret.

func ToolUserInputResponse

func ToolUserInputResponse(content map[string]any) map[string]any

ToolUserInputResponse renders accepted form content as the native answers. Nil content answers nothing.

func ValidThreadID

func ValidThreadID(threadID string) bool

ValidThreadID keeps a stored thread id from naming anything but one file in its day directory.

Types

type Account

type Account struct {
	Account *AccountIdentity `json:"account"`
}

Account is the account/read result. A nil Account means the home holds no login, and account/rateLimits/read refuses in that state.

type AccountIdentity

type AccountIdentity struct {
	Type     string `json:"type"`
	PlanType string `json:"planType"`
}

AccountIdentity is the logged-in account: its type selects whether a rate-limit read is possible and its plan type names the plan.

type AccountUsage

type AccountUsage struct {
	OrdinaryUsageAllowed *bool                 `json:"ordinaryUsageAllowed"`
	Limits               map[string]UsageLimit `json:"rateLimitsByLimitId"`
}

AccountUsage is the account/rateLimits/read result: one limit per limit id and the app-server's own statement of whether ordinary usage is allowed, nil when it makes none.

func (AccountUsage) Sorted

func (u AccountUsage) Sorted() []UsageLimit

Sorted lists the limits in id order, each carrying its map key as ID.

type Client

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

Client speaks the app-server's JSON-RPC protocol over its stdin and stdout. Calls are correlated by id; notifications and server requests are delivered on channels in stream order. Delivery is synchronous, so the consumer keeps draining both channels while calls are in flight.

func NewClient

func NewClient(stdin io.Writer, stdout io.Reader) *Client

NewClient constructs a client over the app-server's stdin writer and stdout reader.

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params any, result any) error

Call sends one request and decodes its result into result when non-nil. A failed response is returned as an *RPCError.

func (*Client) Err

func (c *Client) Err() error

Err returns the transport failure, or nil after a clean end-of-stream.

func (*Client) Initialize

func (c *Client) Initialize(ctx context.Context) error

Initialize performs the app-server handshake.

func (*Client) InterruptTurn

func (c *Client) InterruptTurn(ctx context.Context, threadID string, turnID string) error

InterruptTurn interrupts the thread's in-flight turn.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]Model, error)

ListModels reads the app-server's model catalog.

func (*Client) Notifications

func (c *Client) Notifications() <-chan Notification

Notifications returns the notification stream. It is closed when the read loop exits.

func (*Client) Notify

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

Notify sends one notification.

func (*Client) ReadAccount

func (c *Client) ReadAccount(ctx context.Context) (Account, error)

ReadAccount reports the account the app-server is logged in as.

func (*Client) ReadAccountUsage

func (c *Client) ReadAccountUsage(ctx context.Context) (AccountUsage, error)

ReadAccountUsage performs one fresh account/rateLimits/read. It skips the reset-credit lookup, a second backend request whose result the adapter never reads.

func (*Client) Requests

func (c *Client) Requests() <-chan ServerRequest

Requests returns the server request stream. It is closed when the read loop exits. Every request must be answered through Respond.

func (*Client) Respond

func (c *Client) Respond(request ServerRequest, result any, rpcErr *RPCError) error

Respond answers one server request. A nil rpcErr sends result; otherwise the error is sent and result is ignored.

func (*Client) ResumeThread

func (c *Client) ResumeThread(ctx context.Context, req ThreadResumeRequest, nativePath string) (Thread, error)

ResumeThread resumes a thread by id. The app-server resolves the id against the rollouts under its own home.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start launches the stdout read loop. It must be called exactly once before any call is issued; the loop stops when the stream ends or ctx is cancelled.

func (*Client) StartThread

func (c *Client) StartThread(ctx context.Context, req ThreadStartRequest, nativePath string) (Thread, error)

StartThread starts a new thread that reports each model response's usage as the response completes. nativePath is the PATH the app-server process itself runs with; the thread's PATH is composed ahead of it.

func (*Client) StartTurn

func (c *Client) StartTurn(ctx context.Context, req TurnStartRequest) (string, error)

StartTurn dispatches one turn and returns the native turn id the app-server named in its acknowledgement.

func (*Client) UnloadThread

func (c *Client) UnloadThread(ctx context.Context, threadID string) error

UnloadThread unsubscribes from threadID and waits until the app-server no longer holds it in memory, so its rollout is complete and a later resume reads it afresh. The app-server unloads an idle thread no connection subscribes to after its configured unload delay.

func (*Client) UnsubscribeThread

func (c *Client) UnsubscribeThread(ctx context.Context, threadID string) error

UnsubscribeThread releases the app-server's thread subscription. An app-server without the method is not a failure.

type Event

type Event struct {
	Kind   EventKind
	Method string
	// Params is the notification's decoded params, shared with the tool and
	// image items the event names; consumers must not modify it.
	Params   map[string]any
	ThreadID string
	TurnID   string
	ItemID   string
	// Text carries a delta or, when Completed, the whole text of the item.
	Text      string
	Completed bool
	Plan      []PlanStep
	Tool      ToolEvent
	Image     ImageEvent
	Usage     TokenUsage
	// Response is the usage one completed model response reported, nil when
	// it reported none.
	Response *Usage
	// ResponseID is the id the model gateway returned for a completed model
	// response.
	ResponseID string
	Stop       StopReason
	Failure    *TurnFailure
}

Event is one decoded app-server notification.

func DecodeEvent

func DecodeEvent(notification Notification) Event

DecodeEvent classifies one notification. Every notification decodes; ones the adapter does not model are EventRaw.

type EventKind

type EventKind string

EventKind classifies one app-server notification for the adapter.

const (
	EventCompactionCompleted EventKind = "compaction_completed"
	EventAgentMessageDelta   EventKind = "agent_message_delta"
	EventReasoningDelta      EventKind = "reasoning_delta"
	EventPlanUpdated         EventKind = "plan_updated"
	EventToolStarted         EventKind = "tool_started"
	EventToolDelta           EventKind = "tool_delta"
	EventToolCompleted       EventKind = "tool_completed"
	EventImageStarted        EventKind = "image_started"
	EventImageCompleted      EventKind = "image_completed"
	EventDiffUpdated         EventKind = "diff_updated"
	EventUsageUpdated        EventKind = "usage_updated"
	EventResponseCompleted   EventKind = "response_completed"
	EventTurnStarted         EventKind = "turn_started"
	EventTurnCompleted       EventKind = "turn_completed"
	EventError               EventKind = "error"
	EventRaw                 EventKind = "raw"
)

The event kinds the adapter projects.

type ImageEvent

type ImageEvent struct {
	ID        string
	Kind      string
	Status    string
	Result    string
	SavedPath string
	Raw       map[string]any
}

ImageEvent is an image-generation or image-view item.

type Launch

type Launch struct {
	// ConfigOverrides are passed as -c key=value, sorted by key.
	ConfigOverrides map[string]any
}

Launch describes one app-server process.

func (Launch) Args

func (l Launch) Args() []string

Args renders the app-server command line. The app-server unloads a thread as soon as it is idle and no connection subscribes to it, so a closed session's history leaves memory at once and a thread unloaded for repair is ready to resume without waiting out the default delay.

type Model

type Model struct {
	ID          string
	Name        string
	Description string
	// ContextWindow is the window a gateway's model list states for the
	// model; the app-server's own list states none.
	ContextWindow          int64
	DefaultReasoningEffort string
	ReasoningEfforts       []string
	// InputModalities is the app-server's own list of input modalities; nil
	// means the field was absent.
	InputModalities []string
}

Model is one model/list entry.

type Notification

type Notification struct {
	Method string
	Params map[string]any
}

Notification is one app-server notification. Params is nil when the notification carried no params object.

type PlanStep

type PlanStep struct {
	Text   string
	Status string
}

PlanStep is one entry of a plan update.

type PromptImage

type PromptImage struct {
	Data []byte
	MIME string
}

PromptImage is one validated prompt image: its raw bytes and sniffed MIME.

type RPCError

type RPCError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

RPCError is the error member of a failed app-server response.

func (*RPCError) Error

func (e *RPCError) Error() string

type RolloutRow

type RolloutRow struct {
	Type    string         `json:"type"`
	Payload map[string]any `json:"payload"`
}

RolloutRow is one decoded rollout row.

func DecodeRow

func DecodeRow(row []byte) (RolloutRow, error)

DecodeRow decodes one rollout row.

type RowKind

type RowKind struct {
	Type        string
	PayloadType string
}

RowKind is a rollout row's type and its payload's type.

func DecodeRowKind

func DecodeRowKind(row []byte) (RowKind, error)

DecodeRowKind validates one rollout row as DecodeRow does and reads only its row and payload types.

type ServerRequest

type ServerRequest struct {
	ID     json.RawMessage
	Method string
	Params map[string]any
}

ServerRequest is one request the app-server sent to the adapter, answered through Client.Respond. Params is nil when the request carried no params object.

type SessionMeta

type SessionMeta struct {
	ID        string
	Timestamp time.Time
}

SessionMeta is what the session_meta row names about the thread.

func ParseSessionMeta

func ParseSessionMeta(row []byte) (SessionMeta, bool)

ParseSessionMeta reads the thread identity from a session_meta row. It reports false for any other row.

type StopReason

type StopReason string

StopReason is how the app-server reported a turn ended.

const (
	StopReasonEndTurn   StopReason = "end_turn"
	StopReasonCancelled StopReason = "cancelled"
	StopReasonError     StopReason = "error"
)

The closed turn status vocabulary; anything else is an error.

type Thread

type Thread struct {
	ID   string
	Path string
	// Model is the model the thread reports, when the response names one.
	Model string
	// ReportsResponses marks a thread that sends rawResponse/completed with
	// each model response's usage as the response completes. Only thread/start
	// can opt a thread in.
	ReportsResponses bool
}

Thread is the native thread identity an app-server call returned.

type ThreadResumeRequest

type ThreadResumeRequest struct {
	ThreadID      string
	Cwd           string
	Environment   map[string]string
	ExtraPathDirs []string
}

ThreadResumeRequest is one thread/resume call.

type ThreadStartRequest

type ThreadStartRequest struct {
	Cwd                   string
	AdditionalDirectories []string
	Model                 string
	ServiceTier           string
	Personality           string
	ApprovalPolicy        any
	SandboxMode           any
	// Environment and ExtraPathDirs are applied to this thread alone through
	// its shell environment policy.
	Environment   map[string]string
	ExtraPathDirs []string
}

ThreadStartRequest is one thread/start call.

type TokenUsage

type TokenUsage struct {
	Last               Usage
	Total              Usage
	ModelContextWindow int64
}

TokenUsage is the thread/tokenUsage/updated payload: the last model request's usage, the thread's cumulative usage, and the context window codex applies to the selected model, 0 when it reports none.

func LastTokenUsage

func LastTokenUsage(rows [][]byte) TokenUsage

LastTokenUsage is the thread usage a rollout last recorded, which codex restores when it resumes the thread. A rollout with none reads as zero.

type ToolEvent

type ToolEvent struct {
	ID      string
	Title   string
	Kind    string
	Status  string
	Content string
	Raw     map[string]any
}

ToolEvent is a tool-like item at start, delta, or completion.

type TurnFailure

type TurnFailure struct {
	StatusCode   int
	ProviderCode string
	Message      string
}

TurnFailure is the provider failure a completed turn carried.

type TurnStartRequest

type TurnStartRequest struct {
	ThreadID          string
	Input             []UserInput
	Model             string
	ServiceTier       string
	ReasoningEffort   string
	Personality       string
	ApprovalPolicy    any
	SandboxPolicy     any
	OutputSchema      any
	CollaborationMode any
}

TurnStartRequest is one turn/start call.

type Usage

type Usage struct {
	Input      int64
	CachedRead int64
	CacheWrite int64
	Output     int64
	Reasoning  int64
	Total      int64
}

Usage is one token usage breakdown as the Responses API reports it: Input includes the input read from and written to a prompt cache, Output includes the reasoning, and Total is input plus output.

type UsageLimit

type UsageLimit struct {
	ID        string       `json:"-"`
	Name      string       `json:"limitName"`
	Primary   *UsageWindow `json:"primary"`
	Secondary *UsageWindow `json:"secondary"`
}

UsageLimit is one allowance with up to two windows. ID is its map key.

type UsageWindow

type UsageWindow struct {
	UsedPercent        float64 `json:"usedPercent"`
	WindowDurationMins int64   `json:"windowDurationMins"`
	ResetsAt           int64   `json:"resetsAt"`
}

UsageWindow is one window's utilization, length in minutes, and reset as Unix seconds.

type UserInput

type UserInput map[string]any

UserInput is one element of a turn/start input array.

func PromptToUserInput

func PromptToUserInput(blocks []acp.ContentBlock, images []PromptImage) ([]UserInput, error)

PromptToUserInput maps ACP prompt blocks to the app-server's input shape. Image-bearing blocks consume the validated images in request order and travel as data URLs; embedded data is authoritative and block URIs are provenance only.

Jump to

Keyboard shortcuts

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