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 ¶
- Variables
- type AnswerError
- type AnswerHandle
- type CallError
- type Client
- func (c *Client) Call(ctx context.Context, method string, params any, result any) error
- func (c *Client) Close() error
- func (c *Client) Diagnostics() DiagnosticSnapshot
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Err() error
- func (c *Client) InterruptTurn(ctx context.Context, p protocol.TurnInterruptParams) (protocol.TurnInterruptResponse, error)
- func (c *Client) ReadThread(ctx context.Context, p protocol.ThreadReadParams) (protocol.ThreadReadResponse, error)
- func (c *Client) Requests() <-chan Request
- func (c *Client) ResumeThread(ctx context.Context, p protocol.ThreadResumeParams) (protocol.ThreadResumeResponse, error)
- func (c *Client) ServerInfo() protocol.InitializeResponse
- func (c *Client) StartThread(ctx context.Context, p protocol.ThreadStartParams) (protocol.ThreadStartResponse, error)
- func (c *Client) StartTurn(ctx context.Context, p protocol.TurnStartParams) (protocol.TurnStartResponse, error)
- func (c *Client) Subscribe(ctx context.Context) (*Subscription, error)
- func (c *Client) UnsubscribeThread(ctx context.Context, p protocol.ThreadUnsubscribeParams) (protocol.ThreadUnsubscribeResponse, error)
- type DecodeError
- type DiagnosticSnapshot
- type DispatchState
- type Event
- type ID
- type Limits
- type RPCError
- type RemoteOptions
- type Request
- type StdioOptions
- type Subscription
- type SubscriptionOverflowError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrSubscriptionOverflow = errors.New("codex: subscription overflow; events lost") ErrRemoteTransport = errors.New("codex: remote transport failure") ErrClosed = errors.New("codex: connection closed") 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.
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)
}
Output:
func NewStdio ¶
func NewStdio(ctx context.Context, options StdioOptions) (*Client, error)
NewStdio starts the explicitly selected executable, completes initialize then writes initialized before returning. The context bounds construction only.
func (*Client) Call ¶
Call invokes a raw protocol extension with the same bounds and no-replay rules as typed operations. nil params omits params; json.RawMessage("null") sends null. A nil result discards the result. Raw calls do not certify method support.
func (*Client) Close ¶
Close is idempotent and bounded. A remote client closes only its socket. A stdio client closes stdin, allows a bounded grace period, then kills only the child it started and waits for reaping. It never sends a protocol shutdown RPC or kills an unrelated process, process group, or remote server.
func (*Client) Diagnostics ¶
func (c *Client) Diagnostics() DiagnosticSnapshot
func (*Client) InterruptTurn ¶
func (c *Client) InterruptTurn(ctx context.Context, p protocol.TurnInterruptParams) (protocol.TurnInterruptResponse, error)
InterruptTurn explicitly requests interruption of the caller's native turn. A successful acknowledgement is not evidence that execution has completed.
func (*Client) ReadThread ¶
func (c *Client) ReadThread(ctx context.Context, p protocol.ThreadReadParams) (protocol.ThreadReadResponse, error)
func (*Client) Requests ¶
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
}
Output:
func (*Client) ResumeThread ¶
func (c *Client) ResumeThread(ctx context.Context, p protocol.ThreadResumeParams) (protocol.ThreadResumeResponse, error)
ResumeThread sends the caller's native thread ID unchanged and accepts only a response with that same ID. It never creates a replacement thread, reconnects, or replays a request. Optional parameters preserve omitted/null/value states. Native history/path selectors can select another identity; such a response is an ErrProtocol failure under this method's strict identity contract.
func (*Client) ServerInfo ¶
func (c *Client) ServerInfo() protocol.InitializeResponse
func (*Client) StartThread ¶
func (c *Client) StartThread(ctx context.Context, p protocol.ThreadStartParams) (protocol.ThreadStartResponse, error)
func (*Client) StartTurn ¶
func (c *Client) StartTurn(ctx context.Context, p protocol.TurnStartParams) (protocol.TurnStartResponse, error)
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 ¶
func (c *Client) UnsubscribeThread(ctx context.Context, p protocol.ThreadUnsubscribeParams) (protocol.ThreadUnsubscribeResponse, error)
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 ¶
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 (ID) MarshalJSON ¶
func (ID) StringValue ¶
func (*ID) UnmarshalJSON ¶
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.
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 ¶
Data decodes a fresh native payload. Unknown methods return nil, nil; malformed known payloads return a DecodeError while Params retains the original bytes.
func (Request) Handle ¶
func (r Request) Handle() AnswerHandle
func (Request) Params ¶
func (r Request) Params() json.RawMessage
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
Source Files
¶
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. |