Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Add internal Codex Direct app-server transport foundation (#1645)

Ali Khokhar96495b970146
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 3b099b3a..dd7c3054 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -1364,6 +1364,57 @@ client environment.
Codex surface one credential owner instead of competing with Codex's signed-in
OpenAI authorization.
+[application/work/codex.py](src/free_claude_code/application/work/codex.py)
+defines the concrete Codex Direct port and values for the future Work
+application. It deliberately preserves Codex-native thread, turn, control,
+notification, and server-request identities instead of introducing a generic
+harness abstraction before a second rich harness contract exists.
+
+[runtime/codex_app_server.py](src/free_claude_code/runtime/codex_app_server.py)
+implements that port over Codex's supported `app-server --stdio` JSONL
+interface:
+
+- One application-owned child starts lazily and performs the required
+ `initialize`/`initialized` handshake. Response correlation records the
+ successful `initialize` reply immediately, while app-server requests and
+ notifications buffered behind that reply wait until `initialized` has
+ drained and the same connection is ready. The child then supports concurrent
+ native threads through serialized writes and correlated out-of-order
+ responses. Concurrent first callers share one shielded startup task, so
+ cancelling one waiter does not cancel the application-owned child.
+- The child reuses the exact ephemeral FCC provider, command-backed proxy auth,
+ generated model catalog, credential scrubbing, `CODEX_HOME`, and loopback
+ bypass assembled by `fcc-codex`; synchronous catalog discovery runs outside
+ the event loop.
+- A bounded single-consumer event stream carries native notifications and the
+ supported interactive server requests without interpreting them as Work
+ state. A connection-scoped ledger recognizes Codex's identical replay of an
+ unanswered request, and interactive responses commit exactly once at the
+ serialized subprocess write boundary. Codex clears either pending or
+ committed lifecycle state through `serverRequest/resolved`; that control
+ notification retires wire-response admission before remaining observable to
+ the future Work application.
+ `currentTime/read` is answered locally; unnegotiated server methods receive
+ method-not-found and emit a bounded unsupported-interaction event rather than
+ hanging the child or guessing a response.
+- Model, permission-profile, collaboration-mode, and config catalogs degrade
+ independently when an installed Codex version lacks one discovery method.
+ Required thread and turn methods remain actionable compatibility failures.
+- Unknown notification methods and complete notification params payloads are
+ preserved. Malformed or oversized protocol data and event overflow fail one
+ connection generation visibly, and a later operation may start a clean child.
+ Submitted turns are never replayed after an uncertain failure because that
+ could duplicate commands or edits.
+- One explicit starting/ready/closing/closed lifecycle owns startup and cleanup.
+ Shutdown closes stdin first, then terminates and kills only if the child does
+ not exit. All response futures and stdio readers remain owned until cleanup is
+ complete, including on Windows; an unreaped generation blocks an unsafe
+ replacement child.
+
+This boundary has no HTTP route, persistence, or visible Work UI yet. Those
+belong to later Work application and adapter changes; the existing Chat product
+does not depend on this Codex-specific transport.
+
[cli/launchers/model_catalog.py](src/free_claude_code/cli/launchers/model_catalog.py)
consumes the direct Responses view, validates its nested `provider/model`
references, and is shared by Codex, OpenCode, Cline, Hermes, DeepSeek Harness,
diff --git a/pyproject.toml b/pyproject.toml
index 3d3dc17d..a27f6a0a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "5.19.0"
+version = "5.19.1"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/src/free_claude_code/application/work/__init__.py b/src/free_claude_code/application/work/__init__.py
new file mode 100644
index 00000000..1dc5be2e
--- /dev/null
+++ b/src/free_claude_code/application/work/__init__.py
@@ -0,0 +1,47 @@
+"""Codex Direct boundary for the future Work application."""
+
+from .codex import (
+ CodexAppServerEvent,
+ CodexAppServerPort,
+ CodexAvailability,
+ CodexCompatibilityError,
+ CodexConnectionError,
+ CodexConnectionLost,
+ CodexControlCatalog,
+ CodexDirectError,
+ CodexInitialization,
+ CodexNotification,
+ CodexProtocolError,
+ CodexRequestError,
+ CodexRequestId,
+ CodexServerRequest,
+ CodexThreadHandle,
+ CodexThreadSettings,
+ CodexTurnHandle,
+ CodexTurnSettings,
+ CodexUnavailableError,
+ CodexUnsupportedInteraction,
+)
+
+__all__ = [
+ "CodexAppServerEvent",
+ "CodexAppServerPort",
+ "CodexAvailability",
+ "CodexCompatibilityError",
+ "CodexConnectionError",
+ "CodexConnectionLost",
+ "CodexControlCatalog",
+ "CodexDirectError",
+ "CodexInitialization",
+ "CodexNotification",
+ "CodexProtocolError",
+ "CodexRequestError",
+ "CodexRequestId",
+ "CodexServerRequest",
+ "CodexThreadHandle",
+ "CodexThreadSettings",
+ "CodexTurnHandle",
+ "CodexTurnSettings",
+ "CodexUnavailableError",
+ "CodexUnsupportedInteraction",
+]
diff --git a/src/free_claude_code/application/work/codex.py b/src/free_claude_code/application/work/codex.py
new file mode 100644
index 00000000..c48a1c9b
--- /dev/null
+++ b/src/free_claude_code/application/work/codex.py
@@ -0,0 +1,196 @@
+"""Concrete application-facing contract for Codex Direct mode."""
+
+from collections.abc import AsyncIterator
+from dataclasses import dataclass
+from typing import Protocol
+
+from free_claude_code.core.json_types import JsonObject, JsonValue
+
+type CodexRequestId = int | str
+type CodexApprovalPolicy = str | JsonObject
+
+
+@dataclass(frozen=True, slots=True)
+class CodexAvailability:
+ """Installed Codex availability without starting its app-server."""
+
+ available: bool
+ binary_path: str | None
+ version: str | None
+ reason: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class CodexInitialization:
+ """Connection metadata returned by the app-server handshake."""
+
+ connection_id: str
+ user_agent: str
+ codex_home: str
+ platform_family: str
+ platform_os: str
+
+
+@dataclass(frozen=True, slots=True)
+class CodexControlCatalog:
+ """Native controls exposed by the installed Codex version."""
+
+ models: tuple[JsonObject, ...] | None
+ collaboration_modes: tuple[JsonObject, ...] | None
+ permission_profiles: tuple[JsonObject, ...] | None
+ config: JsonObject | None
+
+
+@dataclass(frozen=True, slots=True)
+class CodexThreadSettings:
+ """Codex-native settings applied when a thread is started or resumed."""
+
+ cwd: str
+ model: str | None = None
+ approval_policy: CodexApprovalPolicy | None = None
+ permission_profile: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class CodexTurnSettings:
+ """Codex-native settings that may be changed between turns."""
+
+ model: str | None = None
+ effort: str | None = None
+ collaboration_mode: JsonObject | None = None
+ approval_policy: CodexApprovalPolicy | None = None
+ permission_profile: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class CodexThreadHandle:
+ """Native thread identity plus the complete start/resume response."""
+
+ connection_id: str
+ thread_id: str
+ response: JsonObject
+
+
+@dataclass(frozen=True, slots=True)
+class CodexTurnHandle:
+ """Native turn identity plus the complete start response."""
+
+ connection_id: str
+ thread_id: str
+ turn_id: str
+ response: JsonObject
+
+
+@dataclass(frozen=True, slots=True)
+class CodexNotification:
+ """A native Codex notification with its complete params payload."""
+
+ connection_id: str
+ method: str
+ params: JsonValue
+
+
+@dataclass(frozen=True, slots=True)
+class CodexServerRequest:
+ """An interactive app-server request that requires a client response."""
+
+ connection_id: str
+ request_id: CodexRequestId
+ method: str
+ params: JsonValue
+
+
+@dataclass(frozen=True, slots=True)
+class CodexConnectionLost:
+ """Terminal event for one app-server connection generation."""
+
+ connection_id: str
+ message: str
+
+
+@dataclass(frozen=True, slots=True)
+class CodexUnsupportedInteraction:
+ """A server request whose response contract FCC does not implement."""
+
+ connection_id: str
+ method: str
+
+
+type CodexAppServerEvent = (
+ CodexNotification
+ | CodexServerRequest
+ | CodexUnsupportedInteraction
+ | CodexConnectionLost
+)
+
+
+class CodexDirectError(Exception):
+ """Base class for the concrete Codex Direct boundary."""
+
+
+class CodexUnavailableError(CodexDirectError):
+ """Codex is missing, closed, or cannot be launched."""
+
+
+class CodexCompatibilityError(CodexDirectError):
+ """The installed Codex lacks a required app-server contract."""
+
+
+class CodexProtocolError(CodexDirectError):
+ """The child emitted malformed or invalid protocol data."""
+
+
+class CodexConnectionError(CodexDirectError):
+ """The app-server connection ended before an operation completed."""
+
+
+class CodexRequestError(CodexDirectError):
+ """Codex rejected one otherwise valid app-server request."""
+
+ def __init__(self, *, method: str, code: int, message: str) -> None:
+ super().__init__(f"Codex {method} failed ({code}): {message}")
+ self.method = method
+ self.code = code
+ self.message = message
+
+
+class CodexAppServerPort(Protocol):
+ """Native Codex operations required by the future Work application."""
+
+ async def availability(self) -> CodexAvailability: ...
+
+ async def initialize(self) -> CodexInitialization: ...
+
+ async def controls(self, *, cwd: str) -> CodexControlCatalog: ...
+
+ async def start_thread(
+ self, settings: CodexThreadSettings
+ ) -> CodexThreadHandle: ...
+
+ async def resume_thread(
+ self, thread_id: str, settings: CodexThreadSettings
+ ) -> CodexThreadHandle: ...
+
+ async def delete_thread(self, thread_id: str) -> None: ...
+
+ async def start_turn(
+ self,
+ *,
+ thread_id: str,
+ text: str,
+ settings: CodexTurnSettings,
+ ) -> CodexTurnHandle: ...
+
+ async def interrupt_turn(self, *, thread_id: str, turn_id: str) -> None: ...
+
+ async def respond(
+ self,
+ *,
+ connection_id: str,
+ request_id: CodexRequestId,
+ result: JsonValue,
+ ) -> None: ...
+
+ def events(self) -> AsyncIterator[CodexAppServerEvent]: ...
+
+ async def close(self) -> None: ...
diff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.py
index ecaaa6eb..4bf7b555 100644
--- a/src/free_claude_code/cli/launchers/codex.py
+++ b/src/free_claude_code/cli/launchers/codex.py
@@ -71,19 +71,18 @@ def launch(argv: Sequence[str] | None = None) -> None:
install_hint=_INSTALL_HINT,
)
catalog = codex_model_catalog_plan(proxy_root_url, settings)
+ plan = build_codex_launcher_plan(
+ binary_path=binary_path,
+ argv=args,
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ catalog_config_args=catalog.config_args,
+ catalog_models=catalog.models,
+ base_env=os.environ,
+ )
run_client_process(
- command=build_codex_launcher_command(
- binary_path=binary_path,
- argv=args,
- settings=settings,
- proxy_root_url=proxy_root_url,
- catalog_config_args=catalog.config_args,
- catalog_models=catalog.models,
- ),
- env=build_codex_launcher_env(
- proxy_root_url=proxy_root_url,
- base_env=os.environ,
- ),
+ command=list(plan.command),
+ env=plan.env,
binary_name=binary_name,
display_name=_DISPLAY_NAME,
install_hint=_INSTALL_HINT,
@@ -98,12 +97,50 @@ class CodexModelCatalogPlan:
models: tuple[ClientModel, ...] = ()
+@dataclass(frozen=True, slots=True)
+class CodexLauncherPlan:
+ """One process invocation configured to route Codex through FCC."""
+
+ command: tuple[str, ...]
+ env: dict[str, str]
+
+
def codex_binary_name() -> str:
"""Return the Codex CLI binary name."""
return _DEFAULT_BINARY
+def build_codex_launcher_plan(
+ *,
+ binary_path: str,
+ argv: Sequence[str],
+ settings: Settings,
+ proxy_root_url: str,
+ catalog_config_args: Sequence[str] = (),
+ catalog_models: Sequence[ClientModel] = (),
+ base_env: Mapping[str, str],
+) -> CodexLauncherPlan:
+ """Return the complete process plan shared by CLI and Direct mode."""
+
+ return CodexLauncherPlan(
+ command=tuple(
+ build_codex_launcher_command(
+ binary_path=binary_path,
+ argv=argv,
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ catalog_config_args=catalog_config_args,
+ catalog_models=catalog_models,
+ )
+ ),
+ env=build_codex_launcher_env(
+ proxy_root_url=proxy_root_url,
+ base_env=base_env,
+ ),
+ )
+
+
def build_codex_launcher_command(
*,
binary_path: str,
diff --git a/src/free_claude_code/cli/process_registry.py b/src/free_claude_code/cli/process_registry.py
index 3b289641..481f84f8 100644
--- a/src/free_claude_code/cli/process_registry.py
+++ b/src/free_claude_code/cli/process_registry.py
@@ -42,7 +42,11 @@ def unregister_pid(pid: int) -> None:
_pids.discard(int(pid))
-def kill_pid_tree_best_effort(pid: int) -> None:
+def kill_pid_tree_best_effort(
+ pid: int,
+ *,
+ timeout_seconds: float | None = None,
+) -> None:
"""Kill a tracked process and its children where the platform supports it."""
if not pid:
return
@@ -54,6 +58,7 @@ def kill_pid_tree_best_effort(pid: int) -> None:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
+ timeout=timeout_seconds,
)
except Exception as e:
logger.debug("process_registry: taskkill failed pid=%s: %s", pid, e)
diff --git a/src/free_claude_code/runtime/codex_app_server.py b/src/free_claude_code/runtime/codex_app_server.py
new file mode 100644
index 00000000..ed267a1c
--- /dev/null
+++ b/src/free_claude_code/runtime/codex_app_server.py
@@ -0,0 +1,1590 @@
+"""Concrete stdio client for Codex Direct mode."""
+
+import asyncio
+import json
+import os
+import shutil
+import subprocess
+import time
+import uuid
+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
+from contextlib import suppress
+from copy import deepcopy
+from dataclasses import dataclass, field
+from enum import StrEnum
+from typing import cast
+
+from loguru import logger
+
+from free_claude_code.application.work import (
+ CodexAppServerEvent,
+ CodexAvailability,
+ CodexCompatibilityError,
+ CodexConnectionError,
+ CodexConnectionLost,
+ CodexControlCatalog,
+ CodexInitialization,
+ CodexNotification,
+ CodexProtocolError,
+ CodexRequestError,
+ CodexRequestId,
+ CodexServerRequest,
+ CodexThreadHandle,
+ CodexThreadSettings,
+ CodexTurnHandle,
+ CodexTurnSettings,
+ CodexUnavailableError,
+ CodexUnsupportedInteraction,
+)
+from free_claude_code.cli.launchers.codex import (
+ build_codex_launcher_plan,
+ codex_binary_name,
+ codex_model_catalog_plan,
+)
+from free_claude_code.cli.process_registry import (
+ kill_pid_tree_best_effort,
+ register_pid,
+ unregister_pid,
+)
+from free_claude_code.config.settings import Settings
+from free_claude_code.core.json_types import JsonObject, JsonValue
+from free_claude_code.core.version import package_version
+
+_PROTOCOL_LINE_LIMIT = 16 * 1024 * 1024
+_EVENT_QUEUE_LIMIT = 1024
+_REQUEST_TIMEOUT_SECONDS = 30.0
+_GRACEFUL_CLOSE_SECONDS = 5.0
+_TERMINATE_SECONDS = 2.0
+_VERSION_TIMEOUT_SECONDS = 5.0
+_STDERR_CHUNK_BYTES = 8192
+_METHOD_NOT_FOUND = -32601
+_SERVER_REQUEST_RESOLVED = "serverRequest/resolved"
+_IS_WINDOWS = os.name == "nt"
+
+_INTERACTIVE_SERVER_METHODS = frozenset(
+ {
+ "item/commandExecution/requestApproval",
+ "item/fileChange/requestApproval",
+ "item/permissions/requestApproval",
+ "item/tool/requestUserInput",
+ "mcpServer/elicitation/request",
+ "applyPatchApproval",
+ "execCommandApproval",
+ }
+)
+
+
+@dataclass(frozen=True, slots=True)
+class CodexAppServerProcessPlan:
+ """Resolved child invocation; injectable so tests need no Codex install."""
+
+ command: tuple[str, ...]
+ env: dict[str, str]
+ binary_path: str
+ version: str | None
+
+
+type CodexProcessPlanFactory = Callable[[], Awaitable[CodexAppServerProcessPlan]]
+type CodexAvailabilityFactory = Callable[[], Awaitable[CodexAvailability]]
+
+
+@dataclass(slots=True)
+class _PendingCall:
+ method: str
+ future: asyncio.Future[JsonValue]
+
+
+class _ConnectionState(StrEnum):
+ STARTING = "starting"
+ READY = "ready"
+ CLOSING = "closing"
+ CLOSED = "closed"
+
+
+class _ServerRequestState(StrEnum):
+ AWAITING_RESPONSE = "awaiting_response"
+ RESPONSE_COMMITTED = "response_committed"
+
+
+class _ServerRequestObservation(StrEnum):
+ NEW = "new"
+ PENDING_REPLAY = "pending_replay"
+ COMMITTED_DUPLICATE = "committed_duplicate"
+ CONFLICT = "conflict"
+
+
+@dataclass(slots=True)
+class _ServerRequestRecord:
+ method: str
+ params: JsonValue
+ state: _ServerRequestState = _ServerRequestState.AWAITING_RESPONSE
+
+
+@dataclass(frozen=True, slots=True)
+class _StartSucceeded:
+ connection: _Connection
+
+
+@dataclass(frozen=True, slots=True)
+class _StartFailed:
+ error: Exception
+
+
+type _StartOutcome = _StartSucceeded | _StartFailed
+
+
+@dataclass(frozen=True, slots=True)
+class _CleanupOutcome:
+ error: CodexConnectionError | None
+
+
+@dataclass(slots=True)
+class _Connection:
+ id: str
+ state: _ConnectionState = _ConnectionState.STARTING
+ initialize_response_received: bool = False
+ ready_for_events: asyncio.Event = field(default_factory=asyncio.Event)
+ process: asyncio.subprocess.Process | None = None
+ version: str | None = None
+ pending: dict[CodexRequestId, _PendingCall] = field(default_factory=dict)
+ interactive_server_requests: dict[CodexRequestId, _ServerRequestRecord] = field(
+ default_factory=dict
+ )
+ initialization: CodexInitialization | None = None
+ startup_task: asyncio.Task[_StartOutcome] | None = None
+ reader_task: asyncio.Task[None] | None = None
+ stderr_task: asyncio.Task[None] | None = None
+ terminal_error: Exception | None = None
+ cleanup_task: asyncio.Task[_CleanupOutcome] | None = None
+ cleanup_outcome: _CleanupOutcome | None = None
+
+ def observe_server_request(
+ self,
+ *,
+ request_id: CodexRequestId,
+ method: str,
+ params: JsonValue,
+ ) -> _ServerRequestObservation:
+ """Record a new request or classify a replay of an existing request."""
+
+ record = self.interactive_server_requests.get(request_id)
+ if record is None:
+ self.interactive_server_requests[request_id] = _ServerRequestRecord(
+ method=method,
+ params=deepcopy(params),
+ )
+ return _ServerRequestObservation.NEW
+ if record.method != method or record.params != params:
+ return _ServerRequestObservation.CONFLICT
+ if record.state is _ServerRequestState.AWAITING_RESPONSE:
+ return _ServerRequestObservation.PENDING_REPLAY
+ return _ServerRequestObservation.COMMITTED_DUPLICATE
+
+ def require_answerable_server_request(
+ self, request_id: CodexRequestId
+ ) -> _ServerRequestRecord:
+ """Return the request only while a response may still be written."""
+
+ record = self.interactive_server_requests.get(request_id)
+ if record is None or record.state is not _ServerRequestState.AWAITING_RESPONSE:
+ raise CodexConnectionError(
+ "The Codex request is no longer awaiting a response."
+ )
+ return record
+
+ def commit_server_response(self, request_id: CodexRequestId) -> None:
+ """Mark a response committed immediately after its successful write."""
+
+ record = self.require_answerable_server_request(request_id)
+ record.state = _ServerRequestState.RESPONSE_COMMITTED
+
+ def resolve_server_request(self, request_id: CodexRequestId) -> None:
+ """Retire a request that Codex has already resolved or cleared."""
+
+ self.interactive_server_requests.pop(request_id, None)
+
+ def clear_server_requests(self) -> None:
+ """Retire every request owned by this connection generation."""
+
+ self.interactive_server_requests.clear()
+
+
+@dataclass(frozen=True, slots=True)
+class _EventStreamClosed:
+ pass
+
+
+type _QueuedEvent = CodexAppServerEvent | _EventStreamClosed
+
+
+class CodexAppServerClient:
+ """Own one lazy Codex app-server and its bidirectional JSONL connection."""
+
+ def __init__(
+ self,
+ process_plan_factory: CodexProcessPlanFactory,
+ *,
+ availability_factory: CodexAvailabilityFactory | None = None,
+ client_version: str | None = None,
+ ) -> None:
+ self._process_plan_factory = process_plan_factory
+ self._availability_factory = availability_factory
+ self._client_version = client_version or package_version()
+ self._plan: CodexAppServerProcessPlan | None = None
+ self._connection: _Connection | None = None
+ self._plan_lock = asyncio.Lock()
+ self._connection_lock = asyncio.Lock()
+ self._writer_lock = asyncio.Lock()
+ self._events: asyncio.Queue[_QueuedEvent] = asyncio.Queue(
+ maxsize=_EVENT_QUEUE_LIMIT
+ )
+ self._next_request_id = 0
+ self._closed = False
+
+ async def availability(self) -> CodexAvailability:
+ """Resolve the binary and version without starting app-server."""
+
+ if self._closed:
+ return CodexAvailability(
+ available=False,
+ binary_path=None,
+ version=None,
+ reason="Codex Direct mode is closed.",
+ )
+ try:
+ if self._availability_factory is not None:
+ return await self._availability_factory()
+ plan = await self._get_plan()
+ except CodexUnavailableError as exc:
+ return CodexAvailability(
+ available=False,
+ binary_path=None,
+ version=None,
+ reason=str(exc),
+ )
+ return CodexAvailability(
+ available=True,
+ binary_path=plan.binary_path,
+ version=plan.version,
+ reason=None,
+ )
+
+ async def initialize(self) -> CodexInitialization:
+ """Start and initialize app-server on first use."""
+
+ connection = await self._ensure_connection()
+ initialization = connection.initialization
+ if initialization is None:
+ raise CodexProtocolError("Codex app-server did not initialize.")
+ return initialization
+
+ async def controls(self, *, cwd: str) -> CodexControlCatalog:
+ """Read native Codex controls, following every paginated catalog."""
+
+ connection = await self._ensure_connection()
+ models, permission_profiles, collaboration_modes, config = await asyncio.gather(
+ self._optional_paged_objects(connection, "model/list", {}),
+ self._optional_paged_objects(
+ connection,
+ "permissionProfile/list",
+ {"cwd": cwd},
+ ),
+ self._optional_catalog_objects(
+ connection,
+ "collaborationMode/list",
+ {},
+ ),
+ self._optional_config(
+ connection,
+ cwd=cwd,
+ ),
+ )
+ return CodexControlCatalog(
+ models=models,
+ collaboration_modes=collaboration_modes,
+ permission_profiles=permission_profiles,
+ config=config,
+ )
+
+ async def start_thread(self, settings: CodexThreadSettings) -> CodexThreadHandle:
+ """Create one durable native Codex thread."""
+
+ connection = await self._ensure_connection()
+ response = await self._request_object(
+ connection,
+ "thread/start",
+ _thread_params(settings),
+ )
+ return _thread_handle(connection.id, response)
+
+ async def resume_thread(
+ self, thread_id: str, settings: CodexThreadSettings
+ ) -> CodexThreadHandle:
+ """Load a durable native Codex thread into this connection."""
+
+ connection = await self._ensure_connection()
+ params = _thread_params(settings)
+ params["threadId"] = thread_id
+ response = await self._request_object(
+ connection,
+ "thread/resume",
+ params,
+ )
+ return _thread_handle(connection.id, response)
+
+ async def delete_thread(self, thread_id: str) -> None:
+ """Hard-delete one native Codex thread and its descendants."""
+
+ connection = await self._ensure_connection()
+ await self._request_object(
+ connection,
+ "thread/delete",
+ {"threadId": thread_id},
+ )
+
+ async def start_turn(
+ self,
+ *,
+ thread_id: str,
+ text: str,
+ settings: CodexTurnSettings,
+ ) -> CodexTurnHandle:
+ """Submit one native turn exactly once; failures are never replayed."""
+
+ connection = await self._ensure_connection()
+ params: JsonObject = {
+ "threadId": thread_id,
+ "input": [{"type": "text", "text": text}],
+ }
+ _add_optional(params, "model", settings.model)
+ _add_optional(params, "effort", settings.effort)
+ _add_optional(params, "collaborationMode", settings.collaboration_mode)
+ _add_optional(params, "approvalPolicy", settings.approval_policy)
+ _add_optional(params, "permissions", settings.permission_profile)
+ response = await self._request_object(
+ connection,
+ "turn/start",
+ params,
+ timeout=None,
+ )
+ turn = _required_object(response, "turn", "turn/start")
+ turn_id = _required_string(turn, "id", "turn/start turn")
+ return CodexTurnHandle(
+ connection_id=connection.id,
+ thread_id=thread_id,
+ turn_id=turn_id,
+ response=response,
+ )
+
+ async def interrupt_turn(self, *, thread_id: str, turn_id: str) -> None:
+ """Request interruption; the later turn/completed event is authoritative."""
+
+ connection = await self._ensure_connection()
+ await self._request_object(
+ connection,
+ "turn/interrupt",
+ {"threadId": thread_id, "turnId": turn_id},
+ )
+
+ async def respond(
+ self,
+ *,
+ connection_id: str,
+ request_id: CodexRequestId,
+ result: JsonValue,
+ ) -> None:
+ """Answer one server request only on the generation that emitted it."""
+
+ connection = self._connection
+ if (
+ connection is None
+ or connection.state is not _ConnectionState.READY
+ or connection.id != connection_id
+ ):
+ raise CodexConnectionError(
+ "The Codex request belongs to a closed app-server connection."
+ )
+ await self._write_server_response(
+ connection,
+ request_id=request_id,
+ result=result,
+ )
+
+ async def events(self) -> AsyncIterator[CodexAppServerEvent]:
+ """Yield the single-consumer native event stream."""
+
+ while True:
+ event = await self._events.get()
+ if isinstance(event, _EventStreamClosed):
+ return
+ yield event
+
+ async def close(self) -> None:
+ """Close the owned child once, escalating only when it does not exit."""
+
+ connection: _Connection | None = None
+ startup_task: asyncio.Task[_StartOutcome] | None = None
+ cleanup_task: asyncio.Task[_CleanupOutcome] | None = None
+ async with self._connection_lock:
+ first_close = not self._closed
+ if first_close:
+ self._closed = True
+ connection = self._connection
+ if connection is not None:
+ if connection.state is _ConnectionState.STARTING:
+ startup_task = connection.startup_task
+ elif connection.state is _ConnectionState.READY:
+ cleanup_task = self._begin_connection_shutdown(
+ connection,
+ error=CodexConnectionError("Codex Direct mode closed."),
+ emit_event=False,
+ )
+ else:
+ cleanup_task = connection.cleanup_task
+ if first_close:
+ self._finish_event_stream()
+ if startup_task is not None:
+ await asyncio.shield(startup_task)
+ if connection is not None:
+ cleanup_task = connection.cleanup_task
+ if cleanup_task is not None:
+ outcome = await asyncio.shield(cleanup_task)
+ if outcome.error is not None:
+ raise outcome.error
+
+ async def _get_plan(self) -> CodexAppServerProcessPlan:
+ plan = self._plan
+ if plan is not None:
+ return plan
+ async with self._plan_lock:
+ if self._plan is None:
+ self._plan = await self._process_plan_factory()
+ return self._plan
+
+ async def _ensure_connection(self) -> _Connection:
+ while True:
+ startup_task: asyncio.Task[_StartOutcome] | None = None
+ cleanup_task: asyncio.Task[_CleanupOutcome] | None = None
+ async with self._connection_lock:
+ if self._closed:
+ raise CodexUnavailableError("Codex Direct mode is closed.")
+ connection = self._connection
+ if connection is None:
+ connection = _Connection(id=str(uuid.uuid4()))
+ startup_task = asyncio.create_task(
+ self._run_connection_start(connection),
+ name=f"fcc-codex-app-server-start-{connection.id}",
+ )
+ connection.startup_task = startup_task
+ self._connection = connection
+ elif connection.state is _ConnectionState.READY:
+ startup_task = connection.startup_task
+ if startup_task is None or startup_task.done():
+ return connection
+ elif connection.state is _ConnectionState.STARTING:
+ startup_task = connection.startup_task
+ elif connection.state is _ConnectionState.CLOSING:
+ cleanup_task = connection.cleanup_task
+ else:
+ outcome = connection.cleanup_outcome
+ if outcome is not None and outcome.error is not None:
+ raise CodexUnavailableError(
+ str(outcome.error)
+ ) from outcome.error
+ if self._connection is connection:
+ self._connection = None
+ continue
+
+ if startup_task is not None:
+ outcome = await asyncio.shield(startup_task)
+ if isinstance(outcome, _StartSucceeded):
+ return outcome.connection
+ raise outcome.error
+ if cleanup_task is None:
+ raise RuntimeError("Codex connection lifecycle lost its owner task.")
+ outcome = await asyncio.shield(cleanup_task)
+ if outcome.error is not None:
+ raise CodexUnavailableError(str(outcome.error)) from outcome.error
+
+ async def _run_connection_start(self, connection: _Connection) -> _StartOutcome:
+ try:
+ plan = await self._get_plan()
+ connection.version = plan.version
+ if self._closed or self._connection is not connection:
+ raise CodexConnectionError(
+ "Codex Direct mode closed during initialization."
+ )
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *plan.command,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=plan.env,
+ limit=_PROTOCOL_LINE_LIMIT + 1,
+ )
+ except OSError as exc:
+ raise CodexUnavailableError(
+ f"Could not start Codex app-server: {exc}"
+ ) from exc
+ connection.process = process
+ if process.pid is not None:
+ register_pid(process.pid)
+ if (
+ process.stdin is None
+ or process.stdout is None
+ or process.stderr is None
+ ):
+ raise CodexUnavailableError(
+ "Codex app-server did not expose its stdio pipes."
+ )
+ connection.reader_task = asyncio.create_task(
+ self._reader_loop(connection),
+ name=f"fcc-codex-app-server-reader-{connection.id}",
+ )
+ connection.stderr_task = asyncio.create_task(
+ self._stderr_loop(connection),
+ name=f"fcc-codex-app-server-stderr-{connection.id}",
+ )
+ response = await self._request_object(
+ connection,
+ "initialize",
+ {
+ "clientInfo": {
+ "name": "free_claude_code",
+ "title": "Free Claude Code",
+ "version": self._client_version,
+ },
+ "capabilities": {"experimentalApi": True},
+ },
+ during_startup=True,
+ )
+ connection.initialization = CodexInitialization(
+ connection_id=connection.id,
+ user_agent=_required_string(response, "userAgent", "initialize"),
+ codex_home=_required_string(response, "codexHome", "initialize"),
+ platform_family=_required_string(
+ response, "platformFamily", "initialize"
+ ),
+ platform_os=_required_string(response, "platformOs", "initialize"),
+ )
+ await self._write_initialized(connection)
+ async with self._connection_lock:
+ if (
+ not self._closed
+ and self._connection is connection
+ and connection.state is _ConnectionState.READY
+ ):
+ logger.info(
+ "Codex app-server initialized: connection_id={} version={}",
+ connection.id,
+ connection.version or "unknown",
+ )
+ return _StartSucceeded(connection)
+ error = connection.terminal_error or CodexConnectionError(
+ "Codex Direct mode closed during initialization."
+ )
+ except asyncio.CancelledError:
+ self._begin_connection_shutdown(
+ connection,
+ error=CodexConnectionError(
+ "Codex app-server initialization was cancelled."
+ ),
+ emit_event=False,
+ )
+ raise
+ except Exception as exc:
+ error = _connection_error(exc)
+
+ cleanup = await self._shutdown_connection(
+ connection,
+ error=error,
+ emit_event=False,
+ )
+ return _StartFailed(cleanup.error or error)
+
+ async def _request_object(
+ self,
+ connection: _Connection,
+ method: str,
+ params: JsonObject,
+ *,
+ timeout: float | None = _REQUEST_TIMEOUT_SECONDS,
+ during_startup: bool = False,
+ ) -> JsonObject:
+ result = await self._request(
+ connection,
+ method,
+ params,
+ timeout=timeout,
+ during_startup=during_startup,
+ )
+ if not isinstance(result, dict):
+ raise CodexProtocolError(f"Codex {method} returned a non-object result.")
+ return result
+
+ async def _request(
+ self,
+ connection: _Connection,
+ method: str,
+ params: JsonObject,
+ *,
+ timeout: float | None,
+ during_startup: bool = False,
+ ) -> JsonValue:
+ _require_requestable_connection(
+ self,
+ connection,
+ during_startup=during_startup,
+ )
+ request_id = self._next_request_id
+ self._next_request_id += 1
+ future: asyncio.Future[JsonValue] = asyncio.get_running_loop().create_future()
+ connection.pending[request_id] = _PendingCall(method=method, future=future)
+ try:
+ await self._write_message(
+ connection,
+ {"id": request_id, "method": method, "params": params},
+ during_startup=during_startup,
+ )
+ if timeout is None:
+ return await future
+ async with asyncio.timeout(timeout):
+ return await future
+ except TimeoutError as exc:
+ raise CodexConnectionError(
+ f"Codex {method} did not respond within {timeout:g} seconds."
+ ) from exc
+ finally:
+ pending = connection.pending.get(request_id)
+ if pending is not None and pending.future is future:
+ connection.pending.pop(request_id, None)
+ if not future.done():
+ future.cancel()
+ elif not future.cancelled():
+ with suppress(Exception):
+ future.exception()
+
+ async def _write_initialized(self, connection: _Connection) -> None:
+ """Write the handshake barrier before admitting normal requests."""
+
+ process = _connection_process(connection)
+ stdin = process.stdin
+ if stdin is None:
+ raise CodexConnectionError("Codex app-server stdin is unavailable.")
+ encoded = b'{"method":"initialized"}\n'
+ try:
+ async with self._writer_lock:
+ _require_requestable_connection(
+ self,
+ connection,
+ during_startup=True,
+ )
+ if self._closed:
+ raise CodexConnectionError(
+ "Codex Direct mode closed during initialization."
+ )
+ stdin.write(encoded)
+ await stdin.drain()
+ if (
+ self._closed
+ or self._connection is not connection
+ or connection.state is not _ConnectionState.STARTING
+ ):
+ raise CodexConnectionError(
+ "Codex Direct mode closed during initialization."
+ )
+ _transition_connection(
+ connection,
+ expected=_ConnectionState.STARTING,
+ target=_ConnectionState.READY,
+ )
+ connection.ready_for_events.set()
+ except (BrokenPipeError, ConnectionResetError, OSError) as exc:
+ error = CodexConnectionError(
+ "Could not finish Codex app-server initialization."
+ )
+ self._begin_connection_shutdown(
+ connection,
+ error=error,
+ emit_event=False,
+ )
+ raise error from exc
+
+ async def _write_message(
+ self,
+ connection: _Connection,
+ message: JsonObject,
+ *,
+ during_startup: bool = False,
+ ) -> None:
+ _require_requestable_connection(
+ self,
+ connection,
+ during_startup=during_startup,
+ )
+ process = _connection_process(connection)
+ stdin = process.stdin
+ if stdin is None:
+ raise CodexConnectionError("Codex app-server stdin is unavailable.")
+ encoded = (
+ json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n"
+ ).encode("utf-8")
+ try:
+ async with self._writer_lock:
+ _require_requestable_connection(
+ self,
+ connection,
+ during_startup=during_startup,
+ )
+ stdin.write(encoded)
+ await stdin.drain()
+ except (BrokenPipeError, ConnectionResetError, OSError) as exc:
+ error = self._write_failure(connection)
+ raise error from exc
+
+ async def _write_server_response(
+ self,
+ connection: _Connection,
+ *,
+ request_id: CodexRequestId,
+ result: JsonValue,
+ ) -> None:
+ """Write one interactive response and commit its admission atomically."""
+
+ _require_requestable_connection(self, connection, during_startup=False)
+ process = _connection_process(connection)
+ stdin = process.stdin
+ if stdin is None:
+ raise CodexConnectionError("Codex app-server stdin is unavailable.")
+ encoded = (
+ json.dumps(
+ {"id": request_id, "result": result},
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ + "\n"
+ ).encode("utf-8")
+ try:
+ async with self._writer_lock:
+ _require_requestable_connection(self, connection, during_startup=False)
+ connection.require_answerable_server_request(request_id)
+ stdin.write(encoded)
+ connection.commit_server_response(request_id)
+ await stdin.drain()
+ except (BrokenPipeError, ConnectionResetError, OSError) as exc:
+ error = self._write_failure(connection)
+ raise error from exc
+
+ def _write_failure(self, connection: _Connection) -> CodexConnectionError:
+ error = CodexConnectionError("Could not write to Codex app-server.")
+ self._begin_connection_shutdown(
+ connection,
+ error=error,
+ emit_event=True,
+ )
+ return error
+
+ async def _reader_loop(self, connection: _Connection) -> None:
+ process = _connection_process(connection)
+ stdout = process.stdout
+ if stdout is None:
+ return
+ try:
+ while True:
+ try:
+ line = await stdout.readline()
+ except ValueError as exc:
+ raise CodexProtocolError(
+ "Codex app-server emitted a protocol line larger than 16 MiB."
+ ) from exc
+ if not line:
+ return_code = process.returncode
+ suffix = (
+ f"exit code {return_code}"
+ if return_code is not None
+ else "before process exit"
+ )
+ self._begin_connection_shutdown(
+ connection,
+ error=CodexConnectionError(
+ f"Codex app-server closed its connection ({suffix})."
+ ),
+ emit_event=True,
+ )
+ return
+ if connection.state in {
+ _ConnectionState.CLOSING,
+ _ConnectionState.CLOSED,
+ }:
+ return
+ if len(line) > _PROTOCOL_LINE_LIMIT:
+ raise CodexProtocolError(
+ "Codex app-server emitted a protocol line larger than 16 MiB."
+ )
+ message = _decode_message(line)
+ if not await self._handle_message(connection, message):
+ return
+ except asyncio.CancelledError:
+ raise
+ except CodexProtocolError as exc:
+ self._begin_connection_shutdown(
+ connection,
+ error=exc,
+ emit_event=True,
+ )
+ return
+ except Exception as exc:
+ self._begin_connection_shutdown(
+ connection,
+ error=CodexConnectionError(
+ f"Codex app-server reader failed: {type(exc).__name__}."
+ ),
+ emit_event=True,
+ )
+ return
+
+ async def _stderr_loop(self, connection: _Connection) -> None:
+ stderr = _connection_process(connection).stderr
+ if stderr is None:
+ return
+ chunks = 0
+ total_bytes = 0
+ try:
+ while chunk := await stderr.read(_STDERR_CHUNK_BYTES):
+ chunks += 1
+ total_bytes += len(chunk)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.debug(
+ "Codex app-server stderr drain ended: connection_id={} exc_type={}",
+ connection.id,
+ type(exc).__name__,
+ )
+ finally:
+ if total_bytes:
+ logger.debug(
+ "Codex app-server stderr drained: "
+ "connection_id={} chunks={} bytes={}",
+ connection.id,
+ chunks,
+ total_bytes,
+ )
+
+ async def _handle_message(
+ self, connection: _Connection, message: JsonObject
+ ) -> bool:
+ if connection.state in {
+ _ConnectionState.CLOSING,
+ _ConnectionState.CLOSED,
+ }:
+ return False
+ method = message.get("method")
+ request_id_value = message.get("id")
+ has_id = "id" in message
+ if isinstance(method, str):
+ if connection.state is _ConnectionState.STARTING:
+ if not connection.initialize_response_received:
+ raise CodexProtocolError(
+ "Codex app-server emitted a request or notification "
+ "before its initialize response."
+ )
+ await connection.ready_for_events.wait()
+ if (
+ self._closed
+ or self._connection is not connection
+ or connection.state is not _ConnectionState.READY
+ ):
+ return False
+ elif connection.state is not _ConnectionState.READY:
+ return False
+ params = message.get("params", {})
+ if has_id:
+ request_id = _request_id(request_id_value)
+ return await self._handle_server_request(
+ connection,
+ request_id=request_id,
+ method=method,
+ params=params,
+ )
+ return await self._handle_notification(
+ connection,
+ method=method,
+ params=params,
+ )
+ if has_id:
+ request_id = _request_id(request_id_value)
+ pending = connection.pending.get(request_id)
+ if pending is None:
+ return True
+ if (
+ connection.state is _ConnectionState.STARTING
+ and pending.method != "initialize"
+ ):
+ raise RuntimeError(
+ "Codex connection admitted a non-initialize startup request."
+ )
+ if "result" in message and "error" not in message:
+ if (
+ connection.state is _ConnectionState.STARTING
+ and pending.method == "initialize"
+ ):
+ connection.initialize_response_received = True
+ if not pending.future.done():
+ pending.future.set_result(message["result"])
+ return True
+ error_value = message.get("error")
+ if not isinstance(error_value, dict):
+ raise CodexProtocolError(
+ "Codex app-server returned an invalid response envelope."
+ )
+ code_value = error_value.get("code")
+ text_value = error_value.get("message")
+ if (
+ isinstance(code_value, bool)
+ or not isinstance(code_value, int)
+ or not isinstance(text_value, str)
+ ):
+ raise CodexProtocolError(
+ "Codex app-server returned an invalid error envelope."
+ )
+ text = _bounded_text(text_value)
+ if code_value == _METHOD_NOT_FOUND:
+ version = connection.version or "unknown"
+ failure: Exception = CodexCompatibilityError(
+ f"Codex {version} does not support method "
+ f"{pending.method}; update Codex and try again."
+ )
+ else:
+ failure = CodexRequestError(
+ method=pending.method,
+ code=code_value,
+ message=text,
+ )
+ if not pending.future.done():
+ pending.future.set_exception(failure)
+ return True
+ raise CodexProtocolError(
+ "Codex app-server emitted an unrecognized protocol message."
+ )
+
+ async def _handle_notification(
+ self,
+ connection: _Connection,
+ *,
+ method: str,
+ params: JsonValue,
+ ) -> bool:
+ if method == _SERVER_REQUEST_RESOLVED:
+ if not isinstance(params, dict):
+ raise CodexProtocolError(
+ "Codex serverRequest/resolved omitted its params object."
+ )
+ if not isinstance(params.get("threadId"), str):
+ raise CodexProtocolError(
+ "Codex serverRequest/resolved omitted its threadId string."
+ )
+ connection.resolve_server_request(_request_id(params.get("requestId")))
+ return await self._emit(
+ connection,
+ CodexNotification(
+ connection_id=connection.id,
+ method=method,
+ params=params,
+ ),
+ )
+
+ async def _handle_server_request(
+ self,
+ connection: _Connection,
+ *,
+ request_id: CodexRequestId,
+ method: str,
+ params: JsonValue,
+ ) -> bool:
+ if method == "currentTime/read":
+ await self._write_message(
+ connection,
+ {
+ "id": request_id,
+ "result": {"currentTimeAt": int(time.time())},
+ },
+ )
+ return True
+ if method in _INTERACTIVE_SERVER_METHODS:
+ observation = connection.observe_server_request(
+ request_id=request_id,
+ method=method,
+ params=params,
+ )
+ if observation is _ServerRequestObservation.CONFLICT:
+ raise CodexProtocolError(
+ "Codex app-server reused a server request ID with different "
+ "request content."
+ )
+ if observation is _ServerRequestObservation.COMMITTED_DUPLICATE:
+ return True
+ return await self._emit(
+ connection,
+ CodexServerRequest(
+ connection_id=connection.id,
+ request_id=request_id,
+ method=method,
+ params=params,
+ ),
+ )
+ await self._write_message(
+ connection,
+ {
+ "id": request_id,
+ "error": {
+ "code": _METHOD_NOT_FOUND,
+ "message": f"Unsupported server request: {method}",
+ },
+ },
+ )
+ return await self._emit(
+ connection,
+ CodexUnsupportedInteraction(
+ connection_id=connection.id,
+ method=_bounded_text(method, limit=200),
+ ),
+ )
+
+ async def _emit(self, connection: _Connection, event: CodexAppServerEvent) -> bool:
+ if (
+ connection.state is not _ConnectionState.READY
+ or self._connection is not connection
+ ):
+ return False
+ try:
+ self._events.put_nowait(event)
+ except asyncio.QueueFull:
+ self._begin_connection_shutdown(
+ connection,
+ error=CodexConnectionError("Codex app-server event queue overflowed."),
+ emit_event=True,
+ )
+ return False
+ return True
+
+ async def _paged_objects(
+ self,
+ connection: _Connection,
+ method: str,
+ base_params: JsonObject,
+ ) -> tuple[JsonObject, ...]:
+ cursor: str | None = None
+ seen_cursors: set[str] = set()
+ records: list[JsonObject] = []
+ while True:
+ params = dict(base_params)
+ params["limit"] = 100
+ if cursor is not None:
+ params["cursor"] = cursor
+ response = await self._request_object(connection, method, params)
+ records.extend(_object_sequence(response.get("data"), method))
+ next_cursor = response.get("nextCursor")
+ if next_cursor is None:
+ return tuple(records)
+ if not isinstance(next_cursor, str) or not next_cursor:
+ raise CodexProtocolError(
+ f"Codex {method} returned an invalid next cursor."
+ )
+ if next_cursor in seen_cursors:
+ raise CodexProtocolError(
+ f"Codex {method} repeated a pagination cursor."
+ )
+ seen_cursors.add(next_cursor)
+ cursor = next_cursor
+
+ async def _optional_paged_objects(
+ self,
+ connection: _Connection,
+ method: str,
+ base_params: JsonObject,
+ ) -> tuple[JsonObject, ...] | None:
+ try:
+ return await self._paged_objects(connection, method, base_params)
+ except CodexCompatibilityError:
+ return None
+
+ async def _catalog_objects(
+ self,
+ connection: _Connection,
+ method: str,
+ params: JsonObject,
+ ) -> tuple[JsonObject, ...]:
+ response = await self._request_object(connection, method, params)
+ return _object_sequence(response.get("data"), method)
+
+ async def _optional_catalog_objects(
+ self,
+ connection: _Connection,
+ method: str,
+ params: JsonObject,
+ ) -> tuple[JsonObject, ...] | None:
+ try:
+ return await self._catalog_objects(connection, method, params)
+ except CodexCompatibilityError:
+ return None
+
+ async def _optional_config(
+ self,
+ connection: _Connection,
+ *,
+ cwd: str,
+ ) -> JsonObject | None:
+ try:
+ response = await self._request_object(
+ connection,
+ "config/read",
+ {"cwd": cwd, "includeLayers": False},
+ )
+ except CodexCompatibilityError:
+ return None
+ config = response.get("config")
+ if not isinstance(config, dict):
+ raise CodexProtocolError("Codex config/read omitted its config object.")
+ return config
+
+ async def _shutdown_connection(
+ self,
+ connection: _Connection,
+ *,
+ error: Exception,
+ emit_event: bool,
+ ) -> _CleanupOutcome:
+ task = self._begin_connection_shutdown(
+ connection,
+ error=error,
+ emit_event=emit_event,
+ )
+ return await asyncio.shield(task)
+
+ def _begin_connection_shutdown(
+ self,
+ connection: _Connection,
+ *,
+ error: Exception,
+ emit_event: bool,
+ ) -> asyncio.Task[_CleanupOutcome]:
+ task = connection.cleanup_task
+ if task is not None:
+ return task
+ if connection.state not in {
+ _ConnectionState.STARTING,
+ _ConnectionState.READY,
+ }:
+ raise RuntimeError(
+ "Codex connection entered a terminal state without a cleanup task."
+ )
+ was_ready = connection.state is _ConnectionState.READY
+ _transition_connection(
+ connection,
+ expected=connection.state,
+ target=_ConnectionState.CLOSING,
+ )
+ connection.terminal_error = error
+ for pending in tuple(connection.pending.values()):
+ if not pending.future.done():
+ pending.future.set_exception(error)
+ connection.clear_server_requests()
+ if emit_event and was_ready:
+ self._emit_connection_lost(connection.id, str(error))
+ task = asyncio.create_task(
+ self._run_connection_cleanup(connection),
+ name=f"fcc-codex-app-server-cleanup-{connection.id}",
+ )
+ connection.cleanup_task = task
+ return task
+
+ async def _run_connection_cleanup(self, connection: _Connection) -> _CleanupOutcome:
+ cleanup_error: CodexConnectionError | None = None
+ process = connection.process
+ try:
+ if process is not None:
+ cleanup_error = await _stop_process(process)
+ except Exception as exc:
+ cleanup_error = CodexConnectionError(
+ "Codex app-server cleanup failed while stopping its process: "
+ f"{type(exc).__name__}."
+ )
+
+ tasks = tuple(
+ task
+ for task in (connection.reader_task, connection.stderr_task)
+ if task is not None
+ )
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ if tasks:
+ try:
+ async with asyncio.timeout(_TERMINATE_SECONDS):
+ await asyncio.gather(*tasks, return_exceptions=True)
+ except TimeoutError:
+ cleanup_error = cleanup_error or CodexConnectionError(
+ "Codex app-server I/O tasks did not stop within the deadline."
+ )
+
+ if process is not None and process.pid is not None:
+ if process.returncode is None:
+ cleanup_error = cleanup_error or CodexConnectionError(
+ "Codex app-server could not be reaped after forced termination."
+ )
+ else:
+ unregister_pid(process.pid)
+
+ _transition_connection(
+ connection,
+ expected=_ConnectionState.CLOSING,
+ target=_ConnectionState.CLOSED,
+ )
+ outcome = _CleanupOutcome(error=cleanup_error)
+ connection.cleanup_outcome = outcome
+ terminal_error = connection.terminal_error
+ if cleanup_error is None:
+ logger.info(
+ "Codex app-server closed: connection_id={} reason={}",
+ connection.id,
+ type(terminal_error).__name__,
+ )
+ async with self._connection_lock:
+ if self._connection is connection:
+ self._connection = None
+ else:
+ logger.warning(
+ "Codex app-server cleanup incomplete: "
+ "connection_id={} reason={} cleanup_error={}",
+ connection.id,
+ type(terminal_error).__name__,
+ cleanup_error,
+ )
+ return outcome
+
+ def _emit_connection_lost(self, connection_id: str, message: str) -> None:
+ event = CodexConnectionLost(
+ connection_id=connection_id,
+ message=_bounded_text(message),
+ )
+ if self._events.full():
+ while not self._events.empty():
+ with suppress(asyncio.QueueEmpty):
+ self._events.get_nowait()
+ self._events.put_nowait(event)
+
+ def _finish_event_stream(self) -> None:
+ if self._events.full():
+ with suppress(asyncio.QueueEmpty):
+ self._events.get_nowait()
+ self._events.put_nowait(_EventStreamClosed())
+
+
+def _transition_connection(
+ connection: _Connection,
+ *,
+ expected: _ConnectionState,
+ target: _ConnectionState,
+) -> None:
+ if connection.state is not expected:
+ raise RuntimeError(
+ "Invalid Codex connection transition: "
+ f"{connection.state.value} -> {target.value}."
+ )
+ connection.state = target
+
+
+def _connection_process(connection: _Connection) -> asyncio.subprocess.Process:
+ process = connection.process
+ if process is None:
+ raise CodexConnectionError("Codex app-server process is unavailable.")
+ return process
+
+
+def _require_requestable_connection(
+ client: CodexAppServerClient,
+ connection: _Connection,
+ *,
+ during_startup: bool,
+) -> None:
+ expected = _ConnectionState.STARTING if during_startup else _ConnectionState.READY
+ if (
+ client._connection is not connection
+ or connection.state is not expected
+ or (client._closed and not during_startup)
+ ):
+ raise CodexConnectionError("Codex app-server connection is closed.")
+
+
+def create_codex_app_server_client(
+ *,
+ settings: Settings,
+ proxy_root_url: str,
+ base_env: Mapping[str, str] | None = None,
+) -> CodexAppServerClient:
+ """Build the production client without starting Codex until first use."""
+
+ environment = dict(os.environ if base_env is None else base_env)
+ installed: CodexAvailability | None = None
+ availability_lock = asyncio.Lock()
+
+ async def inspect() -> CodexAvailability:
+ nonlocal installed
+ if installed is not None:
+ return installed
+ async with availability_lock:
+ if installed is None:
+ installed = await _inspect_codex_installation(environment)
+ return installed
+
+ async def prepare() -> CodexAppServerProcessPlan:
+ availability = await inspect()
+ if not availability.available or availability.binary_path is None:
+ raise CodexUnavailableError(
+ availability.reason or "Codex CLI is not installed."
+ )
+ return await _prepare_codex_app_server_process_plan(
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ base_env=environment,
+ binary_path=availability.binary_path,
+ version=availability.version,
+ )
+
+ return CodexAppServerClient(prepare, availability_factory=inspect)
+
+
+async def prepare_codex_app_server_process_plan(
+ *,
+ settings: Settings,
+ proxy_root_url: str,
+ base_env: Mapping[str, str],
+) -> CodexAppServerProcessPlan:
+ """Prepare the Direct child with the same ephemeral config as `fcc-codex`."""
+
+ environment = dict(base_env)
+ availability = await _inspect_codex_installation(environment)
+ if not availability.available or availability.binary_path is None:
+ raise CodexUnavailableError(
+ availability.reason or "Codex CLI is not installed."
+ )
+ return await _prepare_codex_app_server_process_plan(
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ base_env=environment,
+ binary_path=availability.binary_path,
+ version=availability.version,
+ )
+
+
+async def _inspect_codex_installation(
+ environment: Mapping[str, str],
+) -> CodexAvailability:
+ binary_path = shutil.which(
+ codex_binary_name(),
+ path=_environment_path(environment),
+ )
+ if binary_path is None:
+ return CodexAvailability(
+ available=False,
+ binary_path=None,
+ version=None,
+ reason=(
+ "Codex CLI is not installed. Install it with: "
+ "npm install -g @openai/codex"
+ ),
+ )
+ version = await asyncio.to_thread(_read_codex_version, binary_path, environment)
+ return CodexAvailability(
+ available=True,
+ binary_path=binary_path,
+ version=version,
+ reason=None,
+ )
+
+
+async def _prepare_codex_app_server_process_plan(
+ *,
+ settings: Settings,
+ proxy_root_url: str,
+ base_env: Mapping[str, str],
+ binary_path: str,
+ version: str | None,
+) -> CodexAppServerProcessPlan:
+ catalog = await asyncio.to_thread(
+ codex_model_catalog_plan,
+ proxy_root_url,
+ settings,
+ )
+ launcher = build_codex_launcher_plan(
+ binary_path=binary_path,
+ argv=("app-server", "--stdio"),
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ catalog_config_args=catalog.config_args,
+ catalog_models=catalog.models,
+ base_env=base_env,
+ )
+ return CodexAppServerProcessPlan(
+ command=launcher.command,
+ env=launcher.env,
+ binary_path=binary_path,
+ version=version,
+ )
+
+
+def _read_codex_version(binary_path: str, env: Mapping[str, str]) -> str | None:
+ try:
+ result = subprocess.run(
+ [binary_path, "--version"],
+ capture_output=True,
+ check=False,
+ encoding="utf-8",
+ env=env,
+ errors="replace",
+ text=True,
+ timeout=_VERSION_TIMEOUT_SECONDS,
+ )
+ except OSError, subprocess.SubprocessError:
+ return None
+ if result.returncode != 0:
+ return None
+ version = result.stdout.strip()
+ return _bounded_text(version, limit=200) or None
+
+
+def _environment_path(environment: Mapping[str, str]) -> str | None:
+ return next(
+ (value for key, value in environment.items() if key.casefold() == "path"),
+ None,
+ )
+
+
+async def _stop_process(
+ process: asyncio.subprocess.Process,
+) -> CodexConnectionError | None:
+ stdin = process.stdin
+ if stdin is not None:
+ stdin.close()
+ try:
+ async with asyncio.timeout(_TERMINATE_SECONDS):
+ await stdin.wait_closed()
+ except TimeoutError, BrokenPipeError, ConnectionResetError:
+ pass
+ if process.returncode is not None:
+ await process.wait()
+ return None
+ try:
+ async with asyncio.timeout(_GRACEFUL_CLOSE_SECONDS):
+ await process.wait()
+ return None
+ except TimeoutError:
+ if _IS_WINDOWS and process.pid is not None:
+ await asyncio.to_thread(
+ kill_pid_tree_best_effort,
+ process.pid,
+ timeout_seconds=_TERMINATE_SECONDS,
+ )
+ else:
+ with suppress(ProcessLookupError):
+ process.terminate()
+ try:
+ async with asyncio.timeout(_TERMINATE_SECONDS):
+ await process.wait()
+ return None
+ except TimeoutError:
+ with suppress(ProcessLookupError):
+ process.kill()
+ try:
+ async with asyncio.timeout(_TERMINATE_SECONDS):
+ await process.wait()
+ except TimeoutError:
+ return CodexConnectionError(
+ "Codex app-server did not exit after forced termination."
+ )
+ return None
+
+
+def _thread_params(settings: CodexThreadSettings) -> JsonObject:
+ params: JsonObject = {"cwd": settings.cwd}
+ _add_optional(params, "model", settings.model)
+ _add_optional(params, "approvalPolicy", settings.approval_policy)
+ _add_optional(params, "permissions", settings.permission_profile)
+ return params
+
+
+def _add_optional(target: JsonObject, key: str, value: JsonValue) -> None:
+ if value is not None:
+ target[key] = value
+
+
+def _thread_handle(connection_id: str, response: JsonObject) -> CodexThreadHandle:
+ thread = _required_object(response, "thread", "thread response")
+ return CodexThreadHandle(
+ connection_id=connection_id,
+ thread_id=_required_string(thread, "id", "thread response"),
+ response=response,
+ )
+
+
+def _required_object(value: JsonObject, key: str, source: str) -> JsonObject:
+ nested = value.get(key)
+ if not isinstance(nested, dict):
+ raise CodexProtocolError(f"Codex {source} omitted its {key} object.")
+ return nested
+
+
+def _required_string(value: JsonObject, key: str, source: str) -> str:
+ nested = value.get(key)
+ if not isinstance(nested, str) or not nested:
+ raise CodexProtocolError(f"Codex {source} omitted its {key} value.")
+ return nested
+
+
+def _object_sequence(value: JsonValue, source: str) -> tuple[JsonObject, ...]:
+ if not isinstance(value, list):
+ raise CodexProtocolError(f"Codex {source} omitted its data array.")
+ records: list[JsonObject] = []
+ for record in value:
+ if not isinstance(record, dict):
+ raise CodexProtocolError(
+ f"Codex {source} returned a non-object catalog entry."
+ )
+ records.append(record)
+ return tuple(records)
+
+
+def _request_id(value: JsonValue) -> CodexRequestId:
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
+ raise CodexProtocolError("Codex app-server emitted an invalid request id.")
+ return value
+
+
+def _decode_message(line: bytes) -> JsonObject:
+ try:
+ decoded = line.decode("utf-8")
+ value = cast(JsonValue, json.loads(decoded))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise CodexProtocolError("Codex app-server emitted malformed JSONL.") from exc
+ if not isinstance(value, dict):
+ raise CodexProtocolError(
+ "Codex app-server emitted a non-object protocol message."
+ )
+ return value
+
+
+def _connection_error(exc: BaseException) -> CodexConnectionError:
+ if isinstance(exc, CodexConnectionError):
+ return exc
+ return CodexConnectionError(
+ f"Codex app-server initialization failed: {type(exc).__name__}."
+ )
+
+
+def _bounded_text(value: str, *, limit: int = 1000) -> str:
+ normalized = " ".join(value.split())
+ if len(normalized) <= limit:
+ return normalized
+ return f"{normalized[: limit - 1]}…"
diff --git a/tests/cli/test_process_registry.py b/tests/cli/test_process_registry.py
index cfe66129..11afbaed 100644
--- a/tests/cli/test_process_registry.py
+++ b/tests/cli/test_process_registry.py
@@ -86,7 +86,8 @@ def test_process_registry_kill_pid_tree_windows_uses_taskkill(monkeypatch):
monkeypatch.setattr(os, "name", "nt", raising=False)
monkeypatch.setattr(subprocess, "run", lambda *a, **kw: calls.append((a, kw)))
- pr.kill_pid_tree_best_effort(12345)
+ pr.kill_pid_tree_best_effort(12345, timeout_seconds=1.25)
assert calls
assert calls[0][0][0] == ["taskkill", "/PID", "12345", "/T", "/F"]
+ assert calls[0][1]["timeout"] == 1.25
diff --git a/tests/fixtures/fake_codex_app_server.py b/tests/fixtures/fake_codex_app_server.py
new file mode 100644
index 00000000..9938a2b3
--- /dev/null
+++ b/tests/fixtures/fake_codex_app_server.py
@@ -0,0 +1,298 @@
+"""Deterministic JSONL child used by Codex app-server contract tests."""
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+_LINE_LIMIT = 16 * 1024 * 1024
+
+
+def _emit(message: object) -> None:
+ sys.stdout.write(json.dumps(message, separators=(",", ":")) + "\n")
+ sys.stdout.flush()
+
+
+def _emit_together(*messages: object) -> None:
+ sys.stdout.write(
+ "".join(
+ json.dumps(message, separators=(",", ":")) + "\n" for message in messages
+ )
+ )
+ sys.stdout.flush()
+
+
+def _append(path: str | None, value: str) -> None:
+ if path:
+ with Path(path).open("a", encoding="utf-8") as output:
+ output.write(value + "\n")
+
+
+def _launch_number(path: str | None) -> int:
+ if path is None:
+ return 1
+ counter = Path(path)
+ try:
+ value = int(counter.read_text(encoding="utf-8")) + 1
+ except FileNotFoundError, ValueError:
+ value = 1
+ counter.write_text(str(value), encoding="utf-8")
+ return value
+
+
+def _control_path(name: str) -> Path | None:
+ root = os.environ.get("FAKE_CODEX_CONTROL_DIR")
+ return None if root is None else Path(root) / name
+
+
+def _signal(name: str) -> None:
+ path = _control_path(name)
+ if path is not None:
+ path.touch()
+
+
+def _wait_for(name: str) -> None:
+ path = _control_path(name)
+ if path is None:
+ return
+ while not path.exists():
+ time.sleep(0.01)
+
+
+def _normal_response(method: str, params: object) -> object:
+ if method == "initialize":
+ return {
+ "userAgent": "fake-codex/1.2.3",
+ "codexHome": "/fake/codex",
+ "platformFamily": "test",
+ "platformOs": "test",
+ "futureField": True,
+ }
+ if method == "model/list":
+ cursor = params.get("cursor") if isinstance(params, dict) else None
+ if cursor is None:
+ return {"data": [{"id": "model-1"}], "nextCursor": "models-2"}
+ return {"data": [{"id": "model-2", "futureField": 1}]}
+ if method == "permissionProfile/list":
+ return {"data": [{"id": ":workspace", "name": "Workspace"}]}
+ if method == "collaborationMode/list":
+ return {"data": [{"name": "Plan", "mode": "plan"}]}
+ if method == "config/read":
+ return {"config": {"approval_policy": "on-request"}, "origins": {}}
+ if method in {"thread/start", "thread/resume"}:
+ thread_id = "thread-1"
+ if method == "thread/resume" and isinstance(params, dict):
+ supplied = params.get("threadId")
+ if isinstance(supplied, str):
+ thread_id = supplied
+ return {"thread": {"id": thread_id}, "futureField": {"kept": True}}
+ if method in {"thread/delete", "turn/interrupt"}:
+ return {}
+ if method == "turn/start":
+ return {"turn": {"id": "turn-1"}}
+ return {}
+
+
+def _approval_request() -> object:
+ return {
+ "id": "approval-1",
+ "method": "item/commandExecution/requestApproval",
+ "params": {"availableDecisions": ["accept", "decline"]},
+ }
+
+
+def _approval_resolved() -> object:
+ return {
+ "method": "serverRequest/resolved",
+ "params": {
+ "threadId": "thread-1",
+ "requestId": "approval-1",
+ "futureField": {"kept": True},
+ },
+ }
+
+
+def main() -> None:
+ scenario = os.environ.get("FAKE_CODEX_SCENARIO", "normal")
+ missing_method = os.environ.get("FAKE_CODEX_MISSING_METHOD")
+ failing_method = os.environ.get("FAKE_CODEX_FAILING_METHOD")
+ log_path = os.environ.get("FAKE_CODEX_REQUEST_LOG")
+ launch_number = _launch_number(os.environ.get("FAKE_CODEX_LAUNCH_COUNTER"))
+ delayed_model: tuple[object, object] | None = None
+
+ def release_delayed_model() -> None:
+ nonlocal delayed_model
+ if delayed_model is None:
+ return
+ delayed_id, delayed_params = delayed_model
+ _emit(
+ {
+ "id": delayed_id,
+ "result": _normal_response("model/list", delayed_params),
+ }
+ )
+ delayed_model = None
+
+ for raw_line in sys.stdin:
+ message = json.loads(raw_line)
+ if not isinstance(message, dict):
+ continue
+ method = message.get("method")
+ request_id = message.get("id")
+ if isinstance(method, str):
+ _append(log_path, method)
+ if method == "initialized":
+ if scenario == "hang_on_close":
+ for _remaining in sys.stdin:
+ pass
+ while True:
+ time.sleep(60)
+ continue
+ if not isinstance(method, str):
+ if request_id == "clock-1":
+ _emit({"method": "fixture/currentTime", "params": message})
+ elif request_id == "future-1":
+ _emit({"method": "fixture/methodNotFound", "params": message})
+ elif request_id == "approval-1":
+ _append(log_path, "response:approval-1")
+ if scenario == "replay_after_response":
+ _emit(_approval_request())
+ elif scenario == "hold_resolution_after_replay":
+ _emit_together(
+ _approval_request(),
+ {
+ "method": "fixture/postWriteReplay",
+ "params": {"observed": True},
+ },
+ )
+ _wait_for("release-approval-resolution")
+ _emit_together(
+ _approval_resolved(),
+ {"method": "fixture/approvalAnswered", "params": message},
+ )
+ continue
+ params = message.get("params", {})
+
+ if method == "initialize" and scenario == "delay_initialize":
+ _signal("initialize-seen")
+ _wait_for("release-initialize")
+ if method == "initialize" and scenario == "invalid_initialize":
+ _emit({"id": request_id, "result": []})
+ continue
+ if method == "initialize" and scenario == "notification_with_initialize":
+ _emit_together(
+ {
+ "id": request_id,
+ "result": _normal_response(method, params),
+ },
+ {
+ "method": "fixture/ready",
+ "params": {"initialized": True},
+ },
+ )
+ continue
+ if method == "thread/start" and scenario == "delay_thread_start":
+ _signal("thread-start-seen")
+ _wait_for("release-thread-start")
+ if method == "thread/start" and scenario == "malformed":
+ sys.stdout.write("{not-json}\n")
+ sys.stdout.flush()
+ continue
+ if method == "thread/start" and scenario == "malformed_then_notification":
+ sys.stdout.write("{not-json}\n")
+ _emit(
+ {
+ "method": "fixture/afterTerminal",
+ "params": {"mustNotAppear": True},
+ }
+ )
+ continue
+ if method == "thread/start" and scenario == "oversized":
+ sys.stdout.buffer.write(b'{"oversized":"' + b"x" * _LINE_LIMIT + b'"}\n')
+ sys.stdout.buffer.flush()
+ continue
+ if method == "thread/start" and scenario == "invalid_thread_result":
+ _emit({"id": request_id, "result": []})
+ continue
+ if method == "turn/start" and scenario == "fail_once" and launch_number == 1:
+ sys.exit(7)
+ if method == missing_method or (
+ scenario == "missing_method" and method == "permissionProfile/list"
+ ):
+ _emit(
+ {
+ "id": request_id,
+ "error": {"code": -32601, "message": "Method not found"},
+ }
+ )
+ if method == "config/read":
+ release_delayed_model()
+ continue
+ if method == failing_method:
+ _emit(
+ {
+ "id": request_id,
+ "error": {"code": -32000, "message": "Injected request failure"},
+ }
+ )
+ if method == "config/read":
+ release_delayed_model()
+ continue
+
+ if method == "model/list" and not (
+ isinstance(params, dict) and params.get("cursor") is not None
+ ):
+ delayed_model = (request_id, params)
+ continue
+
+ _emit({"id": request_id, "result": _normal_response(method, params)})
+
+ if method == "thread/resume":
+ if scenario == "replay_on_resume":
+ _emit(_approval_request())
+ elif scenario == "conflicting_replay_on_resume":
+ _emit(
+ {
+ "id": "approval-1",
+ "method": "item/commandExecution/requestApproval",
+ "params": {"availableDecisions": ["decline"]},
+ }
+ )
+
+ if method == "config/read":
+ release_delayed_model()
+
+ if method == "turn/start":
+ if scenario == "flood":
+ for index in range(3):
+ _emit({"method": "fixture/flood", "params": {"index": index}})
+ continue
+ _emit(
+ {
+ "method": "future/notification",
+ "params": {"newField": [1, 2, 3]},
+ "futureEnvelopeField": True,
+ }
+ )
+ _emit(
+ {
+ "id": "clock-1",
+ "method": "currentTime/read",
+ "params": {},
+ }
+ )
+ _emit(
+ {
+ "id": "future-1",
+ "method": "future/serverRequest",
+ "params": {},
+ }
+ )
+ _emit(_approval_request())
+ if scenario == "resolve_before_response":
+ _emit(_approval_resolved())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/runtime/test_codex_app_server.py b/tests/runtime/test_codex_app_server.py
new file mode 100644
index 00000000..fafda1a6
--- /dev/null
+++ b/tests/runtime/test_codex_app_server.py
@@ -0,0 +1,1378 @@
+"""Contracts for the concrete Codex app-server stdio owner."""
+
+import asyncio
+import gc
+import os
+import sys
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Literal
+
+import pytest
+
+from free_claude_code.application.work import (
+ CodexAppServerEvent,
+ CodexCompatibilityError,
+ CodexConnectionError,
+ CodexConnectionLost,
+ CodexNotification,
+ CodexProtocolError,
+ CodexRequestError,
+ CodexServerRequest,
+ CodexThreadSettings,
+ CodexTurnSettings,
+ CodexUnavailableError,
+ CodexUnsupportedInteraction,
+)
+from free_claude_code.cli.launchers.codex import CodexModelCatalogPlan
+from free_claude_code.config.settings import Settings
+from free_claude_code.runtime import codex_app_server
+from free_claude_code.runtime.codex_app_server import (
+ CodexAppServerClient,
+ CodexAppServerProcessPlan,
+ prepare_codex_app_server_process_plan,
+)
+
+_FAKE_SERVER = (
+ Path(__file__).resolve().parents[1] / "fixtures" / "fake_codex_app_server.py"
+)
+
+
+def _client(
+ tmp_path: Path,
+ *,
+ scenario: str = "normal",
+ request_log: Path | None = None,
+ launch_counter: Path | None = None,
+ control_dir: Path | None = None,
+ missing_method: str | None = None,
+ failing_method: str | None = None,
+) -> CodexAppServerClient:
+ env = os.environ.copy()
+ env["FAKE_CODEX_SCENARIO"] = scenario
+ if request_log is not None:
+ env["FAKE_CODEX_REQUEST_LOG"] = str(request_log)
+ if launch_counter is not None:
+ env["FAKE_CODEX_LAUNCH_COUNTER"] = str(launch_counter)
+ if control_dir is not None:
+ env["FAKE_CODEX_CONTROL_DIR"] = str(control_dir)
+ if missing_method is not None:
+ env["FAKE_CODEX_MISSING_METHOD"] = missing_method
+ if failing_method is not None:
+ env["FAKE_CODEX_FAILING_METHOD"] = failing_method
+
+ async def plan() -> CodexAppServerProcessPlan:
+ return CodexAppServerProcessPlan(
+ command=(sys.executable, str(_FAKE_SERVER)),
+ env=env,
+ binary_path=sys.executable,
+ version="codex-cli 1.2.3",
+ )
+
+ return CodexAppServerClient(plan, client_version="9.8.7")
+
+
+async def _next(
+ events: AsyncIterator[CodexAppServerEvent],
+) -> CodexAppServerEvent:
+ async with asyncio.timeout(2):
+ return await anext(events)
+
+
+async def _next_server_request(
+ events: AsyncIterator[CodexAppServerEvent],
+) -> CodexServerRequest:
+ while True:
+ event = await _next(events)
+ if isinstance(event, CodexServerRequest):
+ return event
+ if isinstance(event, CodexConnectionLost):
+ pytest.fail(
+ f"Codex connection failed before server request: {event.message}"
+ )
+
+
+async def _next_notification(
+ events: AsyncIterator[CodexAppServerEvent], method: str
+) -> CodexNotification:
+ while True:
+ event = await _next(events)
+ if isinstance(event, CodexNotification) and event.method == method:
+ return event
+ if isinstance(event, CodexConnectionLost):
+ pytest.fail(f"Codex connection failed before {method}: {event.message}")
+
+
+class _ObservedLock(asyncio.Lock):
+ def __init__(self) -> None:
+ super().__init__()
+ self.acquire_started = asyncio.Event()
+
+ async def acquire(self) -> Literal[True]:
+ self.acquire_started.set()
+ return await super().acquire()
+
+
+async def _wait_for_file(path: Path) -> None:
+ async with asyncio.timeout(2):
+ while not path.exists():
+ await asyncio.sleep(0.01)
+
+
+async def test_production_plan_reuses_launcher_config_and_scrubbed_environment(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def find_binary(command: str, *, path: str | None) -> str | None:
+ assert command == "codex"
+ assert path == "test-path"
+ return "resolved-codex.exe"
+
+ monkeypatch.setattr(codex_app_server.shutil, "which", find_binary)
+ monkeypatch.setattr(
+ codex_app_server,
+ "codex_model_catalog_plan",
+ lambda _proxy, _settings: CodexModelCatalogPlan(),
+ )
+ monkeypatch.setattr(
+ codex_app_server,
+ "_read_codex_version",
+ lambda _binary, _env: "codex-cli 1.2.3",
+ )
+ settings = Settings(
+ model="nvidia_nim/test-model",
+ proxy_auth_enabled=False,
+ proxy_auth_token="proxy-token",
+ )
+
+ plan = await prepare_codex_app_server_process_plan(
+ settings=settings,
+ proxy_root_url="http://127.0.0.1:8082",
+ base_env={
+ "Path": "test-path",
+ "OPENAI_API_KEY": "must-not-leak",
+ "CODEX_HOME": "keep-home",
+ },
+ )
+
+ assert plan.binary_path == "resolved-codex.exe"
+ assert plan.version == "codex-cli 1.2.3"
+ assert plan.command[0] == "resolved-codex.exe"
+ assert 'model_provider="fcc"' in plan.command
+ assert 'model_providers.fcc.wire_api="responses"' in plan.command
+ assert plan.command[-2:] == ("app-server", "--stdio")
+ assert "OPENAI_API_KEY" not in plan.env
+ assert plan.env["CODEX_HOME"] == "keep-home"
+ assert plan.env["NO_PROXY"] == "127.0.0.1,localhost,::1"
+
+
+async def test_initializes_once_and_reads_concurrent_native_catalogs(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(tmp_path, request_log=request_log)
+ try:
+ initialization, controls = await asyncio.gather(
+ client.initialize(),
+ client.controls(cwd=str(tmp_path)),
+ )
+
+ availability = await client.availability()
+ assert availability.available is True
+ assert availability.version == "codex-cli 1.2.3"
+ assert initialization.user_agent == "fake-codex/1.2.3"
+ assert initialization.connection_id
+ assert controls.models is not None
+ assert controls.permission_profiles is not None
+ assert controls.collaboration_modes is not None
+ assert controls.config is not None
+ assert [model["id"] for model in controls.models] == ["model-1", "model-2"]
+ assert controls.permission_profiles[0]["id"] == ":workspace"
+ assert controls.collaboration_modes[0]["mode"] == "plan"
+ assert controls.config["approval_policy"] == "on-request"
+ methods = request_log.read_text(encoding="utf-8").splitlines()
+ assert methods.count("initialize") == 1
+ assert methods.count("initialized") == 1
+ assert methods.count("model/list") == 2
+ finally:
+ await client.close()
+
+
+async def test_concurrent_callers_wait_for_initialized_before_sending_methods(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="delay_initialize",
+ request_log=request_log,
+ launch_counter=launch_counter,
+ control_dir=tmp_path,
+ )
+ initialize = asyncio.create_task(client.initialize())
+ await _wait_for_file(tmp_path / "initialize-seen")
+ start_thread = asyncio.create_task(
+ client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ )
+ try:
+ await asyncio.sleep(0)
+ assert request_log.read_text(encoding="utf-8").splitlines() == ["initialize"]
+
+ (tmp_path / "release-initialize").touch()
+ initialization, thread = await asyncio.gather(initialize, start_thread)
+
+ assert initialization.connection_id == thread.connection_id
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ methods = request_log.read_text(encoding="utf-8").splitlines()
+ assert methods.index("initialized") < methods.index("thread/start")
+ finally:
+ (tmp_path / "release-initialize").touch()
+ await client.close()
+
+
+async def test_notification_buffered_with_initialize_waits_for_readiness(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(
+ tmp_path,
+ scenario="notification_with_initialize",
+ request_log=request_log,
+ )
+ events = client.events()
+ try:
+ initialization = await client.initialize()
+ event = await _next(events)
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+
+ assert isinstance(event, CodexNotification)
+ assert event.connection_id == initialization.connection_id
+ assert event.method == "fixture/ready"
+ assert event.params == {"initialized": True}
+ assert thread.connection_id == initialization.connection_id
+ methods = request_log.read_text(encoding="utf-8").splitlines()
+ assert methods.index("initialized") < methods.index("thread/start")
+ finally:
+ await client.close()
+
+
+async def test_cancelling_one_startup_waiter_preserves_shared_start(
+ tmp_path: Path,
+) -> None:
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="delay_initialize",
+ launch_counter=launch_counter,
+ control_dir=tmp_path,
+ )
+ cancelled_waiter = asyncio.create_task(client.initialize())
+ await _wait_for_file(tmp_path / "initialize-seen")
+ surviving_waiter = asyncio.create_task(client.initialize())
+ try:
+ cancelled_waiter.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await cancelled_waiter
+ (tmp_path / "release-initialize").touch()
+
+ initialization = await surviving_waiter
+ assert initialization.connection_id
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ finally:
+ (tmp_path / "release-initialize").touch()
+ await client.close()
+
+
+async def test_close_during_startup_never_publishes_connection(
+ tmp_path: Path,
+) -> None:
+ client = _client(
+ tmp_path,
+ scenario="delay_initialize",
+ control_dir=tmp_path,
+ )
+ events = client.events()
+ initialize = asyncio.create_task(client.initialize())
+ await _wait_for_file(tmp_path / "initialize-seen")
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ close = asyncio.create_task(client.close())
+ try:
+ async with asyncio.timeout(1):
+ while not client._closed:
+ await asyncio.sleep(0.01)
+ (tmp_path / "release-initialize").touch()
+
+ await close
+ with pytest.raises(CodexConnectionError, match="closed during initialization"):
+ await initialize
+ assert process.returncode is not None
+ with pytest.raises(StopAsyncIteration):
+ await anext(events)
+ finally:
+ (tmp_path / "release-initialize").touch()
+ await asyncio.gather(close, return_exceptions=True)
+ await asyncio.gather(initialize, return_exceptions=True)
+ if process.returncode is None:
+ await codex_app_server._stop_process(process)
+
+
+async def test_invalid_initialize_result_stays_private_to_startup(
+ tmp_path: Path,
+) -> None:
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="invalid_initialize",
+ launch_counter=launch_counter,
+ )
+ events = client.events()
+
+ with pytest.raises(
+ CodexConnectionError,
+ match="Codex app-server initialization failed: CodexProtocolError",
+ ):
+ await client.initialize()
+
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ await client.close()
+ with pytest.raises(StopAsyncIteration):
+ await anext(events)
+
+
+async def test_thread_turn_events_and_bidirectional_server_requests(
+ tmp_path: Path,
+) -> None:
+ client = _client(tmp_path)
+ events = client.events()
+ try:
+ thread = await client.start_thread(
+ CodexThreadSettings(
+ cwd=str(tmp_path),
+ model="provider/model",
+ approval_policy="on-request",
+ permission_profile=":workspace",
+ )
+ )
+ assert thread.thread_id == "thread-1"
+ assert thread.response["futureField"] == {"kept": True}
+
+ resumed = await client.resume_thread(
+ "thread-existing",
+ CodexThreadSettings(cwd=str(tmp_path)),
+ )
+ assert resumed.thread_id == "thread-existing"
+
+ turn = await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(
+ effort="high",
+ collaboration_mode={"mode": "plan"},
+ ),
+ )
+ assert turn.turn_id == "turn-1"
+
+ notification = await _next(events)
+ assert isinstance(notification, CodexNotification)
+ assert notification.method == "future/notification"
+
+ observed: dict[str, object] = {}
+ approval: CodexServerRequest | None = None
+ unsupported: CodexUnsupportedInteraction | None = None
+ while len(observed) < 2 or approval is None or unsupported is None:
+ event = await _next(events)
+ if isinstance(event, CodexServerRequest):
+ approval = event
+ continue
+ if isinstance(event, CodexUnsupportedInteraction):
+ unsupported = event
+ continue
+ assert isinstance(event, CodexNotification)
+ observed[event.method] = event.params
+ assert set(observed) == {"fixture/currentTime", "fixture/methodNotFound"}
+ current_time = observed["fixture/currentTime"]
+ assert isinstance(current_time, dict)
+ assert isinstance(current_time["result"], dict)
+ assert isinstance(current_time["result"]["currentTimeAt"], int)
+ method_not_found = observed["fixture/methodNotFound"]
+ assert isinstance(method_not_found, dict)
+ assert isinstance(method_not_found["error"], dict)
+ assert method_not_found["error"]["code"] == -32601
+ assert unsupported.method == "future/serverRequest"
+ assert unsupported.connection_id == turn.connection_id
+ assert approval.method == "item/commandExecution/requestApproval"
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ with pytest.raises(CodexConnectionError, match="no longer awaiting"):
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ resolved = await _next(events)
+ assert isinstance(resolved, CodexNotification)
+ assert resolved.method == "serverRequest/resolved"
+ assert resolved.params == {
+ "threadId": "thread-1",
+ "requestId": "approval-1",
+ "futureField": {"kept": True},
+ }
+ answered = await _next(events)
+ assert isinstance(answered, CodexNotification)
+ assert answered.method == "fixture/approvalAnswered"
+
+ await client.interrupt_turn(
+ thread_id=thread.thread_id,
+ turn_id=turn.turn_id,
+ )
+ await client.delete_thread(thread.thread_id)
+ finally:
+ await client.close()
+
+
+async def test_remote_resolution_retires_server_request_before_local_response(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(
+ tmp_path,
+ scenario="resolve_before_response",
+ request_log=request_log,
+ )
+ events = client.events()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+
+ approval: CodexServerRequest | None = None
+ resolved: CodexNotification | None = None
+ while approval is None or resolved is None:
+ event = await _next(events)
+ if isinstance(event, CodexServerRequest):
+ if event.request_id == "approval-1":
+ approval = event
+ continue
+ if (
+ isinstance(event, CodexNotification)
+ and event.method == "serverRequest/resolved"
+ ):
+ resolved = event
+
+ assert resolved.params == {
+ "threadId": "thread-1",
+ "requestId": "approval-1",
+ "futureField": {"kept": True},
+ }
+ with pytest.raises(CodexConnectionError, match="no longer awaiting"):
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+
+ await client.delete_thread(thread.thread_id)
+ assert (
+ "response:approval-1"
+ not in request_log.read_text(encoding="utf-8").splitlines()
+ )
+ finally:
+ await client.close()
+
+
+async def test_pending_server_request_is_replayed_when_thread_resumes(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(
+ tmp_path,
+ scenario="replay_on_resume",
+ request_log=request_log,
+ )
+ events = client.events()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+ approval = await _next_server_request(events)
+ assert approval.request_id == "approval-1"
+ assert isinstance(approval.params, dict)
+ approval.params["consumerMutation"] = True
+
+ resumed = await client.resume_thread(
+ thread.thread_id,
+ CodexThreadSettings(cwd=str(tmp_path)),
+ )
+ replay = await _next_server_request(events)
+
+ assert resumed.thread_id == thread.thread_id
+ assert replay.connection_id == approval.connection_id
+ assert replay.request_id == approval.request_id
+ assert replay.method == approval.method
+ assert replay.params == {"availableDecisions": ["accept", "decline"]}
+
+ await client.respond(
+ connection_id=replay.connection_id,
+ request_id=replay.request_id,
+ result={"decision": "decline"},
+ )
+ resolved = await _next_notification(events, "serverRequest/resolved")
+ assert resolved.params == {
+ "threadId": "thread-1",
+ "requestId": "approval-1",
+ "futureField": {"kept": True},
+ }
+
+ await client.delete_thread(thread.thread_id)
+ assert (
+ request_log.read_text(encoding="utf-8")
+ .splitlines()
+ .count("response:approval-1")
+ == 1
+ )
+ finally:
+ await client.close()
+
+
+async def test_conflicting_server_request_replay_fails_connection(
+ tmp_path: Path,
+) -> None:
+ client = _client(tmp_path, scenario="conflicting_replay_on_resume")
+ events = client.events()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+ approval = await _next_server_request(events)
+ assert approval.request_id == "approval-1"
+
+ await client.resume_thread(
+ thread.thread_id,
+ CodexThreadSettings(cwd=str(tmp_path)),
+ )
+ while True:
+ event = await _next(events)
+ if isinstance(event, CodexConnectionLost):
+ assert "different request content" in event.message
+ break
+ if isinstance(event, CodexServerRequest):
+ pytest.fail("A conflicting request replay was exposed as answerable.")
+ finally:
+ await client.close()
+
+
+async def test_replay_after_response_commit_is_suppressed_until_resolution(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(
+ tmp_path,
+ scenario="replay_after_response",
+ request_log=request_log,
+ )
+ events = client.events()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+ approval = await _next_server_request(events)
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+
+ while True:
+ event = await _next(events)
+ if isinstance(event, CodexServerRequest):
+ pytest.fail("A committed server request was exposed as answerable.")
+ if (
+ isinstance(event, CodexNotification)
+ and event.method == "serverRequest/resolved"
+ ):
+ break
+ if isinstance(event, CodexConnectionLost):
+ pytest.fail(
+ "Codex connection failed before request resolution: "
+ f"{event.message}"
+ )
+
+ with pytest.raises(CodexConnectionError, match="no longer awaiting"):
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ await client.delete_thread(thread.thread_id)
+ assert (
+ request_log.read_text(encoding="utf-8")
+ .splitlines()
+ .count("response:approval-1")
+ == 1
+ )
+ finally:
+ await client.close()
+
+
+async def test_cancelled_response_waiting_for_writer_remains_answerable(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ client = _client(tmp_path, request_log=request_log)
+ events = client.events()
+ response: asyncio.Task[None] | None = None
+ writer_lock = _ObservedLock()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+ approval = await _next_server_request(events)
+
+ await writer_lock.acquire()
+ writer_lock.acquire_started.clear()
+ client._writer_lock = writer_lock
+ response = asyncio.create_task(
+ client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ )
+ async with asyncio.timeout(1):
+ await writer_lock.acquire_started.wait()
+ response.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await response
+ assert (
+ "response:approval-1"
+ not in request_log.read_text(encoding="utf-8").splitlines()
+ )
+
+ writer_lock.release()
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ await _next_notification(events, "serverRequest/resolved")
+ await client.delete_thread(thread.thread_id)
+ assert (
+ request_log.read_text(encoding="utf-8")
+ .splitlines()
+ .count("response:approval-1")
+ == 1
+ )
+ finally:
+ if response is not None and not response.done():
+ response.cancel()
+ await asyncio.gather(response, return_exceptions=True)
+ if writer_lock.locked():
+ writer_lock.release()
+ await client.close()
+
+
+async def test_cancelled_response_during_drain_remains_committed(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ release_resolution = tmp_path / "release-approval-resolution"
+ client = _client(
+ tmp_path,
+ scenario="hold_resolution_after_replay",
+ request_log=request_log,
+ control_dir=tmp_path,
+ )
+ events = client.events()
+ response: asyncio.Task[None] | None = None
+ release_drain = asyncio.Event()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="hello",
+ settings=CodexTurnSettings(),
+ )
+ approval = await _next_server_request(events)
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ stdin = process.stdin
+ assert stdin is not None
+ original_drain = stdin.drain
+ drain_started = asyncio.Event()
+
+ async def gated_drain() -> None:
+ drain_started.set()
+ await release_drain.wait()
+ await original_drain()
+
+ monkeypatch.setattr(stdin, "drain", gated_drain)
+ response = asyncio.create_task(
+ client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ )
+ async with asyncio.timeout(1):
+ await drain_started.wait()
+
+ while True:
+ event = await _next(events)
+ if isinstance(event, CodexServerRequest):
+ pytest.fail("A post-write replay was exposed as answerable.")
+ if (
+ isinstance(event, CodexNotification)
+ and event.method == "fixture/postWriteReplay"
+ ):
+ break
+ if isinstance(event, CodexConnectionLost):
+ pytest.fail(
+ f"Codex connection failed before post-write replay: {event.message}"
+ )
+
+ response.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await response
+ release_drain.set()
+ with pytest.raises(CodexConnectionError, match="no longer awaiting"):
+ await client.respond(
+ connection_id=approval.connection_id,
+ request_id=approval.request_id,
+ result={"decision": "decline"},
+ )
+ assert (
+ request_log.read_text(encoding="utf-8")
+ .splitlines()
+ .count("response:approval-1")
+ == 1
+ )
+
+ release_resolution.touch()
+ await _next_notification(events, "serverRequest/resolved")
+ await client.delete_thread(thread.thread_id)
+ finally:
+ release_drain.set()
+ release_resolution.touch()
+ if response is not None and not response.done():
+ response.cancel()
+ await asyncio.gather(response, return_exceptions=True)
+ await client.close()
+
+
[email protected]("scenario", ["malformed", "oversized"])
+async def test_invalid_protocol_disconnects_without_hanging_pending_calls(
+ tmp_path: Path,
+ scenario: str,
+) -> None:
+ client = _client(tmp_path, scenario=scenario)
+ events = client.events()
+ try:
+ with pytest.raises(CodexProtocolError):
+ await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ lost = await _next(events)
+ assert isinstance(lost, CodexConnectionLost)
+ assert lost.connection_id
+ finally:
+ await client.close()
+
+
+async def test_connection_loss_is_final_for_its_generation(
+ tmp_path: Path,
+) -> None:
+ client = _client(tmp_path, scenario="malformed_then_notification")
+ events = client.events()
+ try:
+ with pytest.raises(CodexProtocolError):
+ await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+
+ lost = await _next(events)
+ assert isinstance(lost, CodexConnectionLost)
+ connection_id = lost.connection_id
+
+ await client.close()
+ with pytest.raises(StopAsyncIteration):
+ await anext(events)
+ assert lost.connection_id == connection_id
+ finally:
+ await client.close()
+
+
+async def test_stdout_eof_fails_request_before_process_cleanup_finishes(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ client = _client(
+ tmp_path,
+ scenario="delay_thread_start",
+ control_dir=tmp_path,
+ )
+ await client.initialize()
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ reader_task = connection.reader_task
+ assert reader_task is not None
+ reader_task.cancel()
+ await asyncio.gather(reader_task, return_exceptions=True)
+ eof_reader = asyncio.StreamReader()
+ process.stdout = eof_reader
+ connection.reader_task = asyncio.create_task(client._reader_loop(connection))
+ cleanup_started = asyncio.Event()
+ release_cleanup = asyncio.Event()
+ original_stop = codex_app_server._stop_process
+
+ async def held_stop(
+ target: asyncio.subprocess.Process,
+ ) -> CodexConnectionError | None:
+ cleanup_started.set()
+ await release_cleanup.wait()
+ return await original_stop(target)
+
+ monkeypatch.setattr(codex_app_server, "_stop_process", held_stop)
+ request = asyncio.create_task(
+ client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ )
+ try:
+ await _wait_for_file(tmp_path / "thread-start-seen")
+ eof_reader.feed_eof()
+ async with asyncio.timeout(1):
+ await cleanup_started.wait()
+
+ with pytest.raises(CodexConnectionError, match="before process exit"):
+ async with asyncio.timeout(1):
+ await request
+ assert process.returncode is None
+ finally:
+ (tmp_path / "release-thread-start").touch()
+ release_cleanup.set()
+ if not request.done():
+ request.cancel()
+ await asyncio.gather(request, return_exceptions=True)
+ await client.close()
+
+
+async def test_process_failure_is_not_replayed_and_next_call_starts_cleanly(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="fail_once",
+ request_log=request_log,
+ launch_counter=launch_counter,
+ )
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ with pytest.raises(CodexConnectionError):
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="first",
+ settings=CodexTurnSettings(),
+ )
+ await asyncio.sleep(0.05)
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ assert (
+ request_log.read_text(encoding="utf-8").splitlines().count("turn/start")
+ == 1
+ )
+
+ restarted = await client.start_turn(
+ thread_id=thread.thread_id,
+ text="second",
+ settings=CodexTurnSettings(),
+ )
+ assert restarted.turn_id == "turn-1"
+ assert launch_counter.read_text(encoding="utf-8") == "2"
+ assert (
+ request_log.read_text(encoding="utf-8").splitlines().count("turn/start")
+ == 2
+ )
+ finally:
+ await client.close()
+
+
+async def test_cancelled_request_ignores_late_response_on_same_connection(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="delay_thread_start",
+ request_log=request_log,
+ launch_counter=launch_counter,
+ control_dir=tmp_path,
+ )
+ initialization = await client.initialize()
+ start_thread = asyncio.create_task(
+ client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ )
+ await _wait_for_file(tmp_path / "thread-start-seen")
+ try:
+ start_thread.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await start_thread
+
+ (tmp_path / "release-thread-start").touch()
+ await client.delete_thread("thread-after-cancel")
+
+ connection = client._connection
+ assert connection is not None
+ assert connection.id == initialization.connection_id
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ methods = request_log.read_text(encoding="utf-8").splitlines()
+ assert methods.count("thread/start") == 1
+ assert methods.count("thread/delete") == 1
+ finally:
+ (tmp_path / "release-thread-start").touch()
+ await asyncio.gather(start_thread, return_exceptions=True)
+ await client.close()
+
+
+ ("missing_method", "missing_field"),
+ [
+ ("model/list", "models"),
+ ("permissionProfile/list", "permission_profiles"),
+ ("collaborationMode/list", "collaboration_modes"),
+ ("config/read", "config"),
+ ],
+)
+async def test_missing_optional_catalog_method_degrades_independently(
+ tmp_path: Path,
+ missing_method: str,
+ missing_field: str,
+) -> None:
+ client = _client(tmp_path, missing_method=missing_method)
+ try:
+ controls = await client.controls(cwd=str(tmp_path))
+
+ assert getattr(controls, missing_field) is None
+ for field in (
+ "models",
+ "permission_profiles",
+ "collaboration_modes",
+ "config",
+ ):
+ if field != missing_field:
+ assert getattr(controls, field) is not None
+ finally:
+ await client.close()
+
+
+async def test_missing_required_method_is_actionable(tmp_path: Path) -> None:
+ client = _client(tmp_path, missing_method="thread/start")
+ try:
+ with pytest.raises(
+ CodexCompatibilityError,
+ match=r"codex-cli 1\.2\.3.*thread/start.*update Codex",
+ ):
+ await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ finally:
+ await client.close()
+
+
+async def test_optional_catalog_request_failure_is_not_hidden(tmp_path: Path) -> None:
+ client = _client(tmp_path, failing_method="permissionProfile/list")
+ try:
+ with pytest.raises(CodexRequestError, match="Injected request failure"):
+ await client.controls(cwd=str(tmp_path))
+ finally:
+ await client.close()
+
+
+async def test_event_overflow_fails_the_connection_instead_of_dropping_silently(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(codex_app_server, "_EVENT_QUEUE_LIMIT", 2)
+ client = _client(tmp_path, scenario="flood")
+ events = client.events()
+ try:
+ thread = await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ await client.start_turn(
+ thread_id=thread.thread_id,
+ text="flood",
+ settings=CodexTurnSettings(),
+ )
+ connection = client._connection
+ assert connection is not None
+ async with asyncio.timeout(1):
+ while connection.cleanup_task is None:
+ await asyncio.sleep(0)
+ lost = await _next(events)
+ assert isinstance(lost, CodexConnectionLost)
+ assert "overflowed" in lost.message
+ assert lost.connection_id == connection.id
+ await client.close()
+ with pytest.raises(StopAsyncIteration):
+ await anext(events)
+ finally:
+ await client.close()
+
+
+async def test_write_failure_observes_pending_future_exception(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ client = _client(tmp_path)
+ await client.initialize()
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ writer = process.stdin
+ assert writer is not None
+ loop = asyncio.get_running_loop()
+ previous_handler = loop.get_exception_handler()
+ loop_messages: list[str] = []
+
+ def capture_loop_error(
+ _loop: asyncio.AbstractEventLoop,
+ context: dict[str, object],
+ ) -> None:
+ message = context.get("message")
+ loop_messages.append(message if isinstance(message, str) else repr(context))
+
+ async def broken_drain() -> None:
+ raise BrokenPipeError
+
+ loop.set_exception_handler(capture_loop_error)
+ try:
+ monkeypatch.setattr(writer, "drain", broken_drain)
+ with pytest.raises(CodexConnectionError, match="Could not write"):
+ await client.delete_thread("thread-write-failure")
+ await client.close()
+ gc.collect()
+ await asyncio.sleep(0)
+ assert not any("never retrieved" in message for message in loop_messages)
+ finally:
+ loop.set_exception_handler(previous_handler)
+ await client.close()
+
+
+async def test_close_is_idempotent_and_escalates_for_child_ignoring_eof(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(codex_app_server, "_GRACEFUL_CLOSE_SECONDS", 0.05)
+ monkeypatch.setattr(codex_app_server, "_TERMINATE_SECONDS", 0.05)
+ client = _client(tmp_path, scenario="hang_on_close")
+ await client.initialize()
+
+ await client.close()
+ await client.close()
+
+ availability = await client.availability()
+ assert availability.available is False
+
+
+async def test_cancelled_close_waiter_does_not_cancel_owned_shutdown(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(codex_app_server, "_GRACEFUL_CLOSE_SECONDS", 0.05)
+ monkeypatch.setattr(codex_app_server, "_TERMINATE_SECONDS", 0.05)
+ client = _client(tmp_path, scenario="hang_on_close")
+ await client.initialize()
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ events = client.events()
+ stop_started = asyncio.Event()
+ release_stop = asyncio.Event()
+ stop_calls = 0
+ original_stop = codex_app_server._stop_process
+
+ async def blocking_stop(
+ target: asyncio.subprocess.Process,
+ ) -> CodexConnectionError | None:
+ nonlocal stop_calls
+ stop_calls += 1
+ stop_started.set()
+ await release_stop.wait()
+ return await original_stop(target)
+
+ monkeypatch.setattr(codex_app_server, "_stop_process", blocking_stop)
+ first_close = asyncio.create_task(client.close())
+ second_close: asyncio.Task[None] | None = None
+ try:
+ async with asyncio.timeout(1):
+ await stop_started.wait()
+ first_close.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first_close
+
+ second_close = asyncio.create_task(client.close())
+ await asyncio.sleep(0)
+ assert not second_close.done()
+
+ release_stop.set()
+ async with asyncio.timeout(1):
+ await second_close
+
+ assert stop_calls == 1
+ assert process.returncode is not None
+ with pytest.raises(StopAsyncIteration):
+ async with asyncio.timeout(1):
+ await anext(events)
+ finally:
+ release_stop.set()
+ if second_close is not None and not second_close.done():
+ second_close.cancel()
+ await asyncio.gather(second_close, return_exceptions=True)
+ if process.returncode is None:
+ await original_stop(process)
+ if process.pid is not None:
+ codex_app_server.unregister_pid(process.pid)
+
+
+async def test_failed_cleanup_remains_owned_and_blocks_replacement(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ registered_pids: set[int] = set()
+ monkeypatch.setattr(codex_app_server, "register_pid", registered_pids.add)
+ monkeypatch.setattr(codex_app_server, "unregister_pid", registered_pids.discard)
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="malformed",
+ launch_counter=launch_counter,
+ )
+ await client.initialize()
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ assert process.pid in registered_pids
+ cleanup_started = asyncio.Event()
+ release_cleanup = asyncio.Event()
+ original_stop = codex_app_server._stop_process
+ loop = asyncio.get_running_loop()
+ previous_handler = loop.get_exception_handler()
+ loop_messages: list[str] = []
+
+ def capture_loop_error(
+ _loop: asyncio.AbstractEventLoop,
+ context: dict[str, object],
+ ) -> None:
+ message = context.get("message")
+ loop_messages.append(message if isinstance(message, str) else repr(context))
+
+ async def failed_stop(
+ _target: asyncio.subprocess.Process,
+ ) -> CodexConnectionError:
+ cleanup_started.set()
+ await release_cleanup.wait()
+ return CodexConnectionError("injected unreaped process")
+
+ loop.set_exception_handler(capture_loop_error)
+ monkeypatch.setattr(codex_app_server, "_stop_process", failed_stop)
+ failed_request = asyncio.create_task(
+ client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+ )
+ blocked_replacement: asyncio.Task[object] | None = None
+ first_close: asyncio.Task[None] | None = None
+ try:
+ async with asyncio.timeout(1):
+ await cleanup_started.wait()
+ blocked_replacement = asyncio.create_task(client.initialize())
+ await asyncio.sleep(0)
+ assert not blocked_replacement.done()
+
+ first_close = asyncio.create_task(client.close())
+ async with asyncio.timeout(1):
+ while not client._closed:
+ await asyncio.sleep(0)
+ first_close.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first_close
+
+ release_cleanup.set()
+ with pytest.raises(CodexProtocolError):
+ await failed_request
+ with pytest.raises(CodexUnavailableError, match="injected unreaped process"):
+ await blocked_replacement
+ cleanup = connection.cleanup_task
+ assert cleanup is not None
+ outcome = await asyncio.shield(cleanup)
+ assert outcome.error is not None
+
+ with pytest.raises(CodexConnectionError, match="injected unreaped process"):
+ await client.close()
+ assert client._connection is connection
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ assert process.pid in registered_pids
+ gc.collect()
+ await asyncio.sleep(0)
+ assert not any("never retrieved" in message for message in loop_messages)
+ finally:
+ release_cleanup.set()
+ loop.set_exception_handler(previous_handler)
+ await asyncio.gather(failed_request, return_exceptions=True)
+ if blocked_replacement is not None:
+ await asyncio.gather(blocked_replacement, return_exceptions=True)
+ if first_close is not None:
+ await asyncio.gather(first_close, return_exceptions=True)
+ if process.returncode is None:
+ await original_stop(process)
+ if process.pid is not None:
+ registered_pids.discard(process.pid)
+
+
+async def test_stalled_stdin_close_reaches_bounded_process_escalation(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(codex_app_server, "_GRACEFUL_CLOSE_SECONDS", 0.05)
+ monkeypatch.setattr(codex_app_server, "_TERMINATE_SECONDS", 0.05)
+ client = _client(tmp_path, scenario="hang_on_close")
+ await client.initialize()
+ connection = client._connection
+ assert connection is not None
+ process = connection.process
+ assert process is not None
+ never_closed = asyncio.Event()
+ original_stop = codex_app_server._stop_process
+
+ async def stalled_wait_closed(_writer: asyncio.StreamWriter) -> None:
+ await never_closed.wait()
+
+ try:
+ with monkeypatch.context() as context:
+ context.setattr(asyncio.StreamWriter, "wait_closed", stalled_wait_closed)
+ async with asyncio.timeout(1):
+ await client.close()
+ assert process.returncode is not None
+ finally:
+ if process.returncode is None:
+ await original_stop(process)
+ if process.pid is not None:
+ codex_app_server.unregister_pid(process.pid)
+
+
+async def test_windows_forced_shutdown_targets_tree_before_root_only_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "import sys, time; sys.stdin.read(); time.sleep(60)",
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ tree_calls: list[tuple[int, float | None, bool]] = []
+ terminate_called = False
+
+ def tree_kill(pid: int, *, timeout_seconds: float | None = None) -> None:
+ tree_calls.append((pid, timeout_seconds, process.returncode is None))
+
+ original_terminate = process.terminate
+
+ def record_terminate() -> None:
+ nonlocal terminate_called
+ terminate_called = True
+ original_terminate()
+
+ monkeypatch.setattr(codex_app_server, "_IS_WINDOWS", True)
+ monkeypatch.setattr(codex_app_server, "_GRACEFUL_CLOSE_SECONDS", 0.05)
+ monkeypatch.setattr(codex_app_server, "_TERMINATE_SECONDS", 0.05)
+ monkeypatch.setattr(codex_app_server, "kill_pid_tree_best_effort", tree_kill)
+ monkeypatch.setattr(process, "terminate", record_terminate)
+ try:
+ await codex_app_server._stop_process(process)
+ assert tree_calls == [(process.pid, 0.05, True)]
+ assert terminate_called is False
+ assert process.returncode is not None
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+
+
+async def test_method_result_shape_failure_keeps_healthy_connection(
+ tmp_path: Path,
+) -> None:
+ request_log = tmp_path / "requests.log"
+ launch_counter = tmp_path / "launch-count"
+ client = _client(
+ tmp_path,
+ scenario="invalid_thread_result",
+ request_log=request_log,
+ launch_counter=launch_counter,
+ )
+ try:
+ with pytest.raises(
+ CodexProtocolError,
+ match="Codex thread/start returned a non-object result",
+ ):
+ await client.start_thread(CodexThreadSettings(cwd=str(tmp_path)))
+
+ await client.delete_thread("thread-existing")
+
+ assert launch_counter.read_text(encoding="utf-8") == "1"
+ assert (
+ request_log.read_text(encoding="utf-8").splitlines().count("thread/delete")
+ == 1
+ )
+ finally:
+ await client.close()
diff --git a/uv.lock b/uv.lock
index d9e2030a..da289fac 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "5.19.0"
+version = "5.19.1"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },