codex

package module
v0.0.0-...-c3842e2 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 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-go

A native Go client for the Codex app-server protocol.

Start with compatibility and the complete official capability inventory. The protocol source is pinned to one exact official commit. Mock tests are not live certification, and no supported-version range is claimed.

Local thread example

Go 1.26.9 is pinned with mise. Install the toolchain using your normal mise setup; then build with mise exec go@1.26.9 -- go test ./....

package main

import (
    "context"
    "fmt"
    "log"

    codex "github.com/zoumo/codex-sdk-go"
    "github.com/zoumo/codex-sdk-go/protocol"
)

func main() {
    ctx := context.Background()
    client, err := codex.NewStdio(ctx, codex.StdioOptions{
        Executable: "/path/you/selected/codex",
        Args:       []string{"app-server"},
        Initialize: protocol.InitializeParams{
            ClientInfo: protocol.ClientInfo{Name: "my-client", Version: "0.1"},
        },
    })
    if err != nil { log.Fatal(err) }
    defer client.Close()

    started, err := client.StartThread(ctx, protocol.ThreadStartParams{
        Ephemeral: protocol.Some(true),
    })
    if err != nil { log.Fatal(err) }
    read, err := client.ReadThread(ctx, protocol.ThreadReadParams{
        ThreadID: started.Thread.ID,
        IncludeTurns: protocol.Some(true),
    })
    if err != nil { log.Fatal(err) }
    fmt.Println(read.Thread.ID)
}

The SDK does not download or discover Codex, log in, look up credentials, launch a shell, or own ambient stdin/stdout. The explicitly selected executable can itself read configuration or credentials and perform side effects. Env == nil inherits the parent environment; supply an explicit environment and isolated CODEX_HOME when needed. No executable is launched by importing this package.

The constructor sends initialize, awaits its response, then writes initialized before returning. ServerInfo() returns the native handshake result. Native thread, session, turn, and item identifiers are never fabricated.

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: protocol.InitializeParams{
        ClientInfo: protocol.ClientInfo{Name: "my-client", Version: "0.1"},
    },
})
if err != nil { return err }
defer client.Close()

started, err := client.StartThread(ctx, protocol.ThreadStartParams{
    Ephemeral: protocol.Some(true),
})
if err != nil { return err }
fmt.Println(started.Thread.ID)

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. Remote error messages and RPCError.Message, Data, and Raw also redact the explicitly supplied bearer if reflected by the peer, including supported JSON/URL-encoded echoes. 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.

Explicitly resume and detach a native thread

Keep the native thread ID returned by the server. After closing the old client, construct a new client with NewStdio or NewRemote for a fresh handshake, then resume and read that exact ID. The SDK has no saved-session registry or reconnect loop.

resumed, err := client.ResumeThread(ctx, protocol.ThreadResumeParams{
    ThreadID: nativeThreadID,
    // Omit ServiceTier to preserve the server's override.
    // ServiceTier: protocol.Null[string](), // explicitly clear the override
})
if err != nil { return err }
read, err := client.ReadThread(ctx, protocol.ThreadReadParams{
    ThreadID: resumed.Thread.ID,
    IncludeTurns: protocol.Some(true),
})
if err != nil { return err }
fmt.Println(read.Thread.ID)
detached, err := client.UnsubscribeThread(ctx, protocol.ThreadUnsubscribeParams{
    ThreadID: resumed.Thread.ID,
})
if err != nil { return err }
fmt.Println(detached.Status)

The compilable resume-thread example takes an explicit executable and an already-known native thread ID. Tests compile it but do not run it. A real server must still have the thread; the fake-peer tests do not establish cross-process server persistence or resumability of ephemeral data.

ResumeThread sends the supplied ID unchanged and checks response.thread.id. A mismatch returns ErrProtocol with CallError.Dispatch == Responded and the matching RPC ID. Missing/expired threads, RPC errors, timeouts, or lost connections never create a replacement thread or cause automatic replay.

All native resume fields are exposed, including experimental fields. The native server can select another identity when history or path overrides threadId. This typed wrapper deliberately requires the returned ID to equal the supplied ID even in those cases; prefer ID-only resume. It does not undo server-side work if validation fails. The raw Call escape hatch leaves alternative-identity handling to the caller and does not certify those workflows.

Resume ServiceTier distinguishes omission (keep the override), null (clear it), and a string (set it). ExcludeTurns can be omitted, false, or true, but not null. Other nullable fields preserve wire omission and null without claiming those states always mean different things to the server. Schema defaults are not silently inserted by the SDK.

UnsubscribeThread returns the native notLoaded, notSubscribed, or unsubscribed status (and preserves future string values). This is server-side thread detachment, separate from closing a local Subscription. It does not close local observers, delete the thread, send an interrupt, or establish that an active turn stopped. Server notifications already in flight may still arrive. Closing a local subscription never sends thread/unsubscribe.

Native values and extensions

Models live in the public protocol package. Optional[T] preserves omission, explicit null, and present values, including false, zero, and an empty list:

params := protocol.ThreadStartParams{
    Model: protocol.Some("caller-selected-model"),
    ServiceTier: protocol.Null[string](),
    Ephemeral: protocol.Some(false),
}

Required members are checked on decoding. Generated objects retain unrecognized members in UnknownFields; unions expose typed variants and an Unknown raw fallback. Raw JSON values never pass through float64. Unknown wire structure and values are preserved, although re-encoding may normalize whitespace/key order. These loss-preserving bindings are not strict JSON Schema validators: native minimum/maximum and additionalProperties constraints are not all enforced, and unknown enum, union, and extension values can remain representable. The server remains responsible for accepting a request. See generation provenance for the exact native fields.

Call(ctx, method, params, result) is a raw extension escape hatch with the same bounds, exact correlation, and no-replay behavior. nil params omits the member; json.RawMessage("null") sends explicit null. A nil result discards the response. Calling an unwrapped method does not make it an officially supported SDK workflow. Incoming server requests have a separate bounded pull queue. Unknown methods remain caller-managed raw extensions; their reachability is not workflow certification.

Observe and explicitly interrupt a turn

StartTurn(ctx, protocol.TurnStartParams) and InterruptTurn(ctx, protocol.TurnInterruptParams) return native response types. Call Subscribe(ctx) first: a turn can emit events, including completion, before its start response. The response's turn ID remains authoritative for that response. The SDK does not filter, merge, accumulate, or reinterpret interleaved native thread/turn/item IDs.

The compilable observe-turn example registers before starting work, matches both native thread and turn IDs, and checks stream loss. It is compiled by tests, never run against a model. Running it yourself may use an authenticated account and consume model resources.

A subscription is local observation, active when returned; it does not replay notifications received before registration. Events() supplies ordered Event values with the original Method and raw JSON Params, plus optional typed Data and a separate DecodeError. Absent parameters remain nil; explicit null remains raw null. Each subscriber independently owns its raw and typed data. Typed payloads currently cover turn/started, turn/completed, item/started, item/completed, item/agentMessage/delta, error, and serverRequest/resolved. Other methods remain raw. Malformed supported payloads remain observable with *DecodeError; an invalid JSON envelope instead terminates the connection.

Done() closes immediately on subscription termination, independently of the bounded event queue. Accepted queued events remain readable after termination. After Done, inspect Err():

  • nil: explicit subscription or normal client close
  • context.Canceled / context.DeadlineExceeded: local subscription cancellation
  • *SubscriptionOverflowError / ErrSubscriptionOverflow: the stream lost events
  • Another error: the underlying terminal connection failure

A full queue terminates only that subscriber, without waiting for it or preventing RPC response routing. Check terminal status even when a queued completion is available; an incomplete stream is not evidence of a complete observation. Close() releases local observation without waiting for a consumer. Subscription cancellation does not call thread/unsubscribe or turn/interrupt.

To request execution interruption explicitly, pass the exact native identities:

_, err := client.InterruptTurn(ctx, protocol.TurnInterruptParams{
    ThreadID: threadID,
    TurnID: turnID,
})

The acknowledgement is only an RPC response. It neither creates a completion event nor proves that execution stopped. There is no high-level turn runner, implicit interruption, or final-text aggregation.

Answer server requests explicitly

Requests() is a single bounded pull queue, available immediately after startup. Each immutable Request exposes ID(), Method(), Params(), Data(), and Handle(). Integer 1 and string "1" remain different identities. Params() and Data() return fresh copies, so UI mutations cannot change an answer target. Data() decodes native command/file/permissions approvals, tool user input, and legacy command/patch approvals. Unknown methods return nil, nil; malformed known payloads return *DecodeError without losing their original raw bytes.

Read requests concurrently with calls that might need an answer. Obtain the result from your application or user; the SDK supplies no default decision:

request, ok := <-client.Requests()
if !ok { return client.Err() }
fmt.Println(request.ID(), request.Method(), string(request.Params()))

// For example, read a caller-selected native JSON result from the terminal.
var result json.RawMessage
if err := json.NewDecoder(os.Stdin).Decode(&result); err != nil { return err }
if err := request.Handle().Answer(ctx, result); err != nil { return err }

The compiled example follows this pattern and is never executed by tests. Native response models such as protocol.CommandExecutionRequestApprovalResponse and protocol.ToolRequestUserInputResponse can be passed to Answer instead of raw JSON. Reject(ctx, &RPCError{...}) sends exactly the caller-selected protocol error. RPCError.Raw is inbound diagnostic data and is not sent.

A handle is opaque, bound to its original connection, and shared by copies. Only one answer or cancellation wins. Done() signals termination and Err() reports answered, locally canceled/expired, server-resolved, or connection failure. A successful Answer means its frame was written; it is not a peer acknowledgment or proof of execution. Competing/duplicate answers and stale handles fail locally. Once an answer is admitted to the outbound queue, it consumes the handle, including when a later timeout reports NotSent. Validation, pre-canceled context, oversized frame, and queue-admission failures leave an unanswered handle usable. Partial or ambiguous writes return AnswerError with OutcomeUnknown and cannot be replayed.

Cancel() and the configured handle expiry abandon a prompt locally. They send no response or cancellation and do not stop server work. The native serverRequest/resolved notification invalidates an unanswered matching handle using both its exact requestId and native thread identity. It can follow an answer or interruption and does not establish success. The first admitted answer or terminal signal wins; resolution does not retract an already admitted response. There is no invented generic cancellation method.

Slow consumers cannot block ordinary responses or notifications. Queue or active request exhaustion terminates the connection explicitly with ErrRequestOverflow (also ErrLimit), invalidating handles and pending calls; requests are never silently discarded or automatically denied. Buffered requests may already be expired/resolved when read. Check handle status before showing a prompt and use Done() to dismiss stale UI. Closing the client closes the request queue and invalidates every pending handle without waiting for consumer code.

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 finite per-connection 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
  • Active local subscriptions: 32; queued events per subscriber: 128
  • Active reverse requests: 128; queued reverse requests: 32
  • Unanswered handle lifetime: 5 minutes (local expiry, no protocol cancellation)
  • 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. Subscription storage scales with queue capacity, frame size, and subscriber count, including independent typed payload copies; use smaller limits for large events or many observers. 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, subscriptions, 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.

Development and evidence

mise exec go@1.26.9 -- go test ./...
mise exec go@1.26.9 -- go test -race ./...
mise exec go@1.26.9 -- go vet ./...
python3 docs/protocol/verify_inventory.py

Tests use only synthetic helper processes, loopback WS peers, and local WSS peers with synthetic certificates and dummy tokens. They never require an account or call a model. The CI workflow runs normal tests, race tests, vet, and inventory checks on pinned Go 1.26.9, with no service secrets or live-test step. Configuring CI is not evidence that a hosted CI run has passed. Ticket 01, ticket 02, ticket 03, ticket 04, and ticket 05 evidence record scenarios and verification status. Official testing patterns distinguishes app-server harnesses from the TypeScript SDK's codex exec transport.

Licensed under Apache-2.0. See NOTICE for official protocol attribution and dependency provenance for the WebSocket transport library. This is an independent SDK, not an OpenAI-maintained Go SDK.

Documentation

Overview

Package codex is a bounded, native Codex app-server client. See docs/compatibility.md for the exact 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")
	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 now use Requests and never emit this error.
	ErrUnsupportedRequest = errors.New("codex: server request unsupported by this SDK slice")
)

Functions

This section is empty.

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 after queue admission still consumes the handle. OutcomeUnknown 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. Cancel/expiry/resolution only win before an answer is admitted. 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 leave the handle usable. Once admitted, the handle is consumed even if cancellation occurs before writing. 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/expiry, 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 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 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/codex-sdk-go"
	"github.com/zoumo/codex-sdk-go/protocol"
)

func main() {
	ctx := context.Background()
	client, err := codex.NewRemote(ctx, codex.RemoteOptions{
		URL:         "wss://codex.example.com/",
		BearerToken: "caller-supplied-token",
		Initialize:  protocol.InitializeParams{ClientInfo: protocol.ClientInfo{Name: "my-client", Version: "0.1"}},
	})
	if err != nil {
		return
	}
	defer client.Close()
	started, err := client.StartThread(ctx, protocol.ThreadStartParams{Ephemeral: protocol.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 (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params any, 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) 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) ReadThread

func (*Client) Requests

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

Requests returns the connection's bounded pull queue, active from startup. A stalled consumer never blocks the reader. Exhausting RequestQueue or ActiveRequests explicitly fails the connection with ErrRequestOverflow. Close closes this channel without waiting for consumers; buffered requests remain readable, but all their handles are invalidated. Handle expiry may also leave terminal requests in the queue. Check Handle.Err before presenting a UI.

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/codex-sdk-go"
)

// 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() {
	// Obtain client from NewStdio and start/resume work on another goroutine.
	// No request is approved automatically, even for recognized methods.
	consume := func(ctx context.Context, client *codex.Client) error {
		for {
			select {
			case <-ctx.Done():
				return ctx.Err()
			case request, ok := <-client.Requests():
				if !ok {
					return client.Err()
				}
				if request.Handle().Err() != nil {
					continue
				}
				if err := answerFromTerminal(ctx, request); err != nil {
					return err
				}
			}
		}
	}
	_ = consume
}

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() protocol.InitializeResponse

func (*Client) StartTurn

StartTurn returns only the native response. Events, including early or stale completions, never change its result. Subscribe before starting a turn.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context) (*Subscription, error)

Subscribe registers before returning, with Limits.EventQueue slots. It does not replay prior notifications. Limits.Subscriptions bounds active streams.

func (*Client) UnsubscribeThread

UnsubscribeThread requests server-side detachment for the specified native thread once and returns the native status. It does not close local Subscription values or imply interruption, deletion, or completion of a thread's work.

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 Event

type Event struct {
	Method      string
	Params      json.RawMessage
	Data        any
	DecodeError error
}

Event preserves a notification's method and parameter JSON as received. Params is nil when the member was absent; explicit null remains the bytes "null". Data is a pointer to a supported protocol notification, or nil for unknown methods/decode failures. DecodeError is non-nil only for malformed supported payloads. Unknown fields and union variants remain in the native Data and in Params.

Each subscriber owns its event's buffers and typed data independently. There is no replay or filtering; callers match native thread, turn, and item IDs.

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 Limits

type Limits struct {
	MaxFrameBytes   int
	OutboundQueue   int
	PendingCalls    int
	Subscriptions   int
	EventQueue      int
	DiagnosticBytes int
	// ActiveRequests bounds received server requests until a terminal state.
	ActiveRequests int
	// RequestQueue bounds queued server requests, including terminal unread ones.
	RequestQueue int
	// RequestTimeout locally expires unanswered handles; it sends no cancellation.
	// Admitted answers instead use the caller context and CallTimeout.
	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 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 RemoteOptions

type RemoteOptions struct {
	URL         string
	BearerToken string
	Initialize  protocol.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 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

type StdioOptions

type StdioOptions struct {
	Executable string
	Args       []string
	Env        []string
	Dir        string
	Initialize protocol.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 Subscription

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

Subscription is a local, ordered, bounded notification stream, active when Subscribe returns. Events closes on termination; queued events remain readable. Done closes immediately even if Events is full. After Done, Err distinguishes normal Close (nil), context cancellation, overflow, and connection failure. No method interrupts execution or unsubscribes a thread on the server.

func (*Subscription) Close

func (s *Subscription) Close() error

Close ends local observation normally, without discarding queued events. It is idempotent and does not wait for a consumer. The first terminal cause wins.

func (*Subscription) Done

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

func (*Subscription) Err

func (s *Subscription) Err() error

func (*Subscription) Events

func (s *Subscription) Events() <-chan Event

type SubscriptionOverflowError

type SubscriptionOverflowError struct{ Capacity int }

SubscriptionOverflowError terminates one incomplete stream. Previously queued events remain readable, but the event that exceeded Capacity was not accepted.

func (*SubscriptionOverflowError) Error

func (e *SubscriptionOverflowError) Error() string

func (*SubscriptionOverflowError) Unwrap

func (e *SubscriptionOverflowError) Unwrap() error

Directories

Path Synopsis
examples
observe-turn command
Observe one native turn on an explicitly chosen executable.
Observe one native turn on an explicitly chosen executable.
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.
Package protocol exposes native app-server parameters, results, and recursive model types from the exact official Codex revision recorded in the generated source.
Package protocol 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