Skip to main content

Module app_server

Module app_server 

Source
Expand description

A JSON-RPC client for codex app-server.

codex exec takes one prompt per process and cannot change a turn that is already running. The app-server can: AppServerHandle::turn_steer adds input to the active turn and AppServerHandle::turn_interrupt stops it. AppServer runs the server over stdio and gives a caller its events as they arrive, plus a way to answer the requests the server sends back, such as approvals.

The CLI marks app-server experimental, so this module is behind the app-server feature and wraps the transport, not the whole protocol. The four methods with typed helpers (thread_start, turn_start, turn_steer, turn_interrupt) were exercised against a real server; request reaches any other method without a wrapper change.

§Example

use codex_wrapper::Codex;
use codex_wrapper::app_server::{
    AppServer, ServerMessage, ThreadStartParams, TurnStartParams, UserInput,
};

let codex = Codex::builder().build()?;
let mut server = AppServer::builder(&codex).start().await?;

let thread = server
    .thread_start(ThreadStartParams::new().ephemeral(true))
    .await?;
let turn = server
    .turn_start(TurnStartParams::text(&thread.id, "run `sleep 10`, then say DONE"))
    .await?;

// A handle can be cloned into another task, for example one that
// serves a "steer" command while this task reads events.
let handle = server.handle();
handle
    .turn_steer(&thread.id, &turn.id, vec![UserInput::text("also say STEERED")])
    .await?;

let mut answer = None;
while let Some(message) = server.next_message().await? {
    match message {
        ServerMessage::Notification(notification) => {
            if let Some(message) = notification.agent_message()
                && message.is_final_answer()
            {
                answer = Some(message.text);
            }
            if let Some(done) = notification.turn_completed() {
                println!("{:?}: {answer:?}", done.turn.status);
                break;
            }
        }
        ServerMessage::Request(request) => {
            // An unanswered request stalls the turn.
            server.respond_error(request.id, -32601, "not supported")?;
        }
        _ => {}
    }
}
server.shutdown().await?;

§Lifecycle and cancellation

The server runs in its own process group (unless the client disables CodexBuilder::process_group). That group does not include the shell commands a turn runs: the server starts each in a group of its own. So there are two ways to stop, and they differ in what happens to a command that is still running:

  • AppServer::shutdown closes the server’s stdin and waits up to the client’s termination grace for it to exit. The server stops its running commands and exits, in milliseconds when a turn is active. If it does not exit in time, this falls back to AppServer::terminate. Prefer it.
  • AppServer::terminate has the settled contract of stream_exec_cancellable: it asks the server’s group to stop, waits through the grace period, kills what is left, and reaps the child before returning. A command the server started in its own group keeps running, as it does when codex exec is cancelled; the caller has to find and stop it.
  • Dropping an AppServer kills the server’s group without waiting, as dropping a streaming future does. The same caveat applies.

AppServerHandle::turn_interrupt ends the turn, not the command it is running.

  • A failure that leaves the stream unusable (the output limit, or a line that starts with { but is not valid JSON) kills the child: on Unix as soon as it is detected, and on Windows through its owned process handle. The error also reaches any request still waiting.

§Limits

CodexBuilder::output_limit caps the total bytes read from stdout over the life of the session, as it does for streaming. CodexBuilder::timeout applies to each request, including the handshake, and not to the session; without it a request waits until the server answers or exits. The server’s stderr is drained continuously and the last 16 KiB is kept for error messages.

By default messages wait in an unbounded queue until AppServer::next_message returns them, so a caller that does not read them, or reads more slowly than the server writes, holds them in memory. output_limit bounds the total. Streaming deltas are most of the volume, and AppServerBuilder::opt_out_notification stops the server sending them.

Five opt-in limits bound memory instead of the lifetime total, and each is off by default:

  • max_frame_bytes: one line from the server, newline included. A longer line is rejected before more than the limit is buffered, whether or not it ever ends.
  • max_queued_messages and max_queued_bytes: notifications and server requests read but not yet returned by next_message. Answers to the client’s own requests do not pass through this queue, so they are delivered while events wait, and the reader never blocks on it.
  • max_writer_queue_messages and max_writer_queue_bytes: lines queued for the server’s stdin, including the one being written. A server that stops reading its input fills this.

Exceeding any of them ends the connection with Error::AppServerLimitExceeded. No message is dropped or merged to stay under a limit: an approval request or a turn/completed that does not fit is not delivered and the session fails instead, so a caller never mistakes a lossy stream for a complete one. Messages queued before the failure are still returned by next_message, then the error. Every waiting request fails with the same error, later sends fail at once, and the process the client owns is killed, as for the output limit.

§Capabilities

initialize is sent without capabilities unless something asks for one. AppServerBuilder::capability sets any field of it by its protocol name, for example experimentalApi, which experimental_api also sets. The wrapper does not check other fields; what a field means and whether the server accepts it depends on the CLI version.

optOutNotificationMethods can be set both ways. The two lists are combined: the entries set through capability first, then those from opt_out_notification, each method once. A value for it that is neither an array of strings nor null is rejected by AppServerBuilder::start before anything is spawned. AppServerBuilder::initialize_params shows the result.

§Connecting to an existing server

On Unix, AppServerBuilder::connect_unix(path) attaches over a WebSocket connection to an explicitly selected Unix socket. It spawns no process: AppServer::pid is None, and shutdown, terminate, drop, or a transport failure close only this connection. They never signal the shared server or promise to interrupt its turns. Client binary/env/global arguments, spawn observers, and process-group policies do not apply in this mode.

The connection performs a fresh initialize handshake with the configured capabilities. Client timeout bounds connect/upgrade and each RPC wait. Frame and queue byte limits count UTF-8 JSON message payloads, without WebSocket headers; stdio counts raw line bytes including delimiters. These budgets are not exact heap measurements. WebSocket frame and aggregate-message limits prevent fragmentation from bypassing the cap.

Attached transport support was qualified on CLI 0.163.0 and remains experimental. Nothing discovers or starts a daemon, adopts a private TUI process, reconnects automatically, or replays uncertain requests. A new connection must explicitly resume/reconcile threads, subscriptions and approvals. Empty, unmaterialized threads may not yet be resumable by a second client. Two-client rejoin, steering, pending approval delivery and cancellation, observer disconnect/reconnect, and server loss were probed with an isolated server and deterministic offline backend. See the shipped tests/app-server-qualification.md for versioned evidence and limits.

§Verified against codex-cli 0.149.0

Each of these was read from a captured session, not inferred. Re-capture after a CLI upgrade and correct this block in the same change.

  • Messages are newline-delimited JSON with no jsonrpc field. A notification may carry extra top-level fields (emittedAtMs).
  • A request before initialize gets {"error":{"code":-32600,"message": "Not initialized"},"id":N}, a second initialize gets Already initialized, and an unknown method gets code -32600 with the valid method names in the message.
  • initialize takes clientInfo and optionally capabilities.optOutNotificationMethods, which suppresses those notifications for the connection. The client then sends an initialized notification.
  • thread/start accepts cwd, ephemeral, approvalPolicy, sandbox, and model. It answers with {"thread":{"id":...},"model":...} and sends a thread/started notification.
  • turn/start accepts threadId, input, model, effort, outputSchema, cwd, and approvalPolicy. It answers with {"turn":{"id":...,"status":"inProgress"}}. With outputSchema the captured final message was JSON that followed the schema.
  • A turn ends with a turn/completed notification whose turn.status is completed or interrupted. Whether turn.items holds the final answer depends on the CLI: 0.149.0 includes it (itemsView summary), 0.145.0 always sends items: [] (notLoaded). Both send an item/completed notification for the final agentMessage (phase final_answer) before turn/completed, so that is what Notification::agent_message decodes.
  • turn/steer answers {"turnId":...} at once. The text reaches the model at the next item boundary, not immediately. With no active turn it fails with no active turn to steer; with one, but a different expectedTurnId, with expected active turn id `X` but found `Y` .
  • turn/interrupt answers {}. With no active turn it fails with no active turn to interrupt; with a different turnId, with expected active turn id X but found Y. It ends the turn and leaves a running shell command alone.
  • The server runs each shell command in a process group of its own, with the server as its parent. With a command running, closing stdin made the server exit 0 and took the command with it; SIGTERM to the server, SIGTERM to its group, and SIGKILL to its group each left the command running.
  • When the approval policy asks, the server sends a request (item/commandExecution/requestApproval, numeric id starting at 0) and the turn waits. The reply is {"id":0,"result":{"decision":"decline"}}, after which the server sends a serverRequest/resolved notification.
  • The server logs to stderr, in colour, including MCP startup errors.
  • Closing stdin ends the server with status 0. That took 5 seconds in one capture where no thread had been started, and milliseconds after a turn.
  • A startup failure (an unknown -c key under --strict-config) writes one line to stderr and exits 1.

§Assumed, not verified

  • Server-initiated requests may use string ids; RequestId accepts both.
  • A JSON object with neither method nor a matching response id is logged and ignored. A line that does not start with { is ignored, as streaming ignores it. A line that starts with { and is not valid JSON ends the session.

Structs§

AgentMessage
A finished message from the model, decoded from an item/completed notification by Notification::agent_message.
AppServer
A running codex app-server.
AppServerBuilder
Builds and starts an AppServer.
AppServerHandle
A cloneable handle for sending to the server.
Notification
A message the server sent without being asked.
ServerInfo
What the server reported about itself in the initialize response.
ServerRequest
A request the server sent and is waiting on, such as an approval.
Thread
A thread, as returned by thread/start.
ThreadStartParams
Parameters for thread/start.
Turn
A turn, as reported in turn/start responses and turn/completed notifications.
TurnCompleted
The payload of a turn/completed notification.
TurnStartParams
Parameters for turn/start.

Enums§

AppServerLimit
One of the opt-in transport limits, as reported by Error::AppServerLimitExceeded.
AppServerTransport
How an AppServer reaches the server, and so what it owns.
RequestId
A JSON-RPC request id.
ServerMessage
One message from the server that is not the answer to a request.
TurnStatus
How a turn is going, from its status field.
UserInput
One piece of user input for a turn.