Skip to content

codex_app_server_sdk

codex_app_server_sdk

CancelResult

Bases: BaseModel

Result of cancelling a running turn continuation.

Attributes:

Name Type Description
thread_id str

Thread id for the cancelled turn.

turn_id str

Turn id that was cancelled.

steps list[ConversationStep]

Unread completed step objects accumulated since continuation cursor.

raw_events list[dict[str, Any]]

Unread raw events accumulated since continuation cursor.

was_completed bool

True if the turn was already completed when cancelling.

was_interrupted bool

True if an interrupt request was sent.

ChatContinuation

Bases: BaseModel

Opaque continuation token for resuming a timed-out running turn.

Attributes:

Name Type Description
thread_id str

Thread that owns the running turn.

turn_id str

Running turn identifier.

cursor int

Number of turn events already consumed by caller.

mode Literal['once', 'stream']

API mode that produced this continuation.

ChatResult

Bases: BaseModel

Buffered result for a single chat turn.

Attributes:

Name Type Description
thread_id str

Thread identifier used for the turn.

turn_id str

Turn identifier returned by server.

final_text str

Best-effort final assistant text assembled from events.

raw_events list[dict[str, Any]]

Raw JSON-RPC notifications consumed for the turn.

assistant_item_id str | None

Assistant item id used for final text when known.

completion_source Literal['item_completed', 'thread_read_fallback'] | None

Source used to determine final text.

CodexClient

High-level async client for Codex app-server.

__aenter__() async

Support async with CodexClient(...) usage.

__aexit__(exc_type, exc, tb) async

Close client on context-manager exit.

__init__(transport, *, request_timeout=30.0, inactivity_timeout=180.0, strict=False)

Create a client bound to a transport.

Parameters:

Name Type Description Default
transport Transport

Connected or connectable transport instance.

required
request_timeout float

Default timeout for request/response calls.

30.0
inactivity_timeout float | None

Turn inactivity timeout in seconds. If None, turn waits can run indefinitely until terminal events.

180.0
strict bool

If True, fail on certain protocol ambiguities.

False

approval_requests() async

Yield parsed approval requests from the server.

This stream is observational; automatic callback handling (or auto-decline default) still applies.

approve_approval(request, *, for_session=False, execpolicy_amendment=None) async

Convenience helper to approve an approval request.

archive_thread(thread_id) async

Archive a thread.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required

batch_write_config(edits, *, expected_version=None, file_path=None) async

Write multiple config edits atomically.

Parameters:

Name Type Description Default
edits Sequence[Mapping[str, Any]]

Sequence of edit payload objects.

required
expected_version str | None

Optional optimistic-lock version.

None
file_path str | None

Optional target config file path.

None

Returns:

Type Description
Any

Raw config/batchWrite response payload.

cancel(continuation, *, timeout=None) async

Interrupt a running turn and return unread data since continuation cursor.

Parameters:

Name Type Description Default
continuation ChatContinuation

Continuation token for the active turn session.

required
timeout float | None

Optional timeout for interrupt/drain wait. Defaults to client request timeout.

None

Returns:

Type Description
CancelResult

CancelResult containing unread steps/events and terminal flags.

Notes

Internal turn state is cleaned after cancel so the thread can be reused for new turns.

cancel_approval(request) async

Convenience helper to decline an approval request and cancel turn.

chat(text=None, thread_id=None, *, user=None, metadata=None, thread_config=None, turn_overrides=None, inactivity_timeout=None, continuation=None) async

Stream completed, non-delta conversation steps for one turn.

Parameters:

Name Type Description Default
text str | None

User text for a new turn. Must be omitted when resuming with continuation.

None
thread_id str | None

Existing thread id for the turn. If omitted, a new thread is started.

None
user str | None

Optional user label forwarded on turn/start.

None
metadata Mapping[str, Any] | None

Optional per-turn metadata forwarded on turn/start.

None
thread_config ThreadConfig | None

Optional thread-level overrides applied to thread start/resume context.

None
turn_overrides TurnOverrides | None

Optional per-turn override payload forwarded on turn/start.

None
inactivity_timeout float | None

Optional per-call inactivity timeout override in seconds. None uses client default; if resolved value is None, wait is unbounded by inactivity.

None
continuation ChatContinuation | None

Continuation token from CodexTurnInactiveError for resuming the same running turn.

None

Yields:

Type Description
AsyncIterator[ConversationStep]

Completed non-delta step blocks (ConversationStep), sourced from

AsyncIterator[ConversationStep]

live item/completed notifications.

Raises:

Type Description
ValueError

If required inputs are missing or continuation constraints are violated.

CodexTurnInactiveError

If no matching turn events arrive before timeout. Includes resumable continuation token.

CodexProtocolError

If turn fails.

CodexTransportError

If transport fails while receiving events.

Notes

Streaming is live-notification based and intentionally does not backfill from thread/read snapshots for the same turn.

When continuation is provided, text, thread_id, user, metadata, thread_config, and turn_overrides cannot be provided in the same call.

chat_once(text=None, thread_id=None, *, user=None, metadata=None, thread_config=None, turn_overrides=None, inactivity_timeout=None, continuation=None) async

Send one user message and wait for final assistant output.

Parameters:

Name Type Description Default
text str | None

User text for a new turn. Must be omitted when resuming with continuation.

None
thread_id str | None

Existing thread id for the turn. If omitted, a new thread is started.

None
user str | None

Optional user label forwarded on turn/start.

None
metadata Mapping[str, Any] | None

Optional per-turn metadata forwarded on turn/start.

None
thread_config ThreadConfig | None

Optional thread-level overrides applied to thread start/resume context.

None
turn_overrides TurnOverrides | None

Optional per-turn override payload forwarded on turn/start.

None
inactivity_timeout float | None

Optional per-call inactivity timeout override in seconds. None uses client default; if resolved value is None, wait is unbounded by inactivity.

None
continuation ChatContinuation | None

Continuation token from CodexTurnInactiveError for resuming the same running turn.

None

Returns:

Type Description
ChatResult

ChatResult with final assistant text and raw consumed events.

Raises:

Type Description
ValueError

If required inputs are missing or continuation constraints are violated.

CodexTurnInactiveError

If no matching turn events arrive before timeout. Includes resumable continuation token.

CodexProtocolError

If turn fails or completion cannot be resolved.

CodexTransportError

If transport fails while receiving events.

Notes

When continuation is provided, text, thread_id, user, metadata, thread_config, and turn_overrides cannot be provided in the same call.

close() async

Stop receiver, fail pending requests, clear turn state, and close transport.

compact_thread(thread_id) async

Start compaction for thread history.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required

Returns:

Type Description
Any

Raw thread/compact/start response payload.

connect_stdio(*, command=None, cwd=None, env=None, connect_timeout=30.0, request_timeout=30.0, inactivity_timeout=180.0, strict=False) classmethod

Create an unstarted client configured for stdio transport.

Parameters:

Name Type Description Default
command Sequence[str] | None

Optional command argv. Defaults to CODEX_APP_SERVER_CMD or ["codex", "app-server"].

None
cwd str | None

Optional subprocess working directory.

None
env Mapping[str, str] | None

Optional subprocess environment overrides.

None
connect_timeout float

Subprocess spawn timeout in seconds.

30.0
request_timeout float

Default request/response timeout in seconds.

30.0
inactivity_timeout float | None

Default turn inactivity timeout in seconds. If None, turn waits are unbounded by inactivity.

180.0
strict bool

Enable strict protocol behavior for ambiguous cases.

False

Returns:

Type Description
CodexClient

Unstarted CodexClient using StdioTransport.

connect_websocket(*, url=None, token=None, headers=None, connect_timeout=30.0, request_timeout=30.0, inactivity_timeout=180.0, strict=False) classmethod

Create an unstarted client configured for websocket transport.

Parameters:

Name Type Description Default
url str | None

Optional websocket URL. Defaults to CODEX_APP_SERVER_WS_URL or ws://127.0.0.1:8765.

None
token str | None

Optional bearer token. Defaults to CODEX_APP_SERVER_TOKEN.

None
headers Mapping[str, str] | None

Optional extra websocket headers.

None
connect_timeout float

Websocket handshake timeout in seconds.

30.0
request_timeout float

Default request/response timeout in seconds.

30.0
inactivity_timeout float | None

Default turn inactivity timeout in seconds. If None, turn waits are unbounded by inactivity.

180.0
strict bool

Enable strict protocol behavior for ambiguous cases.

False

Returns:

Type Description
CodexClient

Unstarted CodexClient using WebSocketTransport.

decline_approval(request) async

Convenience helper to decline an approval request and continue turn.

exec_command(command, *, cwd=None, sandbox_policy=None, timeout_ms=None) async

Execute one command through command/exec.

Parameters:

Name Type Description Default
command Sequence[str]

Command argv list.

required
cwd str | None

Optional command working directory.

None
sandbox_policy Mapping[str, Any] | None

Optional sandbox policy payload.

None
timeout_ms int | None

Optional command timeout in milliseconds.

None

Returns:

Type Description
Any

Raw command/exec response payload.

fork_thread(thread_id, *, overrides=None) async

Fork an existing thread and return a handle for the fork.

Parameters:

Name Type Description Default
thread_id str

Source thread id to fork from.

required
overrides ThreadConfig | None

Optional thread-level overrides for the forked thread.

None

Returns:

Type Description
ThreadHandle

ThreadHandle bound to forked thread id.

Raises:

Type Description
CodexProtocolError

If server response lacks forked thread id.

initialize(params=None, *, timeout=None) async

Perform initialize handshake and cache client initialization state.

This method is optional for normal chat usage because chat_once() and chat() initialize automatically on first use. Call it explicitly when you want to fail fast on handshake issues or inspect server protocol/capabilities metadata.

Parameters:

Name Type Description Default
params Mapping[str, Any] | None

Optional initialize request payload. The payload is merged with library defaults via _prepare_initialize_params(), including capability opt-out defaults when applicable.

None
timeout float | None

Optional per-request timeout override in seconds.

None

Returns:

Type Description
InitializeResult

Parsed initialize result containing normalized protocol/server fields

InitializeResult

and raw initialize payload.

interrupt_turn(turn_id, *, timeout=None) async

Send best-effort turn/interrupt for a running turn.

Parameters:

Name Type Description Default
turn_id str

Running turn id to interrupt.

required
timeout float | None

Optional per-request timeout override in seconds.

None

list_models(*, cursor=None, include_hidden=None, limit=None) async

List available models.

Parameters:

Name Type Description Default
cursor str | None

Optional pagination cursor.

None
include_hidden bool | None

Optional hidden-model inclusion flag.

None
limit int | None

Optional page size.

None

Returns:

Type Description
Any

Raw model/list response payload.

list_threads(*, archived=None, cursor=None, cwd=None, limit=None, model_providers=None, sort_key=None, sort_direction=None) async

List threads with optional filters and pagination.

Parameters:

Name Type Description Default
archived bool | None

Optional archived-state filter.

None
cursor str | None

Optional pagination cursor.

None
cwd str | None

Optional working-directory filter.

None
limit int | None

Optional page size.

None
model_providers Sequence[str] | None

Optional model provider filter list.

None
sort_key Literal['created_at', 'updated_at'] | None

Optional sort key (created_at or updated_at).

None
sort_direction Literal['asc', 'desc'] | None

Optional sort direction (asc or desc).

None

Returns:

Type Description
Any

Raw thread/list response payload.

read_config(*, cwd=None, include_layers=False) async

Read effective config and optional config layers.

Parameters:

Name Type Description Default
cwd str | None

Optional working directory used for config resolution.

None
include_layers bool

Include per-layer config data when true.

False

Returns:

Type Description
Any

Raw config/read response payload.

read_config_requirements() async

Read config requirements/constraints.

Returns:

Type Description
Any

Raw configRequirements/read response payload.

read_thread(thread_id, *, include_turns=True) async

Read server-side thread state.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
include_turns bool

Whether returned thread payload should include turns.

True

Returns:

Type Description
Any

Raw thread/read response payload.

request(method, params=None, *, timeout=None) async

Send one JSON-RPC request and return its result.

Parameters:

Name Type Description Default
method str

JSON-RPC method name.

required
params Mapping[str, Any] | None

Optional request parameters.

None
timeout float | None

Optional per-call timeout override in seconds. If omitted, client default request_timeout is used.

None

Returns:

Type Description
Any

JSON-RPC result payload.

Raises:

Type Description
CodexTransportError

If client is closed or transport fails.

CodexTimeoutError

If no response arrives within timeout.

CodexProtocolError

If response contains JSON-RPC error payload.

respond_approval(request, decision) async

Respond to one pending approval request.

resume_thread(thread_id, *, overrides=None) async

Resume an existing thread and return a bound handle.

Parameters:

Name Type Description Default
thread_id str

Existing thread id to resume.

required
overrides ThreadConfig | None

Optional thread-level overrides applied on resume.

None

Returns:

Type Description
ThreadHandle

ThreadHandle bound to resumed thread id.

rollback_thread(thread_id, *, num_turns) async

Drop the most recent turns from thread history.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
num_turns int

Number of latest turns to remove.

required

Returns:

Type Description
Any

Raw thread/rollback response payload.

set_approval_handler(handler)

Set or clear async handler for v2 approval requests.

The handler is invoked for: - item/commandExecution/requestApproval - item/fileChange/requestApproval

If no handler is configured, requests are auto-declined.

set_thread_defaults(thread_id, overrides) async

Apply thread-level defaults to an existing thread.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
overrides ThreadConfig

Thread-level fields applied through thread/resume.

required

set_thread_name(thread_id, name) async

Set user-facing thread name.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
name str

Thread display name.

required

start() async

Connect transport and start the background receiver loop.

Returns:

Type Description
CodexClient

self for fluent usage.

Raises:

Type Description
CodexTransportError

If client is closed or transport connection fails.

start_review(*, thread_id, target, delivery=None) async

Start review mode for a thread.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
target Mapping[str, Any]

Review target payload.

required
delivery Literal['inline', 'detached'] | None

Optional delivery mode (inline or detached).

None

Returns:

Type Description
Any

Raw review/start response payload.

start_thread(config=None) async

Create a new thread and return a bound handle.

Parameters:

Name Type Description Default
config ThreadConfig | None

Optional thread-level configuration for thread/start.

None

Returns:

Type Description
ThreadHandle

ThreadHandle bound to created thread id.

Raises:

Type Description
CodexProtocolError

If server response lacks thread id.

steer_turn(*, thread_id, expected_turn_id, input_items) async

Steer an active turn with additional input items.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required
expected_turn_id str

Running turn id expected by server.

required
input_items Sequence[Mapping[str, Any]]

Additional input items forwarded as input.

required

Returns:

Type Description
Any

Raw turn/steer response payload.

unarchive_thread(thread_id) async

Unarchive a thread.

Parameters:

Name Type Description Default
thread_id str

Target thread id.

required

write_config_value(*, key_path, value, merge_strategy='upsert', expected_version=None, file_path=None) async

Write one config key path.

Parameters:

Name Type Description Default
key_path str

Dot-path key to write.

required
value Any

Value to write.

required
merge_strategy Literal['replace', 'upsert']

Merge behavior (replace or upsert).

'upsert'
expected_version str | None

Optional optimistic-lock version.

None
file_path str | None

Optional target config file path.

None

Returns:

Type Description
Any

Raw config/value/write response payload.

CodexError

Bases: Exception

Base exception for the codex-app-server-sdk package.

CodexProtocolError

Bases: CodexError

Raised when JSON-RPC or app-server protocol reports an error.

__init__(message, *, code=None, data=None)

Create a protocol error.

Parameters:

Name Type Description Default
message str

Human-readable description.

required
code int | None

Optional JSON-RPC error code.

None
data Any

Optional protocol-provided error payload.

None

CodexTimeoutError

Bases: CodexError

Raised when a request or turn wait exceeds its timeout policy.

CodexTransportError

Bases: CodexError

Raised when the underlying transport fails or disconnects unexpectedly.

CodexTurnInactiveError

Bases: CodexTimeoutError

Raised when a running turn emits no matching events for too long.

Attributes:

Name Type Description
continuation

Opaque token used to resume the same running turn.

idle_seconds

Resolved inactivity timeout that triggered this exception.

__init__(message, *, continuation, idle_seconds)

Create a turn inactivity timeout error.

Parameters:

Name Type Description Default
message str

Human-readable timeout description.

required
continuation ChatContinuation

Continuation token for resuming interrupted wait.

required
idle_seconds float

Timeout value in seconds that was exceeded.

required

CommandApprovalRequest dataclass

Server-initiated approval request for one command execution item.

CommandApprovalWithExecpolicyAmendment dataclass

Approval decision carrying an execpolicy amendment prefix rule.

ConversationStep

Bases: BaseModel

A completed, non-delta conversation step emitted during a turn.

Attributes:

Name Type Description
thread_id str

Parent thread identifier.

turn_id str

Parent turn identifier.

item_id str | None

Underlying item identifier when provided.

step_type str

Canonical label for UI/clients (e.g. thinking/exec/codex).

item_type str | None

Raw protocol item type (e.g. reasoning/commandExecution/agentMessage).

status Literal['completed']

Step lifecycle status for this event.

text str | None

Human-readable text for the step when available.

data dict[str, Any]

Full item payload and metadata for advanced consumers.

FileChangeApprovalRequest dataclass

Server-initiated approval request for one file-change item.

InitializeResult

Bases: BaseModel

Parsed result for the initialize handshake response.

Attributes:

Name Type Description
protocol_version str | None

Protocol version echoed by server, if present.

server_info dict[str, Any] | None

Optional server identity/details object.

capabilities dict[str, Any] | None

Optional capability map returned by server.

raw dict[str, Any]

Full raw initialize result payload.

ThreadConfig dataclass

Thread-level configuration overrides used by thread start/resume/fork calls.

Use UNSET (default) to omit a field from the request payload. Use None to explicitly send JSON null where the protocol accepts it.

Attributes:

Name Type Description
cwd str | None | UnsetType

Thread working directory.

base_instructions str | None | UnsetType

Base instruction text for the thread.

developer_instructions str | None | UnsetType

Developer instruction text for the thread.

model str | None | UnsetType

Model id for thread-level default model selection.

model_provider str | None | UnsetType

Optional model provider name/identifier.

approval_policy ApprovalPolicy | None | UnsetType

Approval policy mode (untrusted, on-failure, on-request, never).

sandbox SandboxMode | None | UnsetType

Sandbox mode selector accepted by the server (read-only, workspace-write, danger-full-access).

personality str | None | UnsetType

Optional personality profile name.

ephemeral bool | None | UnsetType

Optional ephemeral-thread flag.

config dict[str, Any] | None | UnsetType

Optional thread-level config map forwarded to the server.

ThreadHandle

Thread-scoped high-level API wrapper bound to one thread_id.

defaults property

Current local default configuration snapshot for this thread handle.

thread_id property

Thread id for this handle.

archive() async

Archive this thread via thread/archive.

chat(text=None, *, user=None, metadata=None, inactivity_timeout=None, continuation=None, turn_overrides=None) async

Stream completed, non-delta steps for one message on this bound thread.

Parameters:

Name Type Description Default
text str | None

User text for a new turn. Must be omitted when resuming with continuation.

None
user str | None

Optional user label forwarded on turn/start.

None
metadata Mapping[str, Any] | None

Optional per-turn metadata forwarded on turn/start.

None
inactivity_timeout float | None

Optional per-call inactivity timeout override. None uses the client-level inactivity timeout policy.

None
continuation ChatContinuation | None

Continuation token from CodexTurnInactiveError for resuming the same running turn.

None
turn_overrides TurnOverrides | None

Optional per-turn override payload for turn/start.

None

Yields:

Type Description
AsyncIterator[ConversationStep]

Completed conversation step blocks as they arrive.

Raises:

Type Description
ValueError

If continuation constraints are violated.

CodexTurnInactiveError

If the turn remains inactive longer than the resolved inactivity timeout.

CodexProtocolError

If protocol/server reports turn failure.

CodexTransportError

If transport fails while waiting for turn events.

Notes

When continuation is provided, text, user, metadata, and turn_overrides cannot be provided in the same call.

chat_once(text=None, *, user=None, metadata=None, inactivity_timeout=None, continuation=None, turn_overrides=None) async

Send one message on this bound thread and return the final assistant output.

Parameters:

Name Type Description Default
text str | None

User text for a new turn. Must be omitted when resuming with continuation.

None
user str | None

Optional user label forwarded on turn/start.

None
metadata Mapping[str, Any] | None

Optional per-turn metadata forwarded on turn/start.

None
inactivity_timeout float | None

Optional per-call inactivity timeout override. None uses the client-level inactivity timeout policy.

None
continuation ChatContinuation | None

Continuation token from CodexTurnInactiveError for resuming the same running turn.

None
turn_overrides TurnOverrides | None

Optional per-turn override payload for turn/start.

None

Returns:

Type Description
ChatResult

Buffered final turn result for this thread.

Raises:

Type Description
ValueError

If continuation constraints are violated.

CodexTurnInactiveError

If the turn remains inactive longer than the resolved inactivity timeout.

CodexProtocolError

If protocol/server reports turn failure.

CodexTransportError

If transport fails while waiting for turn events.

Notes

When continuation is provided, text, user, metadata, and turn_overrides cannot be provided in the same call.

compact() async

Start context compaction for this thread.

Returns:

Type Description
Any

Raw thread/compact/start response payload.

fork(*, overrides=None) async

Fork this thread into a new thread handle.

Parameters:

Name Type Description Default
overrides ThreadConfig | None

Optional thread-level overrides applied to the forked thread.

None

Returns:

Type Description
ThreadHandle

New ThreadHandle bound to the forked thread id.

read(*, include_turns=True) async

Read server-side thread state for this handle's thread.

Parameters:

Name Type Description Default
include_turns bool

Whether response should include turn history.

True

Returns:

Type Description
Any

Raw thread/read response payload.

rollback(num_turns) async

Rollback the last turns for this thread.

Parameters:

Name Type Description Default
num_turns int

Number of most recent turns to drop.

required

Returns:

Type Description
Any

Raw thread/rollback response payload.

set_name(name) async

Set user-facing name for this thread.

Parameters:

Name Type Description Default
name str

Thread display name.

required

start_review(target, *, delivery=None) async

Start review mode against this thread.

Parameters:

Name Type Description Default
target Mapping[str, Any]

Review target payload accepted by review/start.

required
delivery Literal['inline', 'detached'] | None

Optional review delivery mode.

None

Returns:

Type Description
Any

Raw review/start response payload.

unarchive() async

Unarchive this thread via thread/unarchive.

update_defaults(overrides) async

Apply thread-level defaults and update this handle's local snapshot.

Parameters:

Name Type Description Default
overrides ThreadConfig

Thread-level fields to apply via thread/resume.

required

TurnOverrides dataclass

Per-turn override fields forwarded to turn/start.

Use UNSET (default) to omit a field from the request payload. Use None to explicitly send JSON null where the protocol accepts it.

Attributes:

Name Type Description
cwd str | None | UnsetType

Per-turn working directory override.

model str | None | UnsetType

Per-turn model override.

effort ReasoningEffort | None | UnsetType

Reasoning effort level (none..xhigh).

summary ReasoningSummary | None | UnsetType

Reasoning summary verbosity (auto, concise, detailed, none).

sandbox_policy SandboxPolicy | dict[str, Any] | None | UnsetType

Per-turn sandbox policy payload.

personality str | None | UnsetType

Per-turn personality override.

approval_policy ApprovalPolicy | None | UnsetType

Per-turn approval policy override.

output_schema dict[str, Any] | None | UnsetType

Optional structured-output schema override.