Upgrading to 0.4.0? Behavior changes require review. Read the
0.3.2 → 0.4.0 migration guide
before upgrading.
Stream-based approval responders must set approval_mode="manual".
Failed/interrupted turns now raise; cancellation, initialization, unanswered
user questions, and custom transport expectations also change.
Highlights
simple one-shot turns with chat_once(...)
step-streaming turns with chat(...) (thinking, exec, codex, etc.), non-delta
built-in thread/turn lifecycle handling
thread-scoped config + forking via ThreadHandle
inactivity timeout continuation for long-running turns
turn cancellation with unread-step/event drain via cancel(...)
collaboration mode overrides (default/plan) via TurnOverrides
human-in-the-loop user input handling (item/tool/requestUserInput)
optional low-level request(...) access when needed
Why use this client?
Protocol I/O and callbacks run directly on your application's asyncio event
loop, using asynchronous subprocess pipes or WebSockets. Thread handles share
one connection, and approvals can integrate with an async callback or a manual
UI response loop.
You control the Codex runtime: launch your chosen executable or connect to an
existing WebSocket server. The conversation API adds completed-step streaming,
resumable inactivity timeouts, and cancellation with unread-event recovery.
The Transport interface and raw request(...) method remain available for
application-specific integrations.
Compared with openai-codex
Both libraries use the Codex app-server protocol. Their integration choices differ:
Area
codex-app-server-sdk
openai-codex
Execution
Native asyncio client; asynchronous protocol I/O on your event loop
Synchronous client with an async wrapper that offloads blocking operations to background threads
Transport
Public, replaceable Transport; built-in stdio and WebSocket support
SDK-managed subprocess communicating through line-delimited JSON over stdio
Protocol access
Flexible dictionary-based RPC via request(...), plus high-level conversation models
Extensive generated types, typed responses, and typed notifications
Runtime management
You supply and manage Codex; choose an executable or connect to an existing WebSocket server
Installs an exactly pinned Codex runtime dependency by default
This client fits applications that need native async I/O, custom transports,
connections to an existing server, or independent control over runtime upgrades.
The official SDK offers broader generated type coverage and a reproducible
runtime default. You are responsible for installing and updating Codex when
using this client.
Release notes and migration guidance: CHANGELOG.md
Quick start
Stdio
import asyncio
from codex_app_server_sdk import CodexClient
async def main() -> None:
async with CodexClient.connect_stdio() as client:
result = await client.chat_once("Hello from Python")
print(result.final_text)
asyncio.run(main())
By default, stdio transport runs:
command: codex app-server
You can override via:
connect_stdio(command=[...])
environment variable: CODEX_APP_SERVER_CMD
Websocket
import asyncio
from codex_app_server_sdk import CodexClient
async def main() -> None:
async with CodexClient.connect_websocket() as client:
result = await client.chat_once("Hello over websocket")
print(result.final_text)
asyncio.run(main())
Websocket defaults:
URL: CODEX_APP_SERVER_WS_URL or ws://127.0.0.1:8765
Bearer token: CODEX_APP_SERVER_TOKEN (optional)
Continuation on inactivity timeout
Both high-level APIs support resuming the same running turn.
import asyncio
from codex_app_server_sdk import CodexClient, CodexTurnInactiveError
async def main() -> None:
async with CodexClient.connect_stdio(inactivity_timeout=120.0) as client:
continuation = None
while True:
try:
if continuation is None:
result = await client.chat_once("Do a longer task")
else:
result = await client.chat_once(continuation=continuation)
print(result.final_text)
break
except CodexTurnInactiveError as exc:
continuation = exc.continuation
idle = (
f"{exc.idle_seconds:.1f}s"
if exc.idle_seconds is not None
else "unknown"
)
print(
f"[warn] turn inactive for {idle}; resuming "
f"(thread_id={continuation.thread_id}, turn_id={continuation.turn_id})"
)
asyncio.run(main())
Advanced thread control (cwd/instructions/model/fork)
Use explicit thread handles when you need thread-scoped configuration.
import asyncio
from codex_app_server_sdk import CodexClient, ThreadConfig, TurnOverrides
async def main() -> None:
async with CodexClient.connect_stdio() as client:
thread = await client.start_thread(
ThreadConfig(
cwd="/home/me/project",
base_instructions="You are concise.",
developer_instructions="Prefer rg over grep.",
model="gpt-5",
)
)
result = await thread.chat_once("Summarize the repo layout.")
print(result.final_text)
await thread.update_defaults(ThreadConfig(model="gpt-5.1-codex-mini"))
forked = await thread.fork(
overrides=ThreadConfig(
developer_instructions="Focus on tests first.",
)
)
async for step in forked.chat(
"Run a quick diagnostics pass.",
turn_overrides=TurnOverrides(effort="low"),
):
print(step.step_type, step.text)
asyncio.run(main())
When resuming with continuation=..., do not pass extra turn-start arguments in
that same call. Specifically, do not pass: text, thread_id, user,
metadata, thread_config, or turn_overrides.
Apply thread changes via thread.update_defaults(...) or start a new/forked thread before continuing with a new turn.
Example clients
More complete examples are under examples/.
All thread_* examples print lifecycle progress checkpoints by default so long operations are visible.
Use --quiet on those scripts for minimal output.
Rich step-stream example (thinking/exec/codex blocks)
Recommended example for step-oriented API and continuation behavior.
Stdio:
uv run python examples/chat_steps_rich.py
Websocket:
uv run python examples/chat_steps_rich.py --transport websocket --url ws://127.0.0.1:8765
With extra payload summaries:
uv run python examples/chat_steps_rich.py --show-data
Cancel timed-out turns instead of auto-resume:
uv run python examples/chat_steps_rich.py --cancel-on-timeout
uv run python examples/thread_config_and_fork.py \
--transport websocket \
--url ws://127.0.0.1:8765
Quiet mode:
uv run python examples/thread_config_and_fork.py --quiet
Resume-by-id example
uv run python examples/thread_resume_by_id.py \
--transport stdio \
--thread-id <existing-thread-id> \
--prompt "Continue the previous conversation."
Quiet mode:
uv run python examples/thread_resume_by_id.py --thread-id <existing-thread-id> --quiet
Concurrent thread handles example
This example starts two new threads and runs turns concurrently on those fresh
ThreadHandles over one shared client connection (it does not call
thread/resume for the newly started threads).
uv run python examples/thread_concurrent_handles.py --transport stdio
Quiet mode:
uv run python examples/thread_concurrent_handles.py --quiet
chat_once(...) (text=None, thread_id=None, user=None, metadata=None, thread_config=None, turn_overrides=None, inactivity_timeout=None, continuation=None): send one user message and wait for completed turn.
cancel(continuation, timeout=None): interrupt a turn and return unread steps/events after terminal confirmation; retain the continuation if cancellation fails or times out.
steer_turn(thread_id=..., expected_turn_id=..., input_items=...): steer active turn input.
start_review(thread_id=..., target=..., delivery=None): run review mode.
list_models(...): discover available models.
exec_command(command, ...): run one command via server command API.
CodexTimeoutError: request timeout (and base for timeout-related flow).
CodexTurnInactiveError: per-turn inactivity timeout with resumable continuation.
CodexProtocolError: protocol/JSON-RPC error (optional code and data).
Behavior notes
This version does not expose token-delta streaming as a public API.
chat(...) provides async streaming of completed step blocks (non-delta) from live item/completed notifications only.
chat(...) intentionally does not merge thread/read snapshot items for the same turn, avoiding duplicate blocks when snapshot item IDs differ from live event item IDs.
chat_once(...) resolves final text from completed agentMessage items (item/completed), with thread/read(includeTurns=true) fallback.
turn_timeout is intentionally removed to avoid conflicting timeout semantics.
Turn waits are controlled by inactivity_timeout (or unbounded when None).
cancel(...) releases turn state only after a terminal event. RPC failures propagate; a confirmation timeout raises CodexTurnInactiveError with the original continuation.
Failed or interrupted turns raise CodexProtocolError from both chat APIs, even if partial assistant text was received.
Use approval_mode="manual" on either connection factory to answer approval_requests() yourself. Without a callback, the default "auto" mode declines requests.
Advanced thread-level config/fork uses protocol v2 methods (thread/start, thread/resume, thread/fork) exposed via ThreadHandle and ThreadConfig.
metadata is applied on turn/start payloads for message turns; thread-level config uses schema-aligned fields on thread methods.
preferred lifecycle is async with CodexClient.connect_*() as client:; manual start()/close() remains available for advanced control.
The client uses modern thread/turn methods (thread/start, thread/resume, turn/start, turn/interrupt).
initialize currently sends protocolVersion: "1" as handshake metadata.
Websocket transport targets websockets (>=16,<17), uses additional_headers, and disables compression by default (compression=None) for codex app-server compatibility.
After dependency changes, run uv sync to refresh the virtual environment.
Initialize handshake (initialize())
initialize() performs the protocol handshake and returns InitializeResult.
chat_once(...) and chat(...) call initialize() automatically on first use.
call initialize() explicitly when you want to fail fast before first turn, inspect server metadata, or send custom init params.
Default initialize payload
When params=None, the client sends the following payload. The version
placeholder is replaced with the installed package version, also available as
codex_app_server_sdk.__version__: