Documentation
¶
Overview ¶
Package codex provides native long-running Sessions over Codex app-server. Open fixes a main identity. Session.Receive is the single FIFO for native events, real IncomingRequests and observation evidence. Submit retains native turn semantics; results do not close the Session. Client is the explicit shared I/O resource and raw extension seam. Native request handles retain single-use authority. See README.md for the pinned source target and evidence limits.
Index ¶
- Variables
- func WithTraceContext(ctx context.Context, trace TraceContext) context.Context
- type AnswerError
- type AnswerHandle
- type ApprovalOptions
- type CallError
- type ChildDetailPolicy
- type Client
- func (c *Client) Call(ctx context.Context, method string, params, result any) error
- func (c *Client) Close() error
- func (c *Client) CloseInput() error
- func (c *Client) Diagnostics() DiagnosticSnapshot
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Err() error
- func (c *Client) InterruptTurn(ctx context.Context, p types.TurnInterruptParams) (types.TurnInterruptResponse, error)
- func (c *Client) ListThreadItems(ctx context.Context, p types.ThreadItemsListParams) (types.ThreadItemsListResponse, error)
- func (c *Client) ListThreadTurns(ctx context.Context, p types.ThreadTurnsListParams) (types.ThreadTurnsListResponse, error)
- func (c *Client) ListThreads(ctx context.Context, p types.ThreadListParams) (types.ThreadListResponse, error)
- func (c *Client) ReadThread(ctx context.Context, p types.ThreadReadParams) (types.ThreadReadResponse, error)
- func (c *Client) ResumeThread(ctx context.Context, p types.ThreadResumeParams) (types.ThreadResumeResponse, error)
- func (c *Client) ServerInfo() types.InitializeResponse
- func (c *Client) StartThread(ctx context.Context, p types.ThreadStartParams) (types.ThreadStartResponse, error)
- func (c *Client) StartTurn(ctx context.Context, p types.TurnStartParams) (types.TurnStartResponse, error)
- func (c *Client) Unattributed() UnattributedSnapshot
- func (c *Client) UnsubscribeThread(ctx context.Context, p types.ThreadUnsubscribeParams) (types.ThreadUnsubscribeResponse, error)
- type ConfigurationReceipt
- type DecodeError
- type DiagnosticSnapshot
- type DispatchState
- type Feature
- type ID
- type IncomingRequest
- func (r IncomingRequest) Answer(ctx context.Context, answer types.ToolRequestUserInputResponse) error
- func (r IncomingRequest) Approve(ctx context.Context, options ApprovalOptions) error
- func (r IncomingRequest) Context() context.Context
- func (r IncomingRequest) Deny(ctx context.Context, options ApprovalOptions) error
- type Input
- type InterruptOptions
- type Limits
- type Observation
- type RPCError
- type Received
- type ReceivedKind
- type RemoteOptions
- type Request
- type Session
- func (s *Session) Abort() error
- func (s *Session) Archive(ctx context.Context) (types.ThreadArchiveResponse, error)
- func (s *Session) Close() error
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Err() error
- func (s *Session) Inject(ctx context.Context, items []json.RawMessage) error
- func (s *Session) Interrupt(ctx context.Context, options InterruptOptions) error
- func (s *Session) ListSubagents(ctx context.Context, query SubagentQuery) (SubagentPage, error)
- func (s *Session) Receive(ctx context.Context) (Received, error)
- func (s *Session) ResumeResponse() (types.ThreadResumeResponse, bool)
- func (s *Session) SetModel(ctx context.Context, model string) (ConfigurationReceipt, error)
- func (s *Session) SetThinking(ctx context.Context, change ThinkingChange) (ConfigurationReceipt, error)
- func (s *Session) StartResponse() (types.ThreadStartResponse, bool)
- func (s *Session) Submit(ctx context.Context, input Input) (Submission, error)
- func (s *Session) ThreadID() string
- func (s *Session) Unarchive(ctx context.Context) (types.ThreadUnarchiveResponse, error)
- func (s *Session) Unattributed() UnattributedSnapshot
- type SessionOptions
- type StdioOptions
- type StreamOptions
- type StreamTransport
- type SubagentCoverage
- type SubagentPage
- type SubagentQuery
- type Submission
- type SubscriptionOverflowErrordeprecated
- type ThinkingChange
- type Tool
- type TraceContext
- type UnattributedRecord
- type UnattributedSnapshot
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrSubscriptionOverflow = errors.New("codex: subscription overflow; events lost") ErrRemoteTransport = errors.New("codex: remote transport failure") ErrClosed = errors.New("codex: connection closed") ErrInputClosed = errors.New("codex: input is half-closed") ErrStreamRequired = errors.New("codex: stream transport required") ErrUnexpectedEOF = errors.New("codex: unexpected end of stdout") ErrLimit = errors.New("codex: resource limit reached") ErrProtocol = errors.New("codex: protocol error") ErrFrameTooLarge = errors.New("codex: frame too large") ErrWriteTimeout = errors.New("codex: write timeout") ErrShutdownTimeout = errors.New("codex: owned process did not reap before shutdown timeout") ErrInvalidAnswerHandle = errors.New("codex: invalid answer handle") ErrRequestAnswered = errors.New("codex: server request answer already admitted") ErrRequestCanceled = errors.New("codex: server request abandoned locally") ErrRequestExpired = errors.New("codex: server request handle expired locally") ErrRequestResolved = errors.New("codex: server request resolved by server") ErrRequestOverflow = fmt.Errorf("codex: server request capacity exhausted: %w", ErrLimit) // Deprecated: incoming requests use Session.Receive and never emit this error. ErrUnsupportedRequest = errors.New("codex: server request unsupported by this SDK slice") )
var ( ErrOwnershipConflict = errors.New("codex: session ownership conflict") ErrInvalidInput = errors.New("codex: invalid or unsupported input") )
var ( ErrUnsupportedDiscovery = errors.New("codex: descendant queries require experimentalApi initialization") ErrDiscoveryCursor = errors.New("codex: descendant query cursor did not advance or repeated") )
var ErrUnsupportedConfiguration = errors.New("codex: thread settings require experimentalApi initialization")
Functions ¶
func WithTraceContext ¶
func WithTraceContext(ctx context.Context, trace TraceContext) context.Context
WithTraceContext attaches a carrier without validating it. Only Session.Submit consumes it; raw Client calls and thread operations remain trace-free.
Types ¶
type AnswerError ¶
type AnswerError struct {
Method string
ID ID
Dispatch DispatchState
Cause error
}
AnswerError preserves a one-shot server-response failure and its wire evidence. NotSent leaves a still-live handle available for an explicit answer attempt. OutcomeUnknown consumes authority and must never be replayed. A successful Answer returns nil (the frame was written), which is not evidence that the peer accepted or acted on the response.
func (*AnswerError) Error ¶
func (e *AnswerError) Error() string
func (*AnswerError) Unwrap ¶
func (e *AnswerError) Unwrap() error
type AnswerHandle ¶
type AnswerHandle struct {
// contains filtered or unexported fields
}
AnswerHandle is an opaque, connection-bound, one-shot response capability. Copies share one state. It cannot be retargeted to another ID or connection. Native resolution and owner termination invalidate the same registry entry. No operation here claims to stop server execution; turn interruption is a separate RPC.
func (AnswerHandle) Answer ¶
func (h AnswerHandle) Answer(ctx context.Context, result any) error
Answer sends exactly one caller-selected result, including null for nil. Marshal/validation, pre-canceled-context, frame-limit and queue-admission failures and confirmed NotSent cancellation leave a live handle usable. Native resolution/Close still invalidate it. Partial/ambiguous writes are never retried. Context cancellation during a blocked write fails the connection.
func (AnswerHandle) Cancel ¶
func (h AnswerHandle) Cancel() error
Cancel abandons an unanswered handle locally. It sends no response or cancel notification. Call Reject with a caller-chosen RPC error to respond instead.
func (AnswerHandle) Done ¶
func (h AnswerHandle) Done() <-chan struct{}
func (AnswerHandle) Err ¶
func (h AnswerHandle) Err() error
Err is nil while waiting (including a response in progress). After Done it reports ErrRequestAnswered, local cancellation, native resolution, or connection failure. A successful write is not evidence of server acceptance.
func (AnswerHandle) Reject ¶
func (h AnswerHandle) Reject(ctx context.Context, rpcError *RPCError) error
Reject sends a caller-selected protocol error, never an approval decision. RPCError.Raw is diagnostic inbound data and is not emitted; Code, Message and Data define the outgoing error. A nil error is a safe pre-write failure.
type ApprovalOptions ¶
type ApprovalOptions struct {
CommandExecution *types.CommandExecutionRequestApprovalResponse
FileChange *types.FileChangeRequestApprovalResponse
Permissions *types.PermissionsRequestApprovalResponse
ApplyPatch *types.ApplyPatchApprovalResponse
ExecCommand *types.ExecCommandApprovalResponse
}
ApprovalOptions selects at most one response matching the original method. Empty options select accept/decline (approved/denied for legacy requests). Permissions approval requires an explicit native grant; denial grants nothing. Native response fields, scope and policy amendments are emitted unchanged.
type CallError ¶
type CallError struct {
Method string
ID ID
Dispatch DispatchState
Cause error
}
CallError preserves the underlying cause and conservative dispatch evidence. OutcomeUnknown requests must not be replayed without caller reconciliation.
type ChildDetailPolicy ¶
type ChildDetailPolicy string
ChildDetailPolicy selects SDK delivery of confirmed-child detail. It does not control native output, internal results, or model usage.
const ( // ChildDetailPreserve delivers all admitted native facts, as does the zero value. ChildDetailPreserve ChildDetailPolicy = "preserve" // ChildDetailSuppress omits only reviewed pure child progress. Full items, // approvals, lifecycle facts and mixed/unknown frames remain visible; this is // not a content redaction guarantee. ChildDetailSuppress ChildDetailPolicy = "suppress" )
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client owns one app-server connection and, for stdio only, its child process. It never reconnects or replays requests. Calls are safe concurrently; a context only cancels local waiting, never server execution.
func NewRemote ¶
func NewRemote(ctx context.Context, options RemoteOptions) (*Client, error)
NewRemote opens exactly one WS/WSS connection, completes initialize, and writes initialized before returning. Context and CallTimeout bound the whole construction. Cancellation after construction does not close the client. Reconnecting requires a new explicit NewRemote call and initialization.
Example ¶
This example is compiled, not executed; the endpoint and token are placeholders.
package main
import (
"context"
"fmt"
codex "github.com/zoumo/agent-sdk-go/codex"
"github.com/zoumo/agent-sdk-go/codex/types"
)
func main() {
ctx := context.Background()
client, err := codex.NewRemote(ctx, codex.RemoteOptions{
URL: "wss://codex.example.com/",
BearerToken: "caller-supplied-token",
Initialize: types.InitializeParams{ClientInfo: types.ClientInfo{Name: "my-client", Version: "0.1"}},
})
if err != nil {
return
}
defer client.Close()
started, err := client.StartThread(ctx, types.ThreadStartParams{Ephemeral: types.Some(true)})
if err != nil {
return
}
fmt.Println(started.Thread.ID)
}
Output:
func NewStdio ¶
func NewStdio(ctx context.Context, options StdioOptions) (*Client, error)
NewStdio starts the explicitly selected executable, completes initialize then writes initialized before returning. The context bounds construction only.
func NewStreams ¶
func NewStreams(ctx context.Context, options StreamOptions, transport StreamTransport) (*Client, error)
NewStreams connects the native Codex client to caller-provided directional streams. It performs the same initialize exchange as NewStdio without resolving or starting an executable.
func (*Client) Call ¶
Call invokes a raw protocol extension with the same bounds and no-replay rules as typed operations. nil params omits params; json.RawMessage("null") sends null. A nil result discards the result. Raw calls do not certify method support.
func (*Client) Close ¶
Close is idempotent and bounded. A remote client closes only its socket. A stdio client closes stdin, allows a bounded grace period, then kills only the child it started and waits for reaping. It never sends a protocol shutdown RPC or kills an unrelated process, process group, or remote server.
func (*Client) CloseInput ¶
CloseInput half-closes the SDK outbound writer while retaining the reader for final peer frames. It is intended for stream transports.
func (*Client) Diagnostics ¶
func (c *Client) Diagnostics() DiagnosticSnapshot
func (*Client) InterruptTurn ¶
func (c *Client) InterruptTurn(ctx context.Context, p types.TurnInterruptParams) (types.TurnInterruptResponse, error)
InterruptTurn explicitly requests interruption of the caller's native turn. A successful acknowledgement is not evidence that execution has completed.
func (*Client) ListThreadItems ¶
func (c *Client) ListThreadItems(ctx context.Context, p types.ThreadItemsListParams) (types.ThreadItemsListResponse, error)
ListThreadItems returns one native saved-item page, not an event log. An item anchor requires a non-empty TurnID under the native server contract.
func (*Client) ListThreadTurns ¶
func (c *Client) ListThreadTurns(ctx context.Context, p types.ThreadTurnsListParams) (types.ThreadTurnsListResponse, error)
ListThreadTurns returns one native page without resuming or projecting events. Direction, item detail, limits and opaque cursors are interpreted by the server.
func (*Client) ListThreads ¶
func (c *Client) ListThreads(ctx context.Context, p types.ThreadListParams) (types.ThreadListResponse, error)
ListThreads returns one native thread/list page. It does not create a Session, attach threads, or fetch further pages. Defaults and filters belong to the server.
func (*Client) ReadThread ¶
func (c *Client) ReadThread(ctx context.Context, p types.ThreadReadParams) (types.ThreadReadResponse, error)
ReadThread reads native metadata (prefer IncludeTurns: types.Some(false)). It does not resume or subscribe, even when this connection owns a Session.
func (*Client) ResumeThread ¶
func (c *Client) ResumeThread(ctx context.Context, p types.ThreadResumeParams) (types.ThreadResumeResponse, error)
ResumeThread sends the caller's native thread ID unchanged and accepts only a response with that same ID. It never creates a replacement thread, reconnects, or replays a request. Optional parameters preserve omitted/null/value states. Native history/path selectors can select another identity; such a response is an ErrProtocol failure under this method's strict identity contract.
func (*Client) ServerInfo ¶
func (c *Client) ServerInfo() types.InitializeResponse
func (*Client) StartThread ¶
func (c *Client) StartThread(ctx context.Context, p types.ThreadStartParams) (types.ThreadStartResponse, error)
func (*Client) StartTurn ¶
func (c *Client) StartTurn(ctx context.Context, p types.TurnStartParams) (types.TurnStartResponse, error)
StartTurn returns only the native response. Events, including early or stale completions, never change its result. Open a Session before starting a turn to retain its native facts.
func (*Client) Unattributed ¶
func (c *Client) Unattributed() UnattributedSnapshot
Unattributed reads independent diagnostic copies, never a second event stream.
func (*Client) UnsubscribeThread ¶
func (c *Client) UnsubscribeThread(ctx context.Context, p types.ThreadUnsubscribeParams) (types.ThreadUnsubscribeResponse, error)
UnsubscribeThread requests server-side detachment for the specified native thread once and returns the native status. It does not close a coordinated Session values or imply interruption, deletion, or completion of a thread's work.
type ConfigurationReceipt ¶
type ConfigurationReceipt struct {
Requested types.ThreadSettingsUpdateParams
Response types.ThreadSettingsUpdateResponse
NativeAccepted bool
}
ConfigurationReceipt separates the requested settings and native RPC acceptance. Response preserves the native empty acknowledgement and unknown fields. It does not report observed settings or a current-turn switch. Observe thread/settings/updated independently through Receive.
type DecodeError ¶
DecodeError reports a malformed supported request or notification payload. The original method and parameters remain available; the connection stays usable.
func (*DecodeError) Error ¶
func (e *DecodeError) Error() string
func (*DecodeError) Unwrap ¶
func (e *DecodeError) Unwrap() error
type DiagnosticSnapshot ¶
type DiagnosticSnapshot struct {
StderrBytes uint64
UnmatchedResponses uint64
Notifications uint64
Tail string
}
DiagnosticSnapshot never contains the child's raw stderr or wire payloads. Tail is a bounded sequence of redaction markers. Counters saturate at uint64 max.
type DispatchState ¶
type DispatchState string
DispatchState reports delivery evidence, never whether server execution stopped.
const ( NotSent DispatchState = "not-sent" OutcomeUnknown DispatchState = "outcome-unknown" Responded DispatchState = "responded" )
type ID ¶
type ID struct {
// contains filtered or unexported fields
}
ID preserves the pinned protocol's distinct signed-integer and string IDs. Its zero value is invalid. Numeric IDs never pass through floating point.
func (ID) MarshalJSON ¶
func (ID) StringValue ¶
func (*ID) UnmarshalJSON ¶
type IncomingRequest ¶
type IncomingRequest struct{ Request }
IncomingRequest carries the original connection registry capability. Zero values, parsing, history and diagnostic records cannot grant authority.
func (IncomingRequest) Answer ¶
func (r IncomingRequest) Answer(ctx context.Context, answer types.ToolRequestUserInputResponse) error
Answer responds only to a live native requestUserInput, retaining question IDs, answer arrays and native extensions. It never submits an ordinary turn input.
func (IncomingRequest) Approve ¶
func (r IncomingRequest) Approve(ctx context.Context, options ApprovalOptions) error
func (IncomingRequest) Context ¶
func (r IncomingRequest) Context() context.Context
func (IncomingRequest) Deny ¶
func (r IncomingRequest) Deny(ctx context.Context, options ApprovalOptions) error
type Input ¶
type Input struct {
AdditionalContext types.Optional[map[string]types.AdditionalContextEntry]
ApprovalPolicy types.Optional[types.AskForApproval]
ApprovalsReviewer types.Optional[types.ApprovalsReviewer]
ClientUserMessageID types.Optional[string]
CollaborationMode types.Optional[types.CollaborationMode]
Cwd types.Optional[string]
CyberAccessProgram types.Optional[types.CyberAccessProgram]
DisabledPluginIDs types.Optional[[]string]
Effort types.Optional[types.ReasoningEffort]
Environments types.Optional[[]types.TurnEnvironmentParams]
Input []types.UserInput
Model types.Optional[string]
MultiAgentMode types.Optional[types.MultiAgentMode]
OutputSchema types.Optional[json.RawMessage]
ParentTurnID types.Optional[string]
Permissions types.Optional[string]
Personality types.Optional[types.Personality] //nolint:staticcheck // Mirrors the deprecated native field.
ResponsesapiClientMetadata types.Optional[map[string]string]
RootTurnID types.Optional[string]
RuntimeWorkspaceRoots types.Optional[[]types.AbsolutePathBuf]
SandboxPolicy types.Optional[types.SandboxPolicy]
ServiceTier types.Optional[string]
ServiceTierForTurn types.Optional[string]
Summary types.Optional[types.ReasoningSummary]
ToolOutput types.Optional[types.TurnToolOutput]
TurnTrigger types.Optional[string]
}
Input preserves native turn/start execution options, without a target ThreadID.
type InterruptOptions ¶
type InterruptOptions struct{ TurnID string }
type Limits ¶
type Limits struct {
QuarantineRecords int
QuarantineBytes int
QuarantineRetention time.Duration
MaxFrameBytes int
OutboundQueue int
PendingCalls int
Subscriptions int
// Deprecated: retained for source compatibility; negative values remain invalid.
EventQueue int
DiagnosticBytes int
// ActiveRequests bounds received server requests until a terminal state.
ActiveRequests int
// RequestIdentities bounds distinct request identities retained for this connection.
// Exhaustion fails explicitly; terminal/replayed requests never regain authority.
RequestIdentities int
// RequestQueue bounds queued server requests, including terminal unread ones.
RequestQueue int
// Deprecated: retained temporarily for source compatibility; negatives are invalid.
RequestTimeout time.Duration
CallTimeout time.Duration
WriteTimeout time.Duration
ShutdownTimeout time.Duration
}
Limits are per connection. Zero values select DefaultLimits. Negative values are rejected. Incoming and outgoing frame limits bound JSON payload bytes, excluding stdio delimiters and WebSocket frame headers.
func DefaultLimits ¶
func DefaultLimits() Limits
type Observation ¶
type Observation struct{ ThreadID, ParentThreadID, Method, Reason string }
Observation describes SDK knowledge, never a native notification.
type RPCError ¶
type RPCError struct {
Code int64 `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
// Raw retains the entire error object, including future unknown members.
// Remote errors redact reflected bearer credentials from Message, Data, and
// Raw. Otherwise the original native data and bytes are preserved.
Raw json.RawMessage `json:"-"`
}
RPCError is a definitive server error response, not a no-side-effects guarantee.
type Received ¶
type Received struct {
Observation *Observation
Request *IncomingRequest
Kind ReceivedKind
Event *types.Event
Raw json.RawMessage
Params json.RawMessage
Source types.EventIdentity
Origin string
}
Received retains one native or SDK fact with an explicit origin. Kind selects exactly one of Event, Request or Observation.
type ReceivedKind ¶
type ReceivedKind string
const ( ReceivedEvent ReceivedKind = "event" ReceivedRequest ReceivedKind = "request" ReceivedObservation ReceivedKind = "observation" )
type RemoteOptions ¶
type RemoteOptions struct {
URL string
BearerToken string
Initialize types.InitializeParams
Limits Limits
TLSConfig *tls.Config
// AllowInsecureWS permits unencrypted ws to non-loopback hosts. This can
// expose the bearer token and all protocol data; prefer wss instead.
AllowInsecureWS bool
}
RemoteOptions selects one explicitly authenticated WebSocket endpoint. URL must use ws or wss and contain no user info, query, or fragment. BearerToken must be supplied explicitly; it is sent only in the Authorization header. TLSConfig is cloned and certificate verification cannot be disabled. Set RootCAs to explicitly trust a private certificate authority. Do not mutate referenced certificate/configuration data concurrently with construction. No HTTP redirects, environment proxies, reconnects, or token refresh occur.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request holds an immutable received snapshot separately from registry authority. Consuming/releasing the snapshot releases its Raw/Params payload; terminal replay protection retains no command, diff or question payload. Request is an immutable received server request. Accessors return independent copies; changing a decoded payload cannot change its identity or answer target. Requests are shared between pull consumers, not broadcast or replayed.
func (Request) Data ¶
Data decodes a fresh native payload. Unknown methods return nil, nil; malformed known payloads return a DecodeError while Params retains the original bytes.
func (Request) Handle ¶
func (r Request) Handle() AnswerHandle
func (Request) Params ¶
func (r Request) Params() json.RawMessage
func (Request) Raw ¶
func (r Request) Raw() json.RawMessage
Raw returns an independent copy of the complete native request envelope.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session owns main identity, admission and a single FIFO. All mutable state except cleanupOnce/cleanupErr is protected by the connection mutex.
func (*Session) Abort ¶
Abort explicitly abandons consumption, releases the unread FIFO and performs the same cleanup as Close. A Receive already completed may still return a fact.
func (*Session) Archive ¶
Archive requests native archival of the Session's fixed main thread. Success is native RPC acceptance, not proof that the thread is already archived; observe thread/archived through Receive for that separate fact. Archiving does not delete the transcript, close this Session or another Session, or select an arbitrary thread. The native server may shut down loaded execution and archive spawned descendant threads.
func (*Session) Close ¶
Close stops admission before cleanup, preserves accepted facts, and never waits for a consumer. Shared physical attachments detach only after their last Session observer releases them.
func (*Session) Inject ¶
Inject appends raw Responses API items to the owned main thread without starting a user turn. The server validates native item semantics. A successful response proves RPC acceptance, not model consumption or durable recording. Servers without thread/inject_items return a native method-not-found error.
func (*Session) Interrupt ¶
func (s *Session) Interrupt(ctx context.Context, options InterruptOptions) error
func (*Session) ListSubagents ¶
func (s *Session) ListSubagents(ctx context.Context, query SubagentQuery) (SubagentPage, error)
ListSubagents reads native stored descendants without attaching or replaying. Defaults explicitly include all five pinned subAgent source kinds and only non-archived records. Archived records require a separate query.
func (*Session) Receive ¶
Example ¶
This example is compiled but has no Output directive, so tests do not run it.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
codex "github.com/zoumo/agent-sdk-go/codex"
)
// answerFromTerminal is application code, never called on an SDK reader. It
// prints the native request and waits for an explicit caller-selected JSON result.
// In a real UI, watch Handle.Done as well and dismiss stale prompts.
func answerFromTerminal(ctx context.Context, request codex.Request) error {
fmt.Printf("%s %s %s\n", request.ID(), request.Method(), request.Params())
fmt.Println("Enter the native JSON result you choose for this request:")
var result json.RawMessage
if err := json.NewDecoder(os.Stdin).Decode(&result); err != nil {
return err
}
return request.Handle().Answer(ctx, result)
}
// This example is compiled but has no Output directive, so tests do not run it.
func main() {
// Open a Session first. No request is approved automatically.
consume := func(ctx context.Context, session *codex.Session) error {
for {
record, err := session.Receive(ctx)
if err != nil {
return err
}
if record.Request != nil && record.Request.Context().Err() == nil {
if err := answerFromTerminal(ctx, record.Request.Request); err != nil {
return err
}
}
// Native events and observation evidence arrive through this same loop.
}
}
_ = consume
}
Output:
func (*Session) ResumeResponse ¶
func (s *Session) ResumeResponse() (types.ThreadResumeResponse, bool)
ResumeResponse returns an independent copy of the native thread/resume response, including saved turns and unknown fields. It is absent for starts.
func (*Session) SetModel ¶
SetModel requests a native model identifier for subsequent turns of the main thread. It neither waits for idle nor changes any child thread explicitly.
func (*Session) SetThinking ¶
func (s *Session) SetThinking(ctx context.Context, change ThinkingChange) (ConfigurationReceipt, error)
SetThinking requests native reasoning effort for subsequent main-thread turns.
func (*Session) StartResponse ¶
func (s *Session) StartResponse() (types.ThreadStartResponse, bool)
StartResponse returns an independent copy of the actual native thread/start response, including model, sandbox and unknown fields.
func (*Session) Unarchive ¶
Unarchive requests native restoration of the Session's fixed main thread. The returned response preserves the native restored Thread and unknown fields. Success is RPC acceptance; observe thread/unarchived through Receive for the separate native notification. A native response for another thread is a protocol failure rather than a replacement main identity.
func (*Session) Unattributed ¶
func (s *Session) Unattributed() UnattributedSnapshot
Unattributed returns the shared connection's bounded diagnostic snapshot, including when Open owns and hides the underlying process connection.
type SessionOptions ¶
type SessionOptions struct {
Client *Client
Stdio *StdioOptions
Thread types.ThreadStartParams
Resume *types.ThreadResumeParams
// Features and Tools add explicit native thread configuration switches.
// Absent map keys do not override existing configuration.
Features map[Feature]bool
Tools map[Tool]bool
// MCPServers adds shared mcp.Server values to this Session's native thread
// config.
MCPServers []mcp.Server
// ShellEnv adds set-only variables to shell/unified-exec child environments.
// Empty values set empty strings. It does not change the app-server environment.
ShellEnv map[string]string
// ChildDetailPolicy fixes optional confirmed-child progress delivery for this Session.
ChildDetailPolicy ChildDetailPolicy
// MaxMembers bounds observation identities independently of parent knowledge.
MaxMembers int
// MaxParentDepth bounds parent knowledge, never membership eligibility.
MaxParentDepth int
}
SessionOptions selects an existing connection or an explicitly owned process. Exactly one of Client or Stdio must be supplied. Thread uses native start options. Resume selects an existing thread instead; Thread must then be empty.
type StdioOptions ¶
type StdioOptions struct {
Executable string
Args []string
Env []string
Dir string
Initialize types.InitializeParams
Limits Limits
}
StdioOptions explicitly selects the child and its initialization. No shell is invoked and no executable, credentials, or account is discovered by the SDK. Env nil inherits the current environment as os/exec does; a non-nil slice replaces it. Choose a clean environment and Codex home when isolation matters.
type StreamOptions ¶
type StreamOptions struct {
Args []string
Env []string
Dir string
Initialize types.InitializeParams
Limits Limits
}
StreamOptions configures a process-free app-server connection. Args is the validated native startup declaration, not an executable argv. Env is a complete environment snapshot; Dir is the logical protocol working directory.
type StreamTransport ¶
type StreamTransport struct {
Reader io.ReadCloser
Writer io.WriteCloser
Stderr io.ReadCloser
Wait func(context.Context) error
}
StreamTransport supplies already-open directional protocol streams. Reader carries peer-to-SDK bytes and Writer carries SDK-to-peer bytes. Stderr is optional diagnostics. Wait is the authoritative peer result when present; nil is valid only when reader EOF alone is authoritative.
type SubagentCoverage ¶
type SubagentCoverage struct {
Requested types.ThreadListParams
Archived bool
// PagesCompleted counts successfully decoded RPC responses, including an
// over-budget page that could not be retained. len(SubagentPage.Pages) is
// the retained page count; neither count proves enumeration completeness.
PagesCompleted int
// EndReached reports the native end cursor even when enumeration began at
// a supplied cursor. EnumerationComplete additionally requires a full walk
// from the beginning and refers only to Requested filters and native storage.
EndReached bool
EnumerationComplete bool
// SourceSelection is explicit, native-interactive (empty list), or
// native-unrestricted (null with the pinned ancestor relation filter).
SourceSelection string
IncompleteReason string
}
SubagentCoverage describes only the requested storage enumeration, never live observation, active execution, or a snapshot across concurrent native changes.
type SubagentPage ¶
type SubagentPage struct {
Pages []types.ThreadListResponse
// NextCursor is the next page input, or the unretained/failed page input.
// On cursor-cycle or missing-end-cursor it preserves the native problematic
// cursor instead; inspect Coverage.IncompleteReason before continuing.
NextCursor types.Optional[string]
Coverage SubagentCoverage
}
SubagentPage retains each native response, including unknown fields and cursors. Records do not establish observation membership or execution state.
type SubagentQuery ¶
type SubagentQuery struct {
Cursor types.Optional[string]
Limit types.Optional[uint32]
SourceKinds types.Optional[[]types.ThreadSourceKind]
Archived types.Optional[bool]
ModelProviders types.Optional[[]string]
Originators types.Optional[[]string]
SortKey types.Optional[types.ThreadSortKey]
SortDirection types.Optional[types.SortDirection]
Cwd types.Optional[types.ThreadListCwdFilter]
UseStateDbOnly types.Optional[bool] //nolint:staticcheck // Mirrors the native wire spelling.
SectionID types.Optional[string]
ProjectID types.Optional[string]
SearchTerm types.Optional[string]
// Zero selects defaults: 128 pages, 10000 records, 16 MiB of native result
// JSON. A page exceeding record/byte capacity is not retained or truncated;
// NextCursor remains its input cursor so the caller can query it separately.
MaxPages int
MaxRecords int
MaxBytes int
}
SubagentQuery selects stored descendants of the Session's fixed main thread. It cannot redirect the ancestor or select a direct-parent-only query.
type Submission ¶
type Submission struct{ Response types.TurnStartResponse }
type SubscriptionOverflowError
deprecated
type SubscriptionOverflowError struct{ Capacity int }
Deprecated: dynamic subscription queues no longer produce this error.
func (*SubscriptionOverflowError) Error ¶
func (e *SubscriptionOverflowError) Error() string
func (*SubscriptionOverflowError) Unwrap ¶
func (e *SubscriptionOverflowError) Unwrap() error
type ThinkingChange ¶
type ThinkingChange struct {
Effort types.Optional[types.ReasoningEffort]
// Summary is the native reasoning-summary display setting, independent of effort.
Summary types.Optional[types.ReasoningSummary]
}
ThinkingChange preserves native effort and reasoning-summary fields. Omitted and null effort both leave the native override unchanged at the pinned protocol version; null is not a request to clear an effort setting.
type TraceContext ¶
type TraceContext = types.W3cTraceContext
TraceContext carries one native prompt's W3C request-envelope metadata. It is independent of the optional unified agent package.
func TraceContextFromContext ¶
func TraceContextFromContext(ctx context.Context) (TraceContext, bool)
TraceContextFromContext reads the current carrier without validating it. Derived contexts inherit the value; repeated writes keep the latest value.
type UnattributedRecord ¶
type UnattributedRecord struct {
Sequence uint64
ReceivedAt time.Time
Raw json.RawMessage
}
UnattributedRecord is diagnostic material, excluded from Session live streams. Raw is not an answer capability and is never replayed after later association.
type UnattributedSnapshot ¶
type UnattributedSnapshot struct {
Records []UnattributedRecord
MaxRecords, MaxBytes, RetainedBytes int
Retention time.Duration
Received, Evicted, Expired uint64
CoverageGap bool
}
UnattributedSnapshot declares the diagnostic retention range and lost coverage. Evicted includes oversized records; Expired counts retention expiry.
Source Files
¶
- client.go
- environment.go
- errors.go
- frame_transport.go
- history.go
- id.go
- mcp.go
- options.go
- redact.go
- remote.go
- requests.go
- session.go
- session_archive.go
- session_child_detail.go
- session_config.go
- session_discovery.go
- session_inject.go
- session_input.go
- session_observation.go
- session_ownership.go
- session_policy.go
- session_quarantine.go
- session_requests.go
- stdio_transport.go
- stream.go
- subscription.go
- thread.go
- trace.go
- websocket_frames.go
- wire.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
apiusage
Package apiusage contains compile-checked examples.
|
Package apiusage contains compile-checked examples. |
|
history-query-offline
command
history-query-offline uses a synthetic subprocess, never an installed agent.
|
history-query-offline uses a synthetic subprocess, never an installed agent. |
|
observe-subagents-offline
command
This executable talks only to a synthetic copy of itself, never to Codex.
|
This executable talks only to a synthetic copy of itself, never to Codex. |
|
observe-turn
command
Observe a managed root and descendants on an explicitly chosen executable.
|
Observe a managed root and descendants on an explicitly chosen executable. |
|
remote-execution-offline
command
This example demonstrates a best-effort remote MCP profile for Codex.
|
This example demonstrates a best-effort remote MCP profile for Codex. |
|
resume-thread
command
Command resume-thread explicitly opens a fresh connection, resumes a native ID already known to the caller, reads it, and detaches server-side observation.
|
Command resume-thread explicitly opens a fresh connection, resumes a native ID already known to the caller, reads it, and detaches server-side observation. |
|
tests
|
|
|
replay
SDK-specific fixtures and process adapters; native protocol matching belongs to the tool.
|
SDK-specific fixtures and process adapters; native protocol matching belongs to the tool. |
|
Package types exposes native app-server parameters, results, and recursive model types from the exact official Codex revision recorded in the generated source.
|
Package types exposes native app-server parameters, results, and recursive model types from the exact official Codex revision recorded in the generated source. |