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, elsewhere when AppServer::next_message returns the error. 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.

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.

§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§

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.