codex

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0, Apache-2.0 Imports: 32 Imported by: 1 module, 0 packages

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

README

Codex SDK for Go

Use github.com/zoumo/agent-sdk-go/codex to start or connect to a Codex app-server. Import github.com/zoumo/agent-sdk-go/codex/types for native protocol values. Go 1.26 or newer is required.

Use the unified Codex adapter for the shared live session API. For same-connection read-only native queries from a unified Core, use agentcodex.Core.NativeClient().

Open, submit and receive

Run the offline child observation example from the repository root.

go run ./codex/examples/observe-subagents-offline

The example prints synthetic root and child events with their native IDs. To use a real Codex app-server, install a CLI that meets the compatibility notes and configure its account. Then follow these steps.

  1. Set Stdio.Executable to the absolute path of the installed codex CLI.
  2. Call Open to start the app-server and create a thread.
  3. Call Submit and save the native turn ID from submission.Response.
  4. Call Receive to read events. Match TurnCompletedNotification against your thread and turn IDs. Read Turn.Status for the native result.

Running the following program can execute model work. It prints the turn ID, text deltas, and the turn status. If the app-server requests a decision, the example exits and releases the Session. In an interactive application, route the original request to your decision handler.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/zoumo/agent-sdk-go/codex"
	"github.com/zoumo/agent-sdk-go/codex/types"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() (err error) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	session, err := codex.Open(ctx, codex.SessionOptions{
		Stdio: &codex.StdioOptions{
			Executable: "/explicit/path/to/codex",
			Args:       []string{"app-server"},
			Initialize: types.InitializeParams{
				ClientInfo: types.ClientInfo{Name: "example", Version: "1"},
			},
		},
		Thread: types.ThreadStartParams{Ephemeral: types.Some(true)},
	})
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, session.Abort()) }()

	submission, err := session.Submit(ctx, codex.Input{
		Input: []types.UserInput{{Text: types.Ptr(types.TextUserInput{Text: "Say hello briefly."})}},
	})
	if err != nil {
		return err
	}
	turnID := submission.Response.Turn.ID
	fmt.Println("native turn", turnID)

	for {
		received, err := session.Receive(ctx)
		if err != nil {
			return err
		}
		if received.Request != nil {
			return fmt.Errorf("request %s requires an application decision", received.Request.Method())
		}
		if received.Event == nil {
			continue
		}
		if received.Event.DecodeError != nil {
			return received.Event.DecodeError
		}
		switch event := received.Event.Data.(type) {
		case *types.AgentMessageDeltaNotification:
			if event.ThreadID == session.ThreadID() && event.TurnID == turnID {
				fmt.Print(event.Delta)
			}
		case *types.TurnCompletedNotification:
			if event.ThreadID == session.ThreadID() && event.Turn.ID == turnID {
				fmt.Printf("\nturn %s: %s\n", turnID, event.Turn.Status)
				if event.Turn.Status != types.TurnStatusCompleted {
					return fmt.Errorf("turn %s ended with status %s", turnID, event.Turn.Status)
				}
				return nil
			}
		}
	}
}

Open initializes the connection and fixes the server's main identity before returning. StartResponse retains a copy of the actual native startup model, sandbox and unknown fields. Each Session owns one FIFO; Receive selects native events, real IncomingRequest values and SDK observation evidence. Concurrent receivers compete for that same FIFO. Applications own UI/logging fan-out. A native result does not close the Session. Submit uses native turn/start, retains the actual native turn response, and never guesses start versus steer from local Busy state. A successful response is not turn completion.

Use IncomingRequest.Approve / Deny with native ApprovalOptions, or Answer with types.ToolRequestUserInputResponse keyed by original question IDs. Native scope, execpolicy and network amendment options survive. The original Handle().Answer supports explicit raw extensions; Handle().Reject is an RPC error, separate from a user denial. Copies retain the same single-use authority. Cancellation, native resolution or Session termination invalidates that authority. No answer timeout, default deny or automatic retry is imposed by Session.

Native types.Event retains exact Raw, Params, unknown fields/variants and native thread/turn/item IDs. Malformed known payloads retain bytes with a decode error; malformed envelopes terminate interaction. Raw duplicates remain facts. Confirmed members deliver immediately even when parent knowledge is missing. Later parent evidence never reorders earlier facts. Unconfirmed connection records are bounded diagnostic material in Unattributed, never live authority; later membership does not replay them into the Session FIFO.

Receive cancellation affects only that wait. Interrupt requires an explicit native TurnID; its acknowledgment does not prove execution stopped. Close invalidates owned handles and cleans up without waiting for consumers. Done reports interaction termination independently of unread events. Drain to EOF or the stable terminal error, or explicitly Abort to discard abandoned backlog.

Compatibility

The source/schema target is Codex 0.162.1 at 092d3acd6bec3e3a14bdc7e7a2810ab628ab759d; no supported-version range is claimed. Current bindings and descendants have source/offline evidence only. Historical CLI 0.162.1 stdio/loopback WS and user-input checks used older SDK/schema bases; approvals and interrupt were untriggered, public WSS/JWT and current descendants remain unverified. Exact scopes stay in evidence.json.

Use capabilities.json for the method inventory and protocol provenance for source hashes and licensing. Raw Call/types support is not workflow support. Dedicated steering/work queues, thread deletion/rename/compact and other administration, hooks/plugins, MCP server management/discovery, realtime, credential management and durable recovery are not provided. Child observation does not provide a spawn controller, complete forwarding or combined completion.

Session model and reasoning settings

Creation uses SessionOptions.Thread (types.ThreadStartParams). Dynamic changes use Session.SetModel(ctx, nativeModelID) and Session.SetThinking with a native types.ReasoningEffort value such as "high". The connection must opt in during initialization with Capabilities: types.Some(types.InitializeCapabilities{ExperimentalAPI: types.Some(true)}). Without that opt-in, setters return ErrUnsupportedConfiguration with NotSent. Empty model/effort selectors return ErrInvalidInput with NotSent; other native model identifiers and effort strings go to the server for validation.

ConfigurationReceipt preserves the native request and empty settings response; NativeAccepted reports RPC acceptance only. Observe the separate types.ThreadSettingsUpdatedNotification through Session.Receive for native settings facts. Neither request nor ack establishes the currently executing model. At the pinned version, null/omitted effort both leave the override unchanged; neither means clear. Changes target the main thread's subsequent turns, without waiting for idle, changing children explicitly, or substituting turn/start, steer, resume or interrupt. Submit retains its independent native turn/start options and target.

Native refusal remains a CallError wrapping RPCError; possible dispatch followed by cancellation, timeout or Close remains OutcomeUnknown and is never retried automatically. Validation is synthetic/offline; no real configuration effect, active-turn switch, or child inheritance is certified.

Thread feature and tool policy

SessionOptions.Features and SessionOptions.Tools add explicit native dotted configuration to thread/start or thread/resume. They are fixed when Open creates the Session; low-level Client.StartThread and Client.ResumeThread keep their native-only signatures.

SDK value Native config path
codex.FeatureShellTool features.shell_tool
codex.FeatureViewImage features.view_image
codex.FeatureImageGeneration features.image_generation
codex.ToolUpdatePlan tools.update_plan.enabled
codex.ToolRequestUserInput tools.experimental_request_user_input.enabled

Every map entry emits its exact true or false value. Omitted keys do not override the native configuration, and unknown feature/tool strings pass through for the native config layer to accept, ignore or reject:

session, err := codex.Open(ctx, codex.SessionOptions{
    Thread: types.ThreadStartParams{Ephemeral: types.Some(true)},
    Features: map[codex.Feature]bool{
        codex.FeatureShellTool:       false,
        codex.FeatureViewImage:       false,
        codex.FeatureImageGeneration: false,
    },
    Tools: map[codex.Tool]bool{
        codex.ToolUpdatePlan: false,
    },
})

The SDK copies the caller maps and raw Config map instead of mutating them. If the raw config already contains a generated path, or an ancestor or descendant of that path, Open returns ErrInvalidInput before the thread RPC. The error names the conflicting paths but omits configuration values.

Tools is not a general built-in deny list. It only covers native switches with an .enabled path. Codex has no SDK mapping here for names such as Read, Write, Glob or apply_patch, and the SDK does not expose features.unified_exec=false because that value is not a reliable execution switch.

FeatureShellTool: false disables command-execution tools across environments at the native feature layer. It does not guarantee local zero execution: apply_patch may still be exposed by the model catalog, and other native or configured capabilities may remain. Use an external sandbox and permission policy when hard isolation is required. Synthetic tests verify the emitted app-server parameters; they do not prove that a real Codex process removed a tool.

Thread MCP servers

SessionOptions.MCPServers []mcp.Server adds external MCP servers to this Session's thread/start.config or thread/resume.config. The shared mcp package is the single configuration type used here, by Claude, and by the unified agent layer. It does not write the user config.toml, and low-level Client.StartThread / Client.ResumeThread remain native-only. The fixed merge and limitation contract is in the native Session design.

SDK field Native field
Name mcp_servers.<name> key
Command command
Args args
Env env
Cwd cwd
URL url
Headers http_headers
EnvHeaders env_http_headers
BearerTokenEnvVar bearer_token_env_var

Transport is required: mcp.TransportStdio permits Command, Args, Env and Cwd; mcp.TransportHTTP permits URL, Headers, EnvHeaders and BearerTokenEnvVar. The SDK rejects mcp.TransportSSE before the thread RPC. EnvHeaders maps header names to environment-variable names. BearerTokenEnvVar is also an environment-variable name, not the secret itself.

session, err := codex.Open(ctx, codex.SessionOptions{
    Thread: types.ThreadStartParams{Ephemeral: types.Some(true)},
    Features: map[codex.Feature]bool{
        codex.FeatureShellTool:       false,
        codex.FeatureViewImage:       false,
        codex.FeatureImageGeneration: false,
    },
    MCPServers: []mcp.Server{{
        Name:       "remote",
        Transport:  mcp.TransportHTTP,
        URL:        "https://example.invalid/mcp",
        EnvHeaders: map[string]string{"Authorization": "REMOTE_AUTHORIZATION"},
    }},
})

This combination is the best-effort remote execution profile. The feature and ambient-configuration limits above and below still apply.

Server names must be nonempty valid UTF-8, must not contain ., and must be unique. Invalid combinations, including a raw Config key at the same path or an ancestor/descendant of mcp_servers.<name>, return ErrInvalidInput before the thread RPC. Errors name paths and fields but do not include configuration values. The SDK copies the server slices/maps and raw Config map; callers can reuse or modify their inputs after Open returns.

Prefer EnvHeaders or BearerTokenEnvVar for credentials. Literal Headers and Env values become part of the native configuration and may be visible to process inspection or protocol diagnostics; validation errors omit those values.

Codex has no equivalent of Claude's --strict-mcp-config. This wrapper adds or replaces only the servers named in MCPServers; it cannot remove MCP servers loaded from user, project or managed configuration. To use only the servers declared by the application, start Codex with an isolated CODEX_HOME whose configuration contains no additional mcp_servers. An isolated home also needs separately arranged authentication and any required native configuration.

MCP tool filters, OAuth interaction, timeouts, approval policy and server health checks are not wrapped here. MCP connectivity, TLS/proxy behavior, authentication, discovered tool names, remote permissions and the actual operations belong to Codex and the service. Synthetic app-server tests verify the emitted configuration only; they do not prove that a successful thread RPC connected to an external server or exposed a particular tool.

The offline example uses a synthetic app-server and example.invalid; it asserts the complete final thread/start params without contacting the URL or running Codex:

go run ./codex/examples/remote-execution-offline

Optional child detail delivery

To omit reviewed pure child text, reasoning and tool progress from Receive, set SessionOptions.ChildDetailPolicy: codex.ChildDetailSuppress when calling Open. The zero value and codex.ChildDetailPreserve retain default delivery. Other values wrap ErrInvalidInput before process startup or RPC. The policy is fixed per Session, including subsequent submissions and confirmed child members; shared Client sessions select independently.

Filtering leaves native source output, parent tool results, relationships, approvals and lifecycle facts intact. Complete items and mixed/unknown frames remain visible, with their original bytes. It is not content redaction or a token-cost control. The policy also applies to Open with explicit Resume parameters. Low-level Client.ResumeThread is unchanged. See the exact method and shape contract. NativeIntegrationSuite/TestOptionalChildDetail/codex/F1–F5 validates synthetic public API delivery and original peer bytes; real child interoperability remains unverified.

Query existing descendants

Session.ListSubagents(ctx, SubagentQuery{}) reads bounded native pages of stored descendants of the fixed main identity. Initialize with experimentalApi enabled. Inspect returned Pages, Coverage and the error together: partial pages can accompany a failure. Defaults select five native subAgent source kinds and only non-archived records; archived records need a separate query. Results do not change observation membership or prove that an Agent is running or subscribed.

Discovery walks pages with defaults of 128 pages, 10000 records and 16 MiB; MaxPages/MaxRecords/MaxBytes override these bounds. Failed calls retain accepted whole pages plus error/Coverage. EndReached requires explicit terminal null; EnumerationComplete also requires starting without a cursor. Missing/repeated/empty continuation cursors fail explicitly. No automatic retry or cache fallback runs.

Context injection

Session.Inject(ctx, []json.RawMessage{item}) sends raw Responses API items to the owned main thread through thread/inject_items. Use this for context that should not request a model response. The server validates the item semantics; empty input or malformed JSON fails locally. No turn/start, steer or interrupt is sent as a fallback. Native dispatch errors retain CallError and RPCError evidence. Source/version limits and the distinction between RPC acceptance, recording and consumption are documented in the protocol sources.

Archive and unarchive

Session.Archive(ctx) and Session.Unarchive(ctx) send native thread/archive and thread/unarchive for the Session's fixed main thread. The methods do not accept an arbitrary thread ID. Archive returns the native empty acknowledgement with unknown fields; Unarchive returns the restored native types.Thread and unknown fields. Unarchive rejects a response whose restored Thread ID differs from the fixed main thread as ErrProtocol.

if _, err := session.Archive(ctx); err != nil { return err }

restored, err := session.Unarchive(ctx)
if err != nil { return err }
fmt.Println(restored.Thread.ID)

Success is native RPC acceptance, not proof that the archive state has already changed. Observe the native thread/archived or thread/unarchived notification through Session.Receive. Archiving is not deletion: the SDK does not remove the transcript or close the Session. The native server may shut down a loaded thread before archiving it and may also archive spawned descendant threads. Unarchive restores stored thread state; it does not resume, attach or start execution. The Claude package does not offer these methods because Claude Code's terminal protocol has no native archive contract; moving local transcript files is not a supported substitute.

Connect to an existing remote app-server

Use the same client methods with an explicitly selected WS/WSS endpoint and a nonempty caller-supplied bearer token. Supply the token from your application; the SDK never discovers credentials, signs in, mints a token, or refreshes it.

client, err := codex.NewRemote(ctx, codex.RemoteOptions{
    URL:         "wss://codex.example.com/",
    BearerToken: token, // supplied by your application; never put it in the URL
    Initialize: types.InitializeParams{
        ClientInfo: types.ClientInfo{Name: "my-client", Version: "0.1"},
    },
})
if err != nil { return err }
defer client.Close()

session, err := codex.Open(ctx, codex.SessionOptions{Client: client,
    Thread: types.ThreadStartParams{Ephemeral: types.Some(true)},
})
if err != nil { return err }
defer session.Close()
fmt.Println(session.ThreadID())

NewRemote validates its options before dialing, then completes initialize and initialized before returning. Pass a deadline on ctx to bound startup; the configured call timeout bounds dialing plus initialization. Limits has the same finite defaults as stdio. Canceling the constructor context after success does not close the client; call Close() explicitly. Each complete WebSocket text message carries one JSON envelope, with no JSONL delimiter. The transport handles fragmentation. JSON batches, multiple envelopes in one message, and binary messages are unsupported; malformed or oversized messages terminate the connection explicitly.

  • Authentication uses only Authorization: Bearer <token>. URL user information, query strings, and fragments are rejected. Redirects are never followed. Tokens must have valid bearer-token syntax; whitespace/control characters are rejected. No Origin header or environment-selected HTTP proxy is used.
  • WSS verifies the certificate and hostname. To trust a private CA, set TLSConfig: &tls.Config{RootCAs: trustedRoots} using crypto/tls and a caller-built *x509.CertPool. InsecureSkipVerify is rejected, and TLS versions below 1.2 are not enabled.
  • Plain ws:// is allowed for localhost and numeric loopback addresses. Before sending the bearer header, the connected TCP peer must also be loopback. AllowInsecureWS: true explicitly permits other hosts, exposing the bearer token and protocol traffic to the network. Prefer WSS or a secured loopback tunnel.
  • ErrRemoteTransport reports sanitized stage/status information, without URL, token, response body, or peer-supplied close reason. Only safe underlying causes such as context cancellation and EOF are retained. Reflected bearer redaction follows the error rules. Successful results, events, and request payloads remain caller-sensitive data; the SDK is not a general logging redactor and cannot control server logs.

There is no automatic reconnect or request replay. After a lost connection, inspect the operation's dispatch evidence, create a new initialized client, then explicitly resume the saved native thread ID if appropriate. An unknown outcome must be reconciled before repeating side-effecting work. Remote Close releases only this connection; it never shuts down or kills the remote service.

The WSS example describes a caller-provided TLS endpoint; source inspection and synthetic TLS tests do not certify a production TLS proxy, bearer issuer, server configuration, or live account. See the canonical evidence and transport provenance. The remote example compiles in tests and is never executed.

Native values and raw extensions

Native types production code uses only the standard library. Generated Optional[T] preserves omission, explicit null, false, zero and empty collections. Unknown fields retain their JSON without float64 conversion. Representability is not permission to submit an unsupported workflow. The server still validates native constraints. See generation provenance.

ApprovalPolicy and the corresponding ApprovalPolicy* constants enumerate untrusted, on-request and never. The scalar AskForApproval.Value uses this type, while the native union still preserves Granular and unrecognized string values. The former AskForApprovalValue names remain as deprecated aliases for source compatibility.

An explicit Client remains useful for a shared native I/O resource, handshake metadata and Call extensions. Supply it in SessionOptions.Client. Closing one Session leaves other owners on that connection usable. A main identity has one owner. Overlapping child/ancestor observation ranges share physical attachments; only the final observer releases them. Typed detachment/resume operations respect ownership and uncertain-release fences. Raw calls are outside coordinated Session guarantees and never create a second consumer or answer registry.

The SDK does not discover executables, log in, look up credentials, reconnect or retry. Env=nil inherits the parent environment; an explicit environment can select an isolated CODEX_HOME. Stdio owns its chosen child; remote Close owns only the socket. The selected native executable can read its own configuration.

Cancellation and errors

A context timeout cancels local waiting. It does not stop server execution or send an invented cancellation notification. CallError unwraps its cause and carries:

  • NotSent: no write began; local admission, encoding, or cancellation failed.
  • OutcomeUnknown: a write may have begun, without a matching definitive reply.
  • Responded: the matching server error or an invalid typed result was received.

Use errors.Is for context/transport causes and errors.As for *RPCError. RPCError retains its code, message, and raw optional data, with a remote-security exception: a reflected bearer token is replaced in diagnostic messages, data, and raw error JSON. Unaffected raw errors stay byte-for-byte intact; redacted JSON replaces only affected lexical values, including reflected keys/numbers; unaffected bytes, duplicate members, and numeric lexemes remain intact. Native error codes and RPC correlation remain unchanged. Unsafe reflected custom error causes are scrubbed rather than exposed through Unwrap; public SDK sentinel classification remains. A server error is not proof that no side effect occurred. Nothing is retried automatically. A canceled blocked write terminates the connection to release the writer; other pending calls then fail with their own dispatch evidence. Late responses cannot satisfy new calls.

Bounds and connection ownership

DefaultLimits() supplies per-connection resource and operation defaults. Each zero field in Limits selects its default; negative values are rejected:

  • Incoming and outgoing JSON payload: 8 MiB, excluding stdio newline or WS framing
  • Queued outbound frames: 32; pending calls: 128
  • Session owners: 32; accepted event backlog grows with memory
  • Active reverse requests: 128; delivery uses the Session FIFO
  • Unanswered handle lifetime: native resolution/termination only; no SDK deadline
  • Request identity registry: 4096 distinct tagged ID/method/params identities per connection (RequestIdentities). Terminal entries are retained; exhaustion fails with ErrRequestOverflow rather than restoring answer permission. Different method/params may reuse a terminal ID. This is an SDK replay-safety boundary, not a claim that the native server guarantees globally unique IDs.
  • Diagnostic tail: 64 KiB; all stderr content is replaced with redaction markers
  • Every call, including initialization: at most 30 seconds unless configured
  • A blocked write: 10 seconds
  • Shutdown: 2 seconds; stdio splits this between graceful EOF and child reaping

Earlier caller deadlines win. Resource admission fails with ErrLimit before sending where possible. An oversized outgoing frame is not sent; malformed or oversized incoming frames terminate the connection with an explicit cause. Bounded diagnostic counters record unmatched responses and notifications without retaining diagnostic payloads. Session storage scales with unread events and frame size; a slow consumer can exhaust available memory. This is neither durable delivery nor an OOM guarantee. SDK decoding runs on the reader, but caller callbacks never do. Stderr is drained independently of the reader.

Close() is concurrent-safe and idempotent. For stdio it closes stdin, waits for graceful exit, then kills and reaps only the owned child. For a remote client it closes only its WebSocket connection. Both settle pending calls, Sessions, and reverse-request handles; stdio also closes all owned pipe ends. A child exit is detected even if an inherited output pipe remains open. It does not kill descendants, process groups, or an existing daemon. Done() signals connection termination; Err() gives the terminal cause. A rare OS failure to reap before the shutdown deadline returns ErrShutdownTimeout; the background Wait still owns reaping. User-defined JSON marshal/unmarshal implementations run in the caller and must cooperate; the SDK cannot interrupt arbitrary Go code.

Native resume and history queries

Resume a public Session on a shared client or an owned stdio process:

session, err := codex.Open(ctx, codex.SessionOptions{
    Client: client,
    Resume: &types.ThreadResumeParams{ThreadID: savedID},
})

Resume requires a nonempty native ID and empty Thread start options. It reserves ownership before dispatch and returns only after the native response confirms the same identity. Live notifications around that response retain their arrival order. ResumeResponse() returns a detached copy of the actual native response; StartResponse() is absent. Saved turns do not enter Receive, grant answer authority, or establish live child membership. Use ListSubagents to query already saved descendants without submitting another turn.

Recovery is explicit and preserves native resume side effects. It does not retry, create a replacement thread, or promise to recover missed events. Failed or uncertain dispatch performs bounded detachment; failed cleanup preserves an ownership fence. Shared clients remain open; owned processes are reaped.

Client.ResumeThread(ctx, types.ThreadResumeParams{ThreadID: id}) explicitly resumes a native thread. It does not create a Session or project saved history into Session.Receive events. Client.UnsubscribeThread releases that native attachment.

Client.ListThreads, Client.ReadThread, Client.ListThreadTurns and Client.ListThreadItems query native metadata and saved content without Open or resume. Prefer ReadThread with IncludeTurns: types.Some(false). Each call returns one native result; keep opaque next/backwards cursors, sort direction, item-view selection and omitted/null/value fields. Query availability depends on the server version/backend and stored history format. Metadata and saved items are not original notification/delta/approval logs or atomic snapshots. Remote queries use server storage and paths; local list may repair metadata unless UseStateDbOnly selects the native DB-only path. See query boundaries and the offline example.

Offline examples and validation

Run the root offline gate with Go 1.26 or newer. The offline examples use explicit synthetic peers and code-owned protocol inputs, never an installed agent. Migration details distinguish native limitations, resource options and breaking lifecycle changes.

Run from the repository root:

go run ./codex/examples/history-query-offline
go run ./codex/examples/observe-subagents-offline

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

Examples

Constants

This section is empty.

Variables

View Source
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")
)
View Source
var (
	ErrOwnershipConflict = errors.New("codex: session ownership conflict")
	ErrInvalidInput      = errors.New("codex: invalid or unsupported input")
)
View Source
var (
	ErrUnsupportedDiscovery = errors.New("codex: descendant queries require experimentalApi initialization")
	ErrDiscoveryCursor      = errors.New("codex: descendant query cursor did not advance or repeated")
)
View Source
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

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.

func (*CallError) Error

func (e *CallError) Error() string

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

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)
}

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

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

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

func (c *Client) Close() error

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

func (c *Client) CloseInput() error

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) Done

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

func (*Client) Err

func (c *Client) Err() error

func (*Client) InterruptTurn

InterruptTurn explicitly requests interruption of the caller's native turn. A successful acknowledgement is not evidence that execution has completed.

func (*Client) ListThreadItems

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

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

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

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

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 (*Client) StartTurn

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

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

type DecodeError struct {
	Method string
	Cause  error
}

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 Feature

type Feature string

Feature selects a native thread feature under features.<key>.

const (
	FeatureShellTool       Feature = "shell_tool"
	FeatureViewImage       Feature = "view_image"
	FeatureImageGeneration Feature = "image_generation"
)

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 IntegerID

func IntegerID(v int64) ID

func ParseID

func ParseID(raw []byte) (ID, error)

func StringID

func StringID(v string) ID

func (ID) Integer

func (id ID) Integer() (int64, bool)

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

func (ID) String

func (id ID) String() string

func (ID) StringValue

func (id ID) StringValue() (string, bool)

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(raw []byte) error

func (ID) Valid

func (id ID) Valid() bool

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

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.

func (*RPCError) Error

func (e *RPCError) Error() string

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

func (r Request) Data() (any, error)

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) ID

func (r Request) ID() ID

func (Request) Method

func (r Request) Method() string

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 Open

func Open(ctx context.Context, options SessionOptions) (*Session, error)

func (*Session) Abort

func (s *Session) Abort() error

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

func (s *Session) Close() error

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) Done

func (s *Session) Done() <-chan struct{}

func (*Session) Err

func (s *Session) Err() error

func (*Session) Inject

func (s *Session) Inject(ctx context.Context, items []json.RawMessage) error

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

func (s *Session) Receive(ctx context.Context) (Received, error)
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
}

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

func (s *Session) SetModel(ctx context.Context, model string) (ConfigurationReceipt, error)

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) Submit

func (s *Session) Submit(ctx context.Context, input Input) (Submission, error)

func (*Session) ThreadID

func (s *Session) ThreadID() string

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 Tool

type Tool string

Tool selects a native tool switch under tools.<key>.enabled.

const (
	ToolUpdatePlan       Tool = "update_plan"
	ToolRequestUserInput Tool = "experimental_request_user_input"
)

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.

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.

Jump to

Keyboard shortcuts

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