Skip to content

codex_app_server_sdk.client

client

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, user_input_response_timeout=300.0, approval_mode=_APPROVAL_AUTO_MODE, strict=False)

Create a client bound to a transport.

:param transport: Connected or connectable transport instance. :param request_timeout: Default request/response timeout in seconds. :param inactivity_timeout: Turn inactivity timeout; None disables it. :param user_input_response_timeout: Timeout for unanswered user-input requests without a callback; None disables it. :param approval_mode: Without a callback, auto declines approvals and manual keeps them pending for explicit responses. :param strict: Enable strict handling of protocol ambiguities. :return: None.

approval_requests() async

Yield parsed approval requests from the server.

Use approval_mode="manual" without a callback for manual responses. Otherwise the stream observes callback handling or automatic decline.

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 turn and release its state only after terminal confirmation.

RPC failures propagate and leave the continuation usable. If no terminal event arrives within the drain timeout, CodexTurnInactiveError retains the original unread cursor so callers can resume or retry cancellation.

:param continuation: Token for a turn retained by this client. :param timeout: Interrupt RPC and subsequent drain timeout in seconds; defaults to the client's request timeout. :return: Unread events/steps and observed completion flags. :raises CodexProtocolError: If the token is invalid or interruption fails. :raises CodexTurnInactiveError: If terminal confirmation times out.

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, user_input_response_timeout=300.0, approval_mode=_APPROVAL_AUTO_MODE, strict=False) classmethod

Create an unstarted client using asynchronous subprocess pipes.

:param command: Server argv; defaults to CODEX_APP_SERVER_CMD or ["codex", "app-server"]. :param cwd: Optional subprocess working directory. :param env: Optional subprocess environment. :param connect_timeout: Subprocess spawn timeout in seconds. :param request_timeout: Default request/response timeout in seconds. :param inactivity_timeout: Turn inactivity timeout; None disables it. :param user_input_response_timeout: Timeout for unanswered user-input requests without a callback; None disables it. :param approval_mode: Without a callback, auto declines approvals and manual waits for explicit responses. :param strict: Enable strict handling of protocol ambiguities. :return: Unstarted client using StdioTransport.

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

Create an unstarted client using asynchronous WebSocket I/O.

:param url: Endpoint; defaults to CODEX_APP_SERVER_WS_URL or ws://127.0.0.1:8765. :param token: Bearer token; defaults to CODEX_APP_SERVER_TOKEN. :param headers: Optional additional handshake headers. :param connect_timeout: WebSocket connection timeout in seconds. :param request_timeout: Default request/response timeout in seconds. :param inactivity_timeout: Turn inactivity timeout; None disables it. :param user_input_response_timeout: Timeout for unanswered user-input requests without a callback; None disables it. :param approval_mode: Without a callback, auto declines approvals and manual waits for explicit responses. :param strict: Enable strict handling of protocol ambiguities. :return: Unstarted client 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

Initialize once per connection, including concurrent first calls.

Send initialize followed by initialized. Subsequent calls return the cached result; parameters from the first successful call take effect. The high-level chat and thread-creation methods call this automatically.

:param params: Optional payload merged with library defaults. :param timeout: Optional request timeout in seconds. :return: Parsed and raw initialization result.

interrupt_turn(turn_id, *, thread_id=None, timeout=None) async

Request interruption using both required wire identifiers.

An acknowledged request does not confirm terminal completion; use cancel() when the SDK owns a continuation and must drain the turn.

:param turn_id: Running turn to interrupt. :param thread_id: Owning thread, inferred for turns tracked by this client. Required for turns started through low-level requests. :param timeout: Optional request timeout in seconds. :return: None after the server acknowledges the interrupt request. :raises ValueError: If the thread is unknown or conflicts with local state.

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.

respond_user_input(request, response) async

Respond to one pending user-input request.

Parameters:

Name Type Description Default
request UserInputRequest

Original pending request object.

required
response UserInputResponse

Response payload mapping question ids to answers.

required

Raises:

Type Description
CodexProtocolError

If request is no longer pending or mismatched.

respond_user_input_choice(request, *, question_id, selections) async

Respond with selected choices for one question id.

Parameters:

Name Type Description Default
request UserInputRequest

Original pending request object.

required
question_id str

Question identifier from request.questions.

required
selections Sequence[str]

Selected option labels/values.

required

respond_user_input_other(request, *, question_id, freeform) async

Respond with a freeform answer for one question id.

Parameters:

Name Type Description Default
request UserInputRequest

Original pending request object.

required
question_id str

Question identifier from request.questions.

required
freeform str

Freeform answer text.

required

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

Without a handler, approval_mode="auto" declines requests and approval_mode="manual" keeps them pending for explicit responses.

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

set_user_input_handler(handler)

Set or clear async handler for item/tool/requestUserInput.

Parameters:

Name Type Description Default
handler Callable[[UserInputRequest], Awaitable[UserInputResponse]] | None

Async callback that receives one UserInputRequest and returns a UserInputResponse. Set to None to disable callback handling.

required
Notes

If no callback is configured, requests remain available via user_input_requests(). Unanswered requests are auto-failed after user_input_response_timeout (or never when disabled).

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

user_input_requests() async

Yield parsed user-input requests from the server.

Yields:

Type Description
AsyncIterator[UserInputRequest]

Parsed UserInputRequest objects from

AsyncIterator[UserInputRequest]

item/tool/requestUserInput server requests.

Notes

This stream is observational. Callback handling via set_user_input_handler(...) still runs when configured.

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.

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