Documentation
¶
Index ¶
- Constants
- Variables
- func ActiveGatewayRoute(home string, overrides map[string]any, lookup func(string) (string, bool)) (gateway.Route, bool, error)
- func ApprovalContent(method string, params map[string]any) []acp.ToolCallContent
- func ApprovalKind(method string) acp.ToolKind
- func ApprovalOptions(params map[string]any) []acp.PermissionOption
- func ApprovalResponse(selected *acp.PermissionOptionId, params map[string]any) map[string]any
- func ApprovalTitle(method string, params map[string]any) string
- func CodexHome(home string, lookup func(string) (string, bool)) string
- func ElicitationCancelResponse() map[string]any
- func ElicitationResponse(resp acp.UnstableCreateElicitationResponse) map[string]any
- func GatewayRoutes(home string, overrides map[string]any, lookup func(string) (string, bool)) ([]gateway.Route, error)
- func IsMCPToolApproval(params map[string]any) bool
- func IsMissingThread(err error, threadID string) bool
- func LockHome(home string) (*process.FileLock, error)
- func MCPElicitationRequest(params map[string]any, meta map[string]any) (acp.UnstableCreateElicitationRequest, error)
- func MCPToolApprovalOptions() []acp.PermissionOption
- func MCPToolApprovalResponse(selected *acp.PermissionOptionId) map[string]any
- func MCPToolApprovalTitle(params map[string]any) string
- func PermissionsOptions() []acp.PermissionOption
- func PermissionsResponse(selected *acp.PermissionOptionId, params map[string]any) map[string]any
- func RefusesInvalidArguments(message string) bool
- func RelocateRollout(home string, recorded string, threadID string) (string, bool)
- func RepairCallArguments(rows [][]byte) ([][]byte, int, error)
- func RequestItemID(params map[string]any) string
- func RequestThreadID(params map[string]any) string
- func RolloutPath(home string, threadID string, stamp time.Time) string
- func ToolUserInputForm(params map[string]any, meta map[string]any) (*acp.UnstableCreateElicitationForm, error)
- func ToolUserInputResponse(content map[string]any) map[string]any
- func ValidThreadID(threadID string) bool
- type Account
- type AccountIdentity
- type AccountUsage
- type Client
- func (c *Client) Call(ctx context.Context, method string, params any, result any) error
- func (c *Client) Err() error
- func (c *Client) Initialize(ctx context.Context) error
- func (c *Client) InterruptTurn(ctx context.Context, threadID string, turnID string) error
- func (c *Client) ListModels(ctx context.Context) ([]Model, error)
- func (c *Client) Notifications() <-chan Notification
- func (c *Client) Notify(method string, params any) error
- func (c *Client) ReadAccount(ctx context.Context) (Account, error)
- func (c *Client) ReadAccountUsage(ctx context.Context) (AccountUsage, error)
- func (c *Client) Requests() <-chan ServerRequest
- func (c *Client) Respond(request ServerRequest, result any, rpcErr *RPCError) error
- func (c *Client) ResumeThread(ctx context.Context, req ThreadResumeRequest, nativePath string) (Thread, error)
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) StartThread(ctx context.Context, req ThreadStartRequest, nativePath string) (Thread, error)
- func (c *Client) StartTurn(ctx context.Context, req TurnStartRequest) (string, error)
- func (c *Client) UnloadThread(ctx context.Context, threadID string) error
- func (c *Client) UnsubscribeThread(ctx context.Context, threadID string) error
- type Event
- type EventKind
- type ImageEvent
- type Launch
- type Model
- type Notification
- type PlanStep
- type PromptImage
- type RPCError
- type RolloutRow
- type RowKind
- type ServerRequest
- type SessionMeta
- type StopReason
- type Thread
- type ThreadResumeRequest
- type ThreadStartRequest
- type TokenUsage
- type ToolEvent
- type TurnFailure
- type TurnStartRequest
- type Usage
- type UsageLimit
- type UsageWindow
- type UserInput
Constants ¶
const ( EnvCodexHome = "CODEX_HOME" EnvHome = "HOME" )
Native environment variables Codex reads for its home.
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.
const ( RowTypeSessionMeta = "session_meta" RowTypeEventMsg = "event_msg" RowTypeResponseItem = "response_item" RowTypeCompacted = "compacted" )
Rollout row types the adapter reads.
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.
const InternalEnvPrefix = "ACP_GO_CODEX_INTERNAL_"
InternalEnvPrefix names the adapter's private child-process markers.
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 ¶
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.
var ErrTransportClosed = errors.New("codex app-server transport closed")
ErrTransportClosed reports that the app-server stdout stream ended before a call received its response.
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 ¶
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 ¶
ApprovalResponse maps the selected option back onto the native decision. A nil selection is the native cancel.
func ApprovalTitle ¶
ApprovalTitle renders the host-facing title of an approval request.
func CodexHome ¶
CodexHome resolves the home the app-server uses under an environment: an explicit home, else CODEX_HOME, else $HOME/.codex.
func ElicitationCancelResponse ¶
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 ¶
IsMCPToolApproval reports whether an MCP elicitation is a tool-call approval, which the host answers as a permission.
func IsMissingThread ¶
IsMissingThread recognizes the native refusal for a thread with no rollout.
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 ¶
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 ¶
PermissionsResponse maps the selected option back onto the native grant. A nil selection or a rejection grants nothing.
func RefusesInvalidArguments ¶
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 ¶
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 ¶
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 ¶
RequestItemID returns the item a server request concerns.
func RequestThreadID ¶
RequestThreadID returns the thread a server request addresses.
func RolloutPath ¶
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 ¶
ToolUserInputResponse renders accepted form content as the native answers. Nil content answers nothing.
func ValidThreadID ¶
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 ¶
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 ¶
NewClient constructs a client over the app-server's stdin writer and stdout reader.
func (*Client) Call ¶
Call sends one request and decodes its result into result when non-nil. A failed response is returned as an *RPCError.
func (*Client) Initialize ¶
Initialize performs the app-server handshake.
func (*Client) InterruptTurn ¶
InterruptTurn interrupts the thread's in-flight turn.
func (*Client) ListModels ¶
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) ReadAccount ¶
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 ¶
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 ¶
StartTurn dispatches one turn and returns the native turn id the app-server named in its acknowledgement.
func (*Client) UnloadThread ¶
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.
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.
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 ¶
Notification is one app-server notification. Params is nil when the notification carried no params object.
type PromptImage ¶
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.
type RolloutRow ¶
RolloutRow is one decoded rollout row.
type RowKind ¶
RowKind is a rollout row's type and its payload's type.
func DecodeRowKind ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.