10. Running Commands

Every shell command the model runs goes through one mechanism, unified exec. exec_command starts a process, waits a bounded time for output, and returns either an exit code or a session ID; write_stdin talks to a process that is still running. Codex keeps at most 64 such processes, bounds every output to a 1 MiB head and tail, and truncates the text a Direct-mode model reads to a token budget.

A coding agent runs builds, tests, searches, and long-lived servers. Some finish in milliseconds; some never finish. Waiting for every exit would hang on a dev server, and returning at once would lose a quick test’s output. Codex answers with a yield window: wait a while, return what arrived, and keep the process alive if it is still running.

This chapter covers the two shell tools, how Codex picks and wraps your shell, the environment a command sees, the unified exec manager with its limits and buffers, the truncation the model sees, the capture path in exec.rs, and your own ! commands. Approvals and sandboxes belong to Chapters 13 and 14.

The picture

A unified exec process starts with a reserved ID and an approval decision, collects output until its yield deadline, and either exits early with an exit code or is stored with a session ID; the model polls a stored process with write_stdin until an exit is seen, and a stored process can also be pruned when 64 are stored, or terminated by cleanup, shutdown, or a one-shot timeout.

A call to exec_command reserves a process ID, then passes through approval and sandbox selection; a refusal ends there. The spawned process writes into buffers while the call waits for its yield deadline. If it exits first, the call returns its exit code. If it is still running, the manager stores it and the call returns a session ID. Each later write_stdin call drains new output and either finds the process still running or sees its exit. A stored process can also leave without exiting: the manager prunes one when 64 are stored, and a clean request or session shutdown terminates them all.

Two tools and an alias

exec_command and write_stdin

At this commit Codex has exactly two shell tools, both function tools built in core/src/tools/handlers/shell_spec.rs. exec_command requires cmd and accepts workdir, tty, yield_time_ms, max_output_tokens, shell, login, and the approval fields sandbox_permissions, justification, and prefix_rule. write_stdin requires session_id and accepts chars, yield_time_ms, and max_output_tokens; empty chars polls without writing. Defaults live in core/src/tools/handlers/unified_exec.rs: yield_time_ms is 10,000 for exec_command and 250 for write_stdin, and tty is false.

The tty flag asks for a pseudo-terminal (PTY), and its default deserves attention. The tool description says “Runs a command in a PTY”, but a call that omits tty gets plain pipes. Pipes keep stdin closed, so a later write_stdin with input fails with “stdin is closed for this session; rerun exec_command with tty=true to keep stdin open”. The one exception is Ctrl-C: on a pipe session, write_stdin turns the character \u{3} into an interrupt.

Where shell and shell_command went

The names shell and shell_command survive only as configuration values. ConfigShellToolType in codex-rs/protocol/src/openai_models.rs has two variants:

pub enum ConfigShellToolType {
    #[serde(alias = "default", alias = "local", alias = "shell_command")]
    UnifiedExec,
    Disabled,
}

Every bundled model in models-manager/models.json declares "shell_type": "shell_command", and serde reads that value as UnifiedExec. No handler named shell or shell_command is registered, so a replayed call to one gets unsupported call back (Chapter 9).

One-shot mode

add_shell_tools registers ExecCommandHandler::one_shot instead when the unified_exec feature is off, which a code comment says only managed requirements can force. The one-shot spec drops tty and yield_time_ms, adds timeout_ms (“Defaults to 10000 ms”), and removes session_id from the output schema. The command still runs through the unified exec manager, in exec_command_to_completion, but the call waits for exit; at the timeout the manager marks the process timed out and terminates it.

Building the command line

Finding your shell

At session start, Session takes the user shell from a configured override or from default_user_shell in codex-rs/shell-command/src/shell_detect.rs. On Unix it reads your login shell from the password database with getpwuid_r, not from $SHELL. If that shell is not usable, macOS falls back to zsh then bash, Linux to bash then zsh, and both to /bin/sh. Windows prefers PowerShell and falls back to cmd.exe. The model may name another shell in shell, but get_shell_by_model_provided_path uses that path only to choose a shell type, then finds the executable itself.

Login shells

Shell::derive_exec_args in core/src/shell.rs turns the script into an argument vector:

Shell Login Not login
bash, zsh, sh [path, "-lc", cmd] [path, "-c", cmd]
PowerShell [path, "-Command", cmd] [path, "-NoProfile", "-Command", cmd]
cmd [path, "/c", cmd] [path, "/c", cmd]

get_command decides the login flag. An omitted login inherits allow_login_shell, which defaults to true. A call that asks for login: true where the environment forbids login shells fails with “login shell is disabled by config; omit login or set it to false.” Managed requirements can pin allow_login_shell for an organization.

Shell snapshots

A login shell sources your profile on every command, which is slow and sometimes noisy. A shell snapshot pays that cost once. With the shell_snapshot feature on, ShellSnapshot::build in core/src/shell_snapshot.rs runs your shell once, captures its functions, options, aliases, and exports, validates the result, and writes it under shell_snapshots/ in the Codex home. The capture script for zsh prints unalias -a, then functions, setopt lines, and alias -L; the bash script uses declare -f and alias -p. Snapshot creation has a 10-second timeout, and a cleanup pass deletes snapshots whose thread has been idle for three days.

maybe_wrap_shell_lc_with_snapshot in core/src/tools/runtimes/mod.rs then rewrites each login command, as its doc comment shows:

shell -lc "<script>"
=> user_shell -c ". SNAPSHOT (best effort); exec shell -c <script>"

The command runs in a non-login shell that sources the snapshot first. The rewrite applies only to -lc commands (and to -c commands while the network proxy’s credential broker is active), and it is a no-op on Windows, for remote environments, when the snapshot file is missing, and when the command’s working directory differs from the one the snapshot was taken in. One cost follows: commands see your profile as it was when the snapshot was taken.

The environment a command sees

Codex builds every child environment from scratch. populate_env in codex-rs/protocol/src/shell_environment.rs applies your [shell_environment_policy] in six steps:

  1. Start from inherit: all (the default), core (on Unix PATH, SHELL, TMPDIR, TEMP, TMP, HOME, LANG, LC_ALL, LC_CTYPE, LOGNAME, USER), or none.
  2. Unless ignore_default_excludes is true, drop names matching *KEY*, *SECRET*, or *TOKEN*, case-insensitively.
  3. Drop names matching exclude.
  4. Insert the set overrides.
  5. If include_only is set, keep only matching names.
  6. Add CODEX_THREAD_ID when a thread ID is given.

Step 2 surprises people: ignore_default_excludes defaults to true, both in ShellEnvironmentPolicy::default and when the TOML omits it. By default, therefore, variables such as GITHUB_TOKEN do reach commands. Set ignore_default_excludes = false to filter them. A short list of Codex-internal secrets, NON_INHERITABLE_ENV_VARS, is removed whatever the policy says.

open_session_with_sandbox in core/src/unified_exec/process_manager.rs then adds Codex’s own variables: CODEX_THREAD_ID, CODEX_TOOL_CALL_ID, CODEX_SESSION_ID, CODEX_VERSION, CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS=1, and CODEX_PERMISSION_PROFILE. The doc comment in core/src/exec_env.rs warns that child processes can overwrite the last one, so it “must not be treated as proof of enforcement.” Last, apply_unified_exec_env overwrites ten variables so tools produce plain, non-interactive output: NO_COLOR=1, TERM=dumb, LANG, LC_CTYPE, and LC_ALL set to C.UTF-8, an empty COLORTERM, PAGER, GIT_PAGER, and GH_PAGER set to cat, and CODEX_CI=1.

Unified exec sessions

Spawning: a PTY or pipes

After the orchestrator approves and picks a sandbox, the manager starts the process. A local process spawns through codex_sandboxing::spawn_process with tty and stdin_open: tty, so a pipe session never has an open stdin. A remote environment, or a request that uses an executor-side snapshot, starts through the exec-server backend instead. The manager reserves the ID before spawning with allocate_process_id: a random number from 1,000 to 99,999 in production, and a counter from 1,000 in tests.

Yield windows

The initial call waits for output until a deadline set by clamp_yield_time in core/src/unified_exec/mod.rs:

pub(crate) fn clamp_yield_time(yield_time_ms: u64) -> u64 {
    let yield_time_ms = if cfg!(windows) {
        yield_time_ms.max(WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS)
    } else {
        yield_time_ms
    };
    yield_time_ms.clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS)
}

where is the requested yield_time_ms (default 10,000), and is WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS, 10,000 on Windows and 0 elsewhere. The bounds 250 and 30,000 are MIN_YIELD_TIME_MS and MAX_YIELD_TIME_MS.

write_stdin uses two rules, because a poll and a keystroke want different waits. Its code comment says non-empty writes “keep a fixed max cap so interactive stdin remains responsive”:

where defaults to 250, 5,000 is MIN_EMPTY_YIELD_TIME_MS, and is the config key background_terminal_max_timeout (default 300,000) raised to at least 5,000. An empty poll therefore waits at least five seconds. The deadline also moves forward by any time the session spends paused for an elicitation. Each poll drains only the output that arrived since the previous call.

The process store: 64 processes, newest 8 protected

A process still running at its deadline goes into ProcessStore, keyed by its ID and stamped with last_used, which every later write_stdin refreshes. Before inserting, prune_processes_if_needed checks the count against MAX_UNIFIED_EXEC_PROCESSES, 64, and process_id_to_prune_from_meta picks a victim:

where is the set of stored processes, applied only when ; is the last-use time of ; is the protected set; and is the process to evict. The manager terminates the victim. It skips a candidate whose interaction lock is held by write_stdin or a terminal event, so a code comment calls 64 a soft cap. This is least-recently-used eviction with a recency shield: the processes the model is using survive a burst of new ones.

Nothing in the turn lifecycle terminates stored processes. They end when they exit, when they are pruned, when a client sends Op::CleanBackgroundTerminals or terminates one by ID through the app server’s experimental thread/backgroundTerminals/terminate, or at session shutdown through terminate_all_processes.

Output buffering: head and tail

Each process keeps two HeadTailBuffer values in OutputBuffers (core/src/unified_exec/process.rs): pending, which the next call drains, and transcript, the record for the completion event. Both have capacity = UNIFIED_EXEC_OUTPUT_MAX_BYTES, 1 MiB. The buffer in codex-rs/utils/head-tail-buffer/src/lib.rs splits that capacity evenly:

where is the head budget, filled by the first bytes and then frozen; is the tail budget, which keeps the newest bytes and drops older ones; is the total bytes written; and is the omitted count. When the rendered text carries ... {ω} bytes omitted ... at the gap. The design keeps a build’s first errors and its final summary in bounded memory; the middle is lost for good. Clients see the stream live: a watcher emits ExecCommandOutputDelta events of at most 8,192 bytes each, up to 10,000 events per call.

What the model reads

The response header

Most bundled models run in code mode (Chapter 9): 13 of the 14 in models.json set "tool_mode": "code_mode_only". For them, exec_command is reachable only as tools.exec_command inside the exec JavaScript tool, and its result reaches the script as JSON from code_mode_result, with fields chunk_id, wall_time_seconds, exit_code, session_id, original_token_count, and output. That output is truncated only when the script passes max_output_tokens; the model reads whatever the script emits, under code mode’s own limits (Chapter 12). The rest of this section describes the text a Direct-mode model, such as gpt-5.5, receives.

ExecCommandToolOutput::response_header in core/src/tools/context.rs prefixes the output with up to five lines: Chunk ID (six random hex characters), Wall time to four decimals, Process exited with code N or Process running with session ID N, Original token count, and Output:.

Token truncation

The output then shrinks to a token budget. Codex estimates tokens as bytes divided by 4, rounded up. model_output_policy picks the smaller of the call’s budget and the model’s own truncation policy:

where is max_output_tokens (default DEFAULT_MAX_OUTPUT_TOKENS, 10,000), is the model’s limit (every bundled model uses {"mode": "tokens", "limit": 10000}, which tool_output_token_limit can override), is the byte budget, is the output length in bytes, and the result keeps the first and last bytes around the marker …n tokens truncated…. Above the snippet, formatted_truncate_text adds Warning: truncated output (original token count: N) and Total output lines: L. A model cannot raise its budget by asking: max_output_tokens only lowers it.

One more limit applies when the output item enters history. record_item_with_metadata truncates every function output to the model policy times a serialization allowance of 1.2, and response_text reserves room for its own header inside that limit, so the output is not truncated twice:

where is the byte room left for output and is the header length. With the bundled limit, is 48,000 bytes minus the header.

A worked example

The integration test core/tests/suite/unified_exec.rs sends this direct call through a mock model:

{"cmd": "printf 'token one token two token three token four token five token six token seven'",
 "yield_time_ms": 500, "max_output_tokens": 6}

The output is 75 bytes, so the original count is tokens. With , equation (10.5) gives , , and . The function_call_output item, computed from the code rather than captured from a run, with an illustrative chunk ID and wall time, is:

{"type": "function_call_output", "call_id": "uexec-metadata",
 "output": "Chunk ID: 9c1e4a\nWall time: 0.0518 seconds\nProcess exited with code 0\nOriginal token count: 19\nOutput:\nWarning: truncated output (original token count: 19)\nTotal output lines: 1\n\ntoken one to…13 tokens truncated… token seven"}

The test checks the stable parts: the chunk ID shape, exit code 0, no session ID, the marker, and a count above 6.

exec.rs: the capture path

core/src/exec.rs is not the model’s shell path at this commit; unified exec is. It serves your ! commands and internal helpers through capture_sandbox_request. Its child process comes from spawn_child_async in core/src/spawn.rs, which clears the environment and sets only the computed map, adds CODEX_SANDBOX_NETWORK_DISABLED=1 when the network is off, gives the child a null stdin so tools like ripgrep do not wait for input, asks Linux to send SIGTERM if Codex dies, and closes inherited descriptors on macOS.

ExecParams carries an ExecExpiration: a timeout, the 10,000 ms default, a cancellation token, or both. On timeout exec kills the process group, and finalize_exec_result reports exit code 124 and a SandboxErr::Timeout; the formatted output starts with “command timed out after N milliseconds”. Readers keep draining pipes to avoid back-pressure, but stop waiting after IO_DRAIN_TIMEOUT_MS, 2,000 ms, because grandchildren can hold pipes open. Under the default ExecCapturePolicy::ShellTool, each stream keeps its first 1 MiB, and the combined output is cut by aggregate_output:

where and are the stdout and stderr lengths, is 1 MiB, and and are the bytes kept. The code comment states the intent: reserve a third for stdout, give stderr the rest, and return unused stderr room to stdout. This path keeps only heads, while unified exec keeps heads and tails.

Your ! commands

When you type !ls in the terminal UI, the composer sends Op::RunUserShellCommand. execute_user_shell_command in core/src/tasks/user_shell.rs builds a login-shell command, wraps it with the snapshot, and runs it through exec.rs with SandboxType::None, PermissionProfile::Disabled, and a default timeout of one hour (USER_SHELL_TIMEOUT_MS). A comment calls it “the explicit full-access escape hatch”, so it also strips any managed network proxy. You typed the command, so no approval applies.

The result enters history as a user-role fragment, so the model knows what you ran:

<user_shell_command>
<command>
ls
</command>
<result>
Exit code: 0
Duration: 0.0123 seconds
Output:
Cargo.toml
</result>
</user_shell_command>

Its output is truncated to the model’s policy by format_exec_output_str. When a turn is already running, the record is injected without starting a new turn.

Status at commit 081295be9d. shell_tool, unified_exec, unified_exec_tty, and shell_snapshot: STABLE, on by default. shell_snapshot_v2 (executor-side snapshots): UNDER DEVELOPMENT, off. login_shell_package_path: EXPERIMENTAL, off by default. One-shot exec_command: IMPLEMENTED, used only when managed requirements disable unified exec. Shell snapshot wrapping: PLATFORM-SPECIFIC, Unix only. Windows initial yield floor of 10 seconds: PLATFORM-SPECIFIC. Read in code, not run.

What breaks

Symptom Cause Check
stdin is closed for this session; rerun exec_command with tty=true ... Session started with pipes, the default Pass "tty": true
Unknown process id N from write_stdin Process exited and was released, or was pruned prune_processes_if_needed
login shell is disabled by config; ... Model asked for login: true where it is forbidden allow_login_shell
Secrets such as GITHUB_TOKEN visible to commands ignore_default_excludes defaults to true [shell_environment_policy]
Output contains ... N bytes omitted ... Process wrote over 1 MiB between polls UNIFIED_EXEC_OUTPUT_MAX_BYTES
Output ends in …N tokens truncated… Over max_output_tokens or the model limit tool_output_token_limit
Profile change ignored Commands source an older snapshot Start a new session
! command ran with full access User commands bypass the sandbox by design user_shell.rs

Code map

What it is Where it lives Identifier
Shell tool specs codex:codex-rs/core/src/tools/handlers/shell_spec.rs create_exec_command_tool
Argument defaults and login rule codex:codex-rs/core/src/tools/handlers/unified_exec.rs get_command
Yield clamp and limits codex:codex-rs/core/src/unified_exec/mod.rs clamp_yield_time
Process store and eviction codex:codex-rs/core/src/unified_exec/process_manager.rs process_id_to_prune_from_meta
Head and tail buffer codex:codex-rs/utils/head-tail-buffer/src/lib.rs HeadTailBuffer
Environment policy codex:codex-rs/protocol/src/shell_environment.rs populate_env
Shell snapshot codex:codex-rs/core/src/shell_snapshot.rs SNAPSHOT_RETENTION
Capture path and timeouts codex:codex-rs/core/src/exec.rs aggregate_output

Recall check

What happens to an exec_command whose process outlives its yield window?
The manager stores it and the output carries Process running with session ID N for write_stdin.

What are the bounds on the initial yield window?
250 to 30,000 ms, with a 10,000 ms floor on Windows.

Which stored process is evicted when the store holds 64?
The least recently used exited process outside the newest 8, or else the least recently used live one outside them.

How much command output does unified exec keep?
The first 512 KiB and the last 512 KiB, with an omitted-bytes marker between.

Does max_output_tokens let the model see more output than its model limit?
No; Codex uses the smaller of the requested budget and the model’s truncation policy.