Rust CLI Entrypoints
Overview
The primary Rust CLI binary starts in codex-rs/…/main.rs. Its main() first initializes build metadata with codex_build_info::initialize!(), consumes the app-server remote-control disable environment flag, then enters codex_arg0::arg0_dispatch_or_else. That wrapper is the pre-parser startup gate: codex-rs/…/lib.rs detects special invocation modes from argv0/argv1, loads ~/…/.env with CODEX_ keys filtered out, prepares helper aliases on PATH, and runs the async CLI dispatcher on a Tokio runtime created on a controlled-stack codex-main thread.
codex-rs/…/lib.rs owns the single-binary routing tricks used before normal clap parsing. If argv0 is codex-linux-sandbox, it jumps directly to the Linux sandbox main; if argv0 is apply_patch or applypatch, it runs the apply-patch CLI. Hidden argv1 sentinels route to Windows MXC, Unix exec helper, filesystem helper, Windows sandbox wrapper, or core apply-patch mode. Regular invocations continue after load_dotenv() and alias setup. Alias setup creates a locked per-session directory under $CODEX_HOME/tmp/arg0-<os> containing apply_patch/applypatch and, on Linux, codex-linux-sandbox; it also prepends any packaged codex-path directory from codex-rs/…/lib.rs before the existing PATH. The resulting Arg0DispatchPaths carries codex_self_exe and codex_linux_sandbox_exe to downstream TUI, exec, app-server, and exec-server code that may need to re-exec the current binary.
After arg0 setup, dispatch_cli() in codex-rs/…/main.rs parses the large MultitoolCli with config_override_args::try_parse_from() from codex-rs/…/config_override_args.rs. That wrapper uses clap for typed parsing, validates queue options, and then recollects root -c key=value overrides when a subcommand is present so root overrides can be prepended later with lower precedence than subcommand-scoped overrides. Root --enable/--disable feature toggles are converted into config overrides before dispatch. Root remote endpoint/auth-token flags are accepted only for interactive flows and are explicitly rejected for most subcommands by reject_remote_mode_for_subcommand().
The default path (codex with no subcommand) and codex agents return a TUI future from dispatch_cli() rather than running it inline. run_interactive_tui() in codex-rs/…/main.rs normalizes prompt newlines, reads terminal metadata via codex-rs/…/lib.rs, refuses or warns on TERM=dumb depending on TTY availability and confirmation, resolves any remote endpoint, enforces TTYs for local agents overview, and then calls codex_tui::run_main(...) with the merged TuiCli, Arg0DispatchPaths, default loader overrides, and optional remote endpoint. run_tui_with_recovery() wraps that handoff with local SQLite startup recovery: lock errors produce guidance, recoverable damaged DBs are backed up once before retrying, and unrecoverable errors become fatal app exits. handle_app_exit() prints TUI exit messages and can run update actions, including daemon handoff through the retained launching CLI path.
Runtime wrapper subcommands in codex-rs/…/main.rs reshape arguments before handing off. codex resume and codex fork merge root interactive flags with subcommand-scoped TuiCli flags in finalize_resume_interactive() and finalize_fork_interactive(), then launch the same TUI startup function with picker/last/session fields set. codex archive, delete, unarchive, and queue call TUI session-management helpers after applying compatible shared options. codex exec and codex review pass root options, strict config, feature/config overrides, remote settings where allowed, and Arg0DispatchPaths to codex_exec::run_main. codex app-server builds app-server runtime options and calls codex_app_server::run_main_with_transport_options; its daemon, proxy, and schema-generation subcommands route to app-server daemon/control/protocol helpers instead of the TUI. codex exec-server delegates to codex_exec_server_cli::ExecServerCommand::run, sharing the standalone executor path described below.
Non-interactive utility subcommands also live in codex-rs/…/main.rs but stop before the agent UI: login/logout and git credential use reexports from codex-rs/…/lib.rs; MCP, plugin, marketplace, sandbox, doctor, cloud, update, completion, feature editing, debug, migration, and proxy commands each reject unsupported root remote/strict-config combinations and call their owning crates. codex apply is backed by codex-rs/…/apply_command.rs: it loads config from CLI overrides, fetches /wham/tasks/{task_id} through the ChatGPT backend client in codex-rs/…/chatgpt_client.rs, extracts the current PR diff from codex-rs/…/get_task.rs, and applies it with codex_git_utils::apply_git_patch. The broader codex-rs/…/connectors.rs module provides ChatGPT connector-directory and metadata calls used by UI/runtime code; it uses the same standalone-auth pattern and account-scoped caching, but it is not itself a top-level binary entrypoint.
Build/install metadata is resolved early and reused by startup paths. codex-rs/…/lib.rs stores a process-global BuildInfo; initialize!() stamps STABLE_GIT_COMMIT at the final executable call site, while build.rs stamps CODEX_BUILD_TARGET. BuildInfo::resolve() reads InstallContext::current().package_manifest() when the running executable is inside a recognized package layout, otherwise reports a source build (0.0.0 plus the commit/dev marker). codex-rs/…/lib.rs detects package layouts from the current executable, including bin/, codex-resources/, codex-path/, macOS CodexCLI.app/Contents/MacOS, and Windows package-root entrypoints validated by codex-package.json. It also classifies install method from package paths under $CODEX_HOME/packages/standalone/releases, npm/bun/pnpm/Vite+ environment markers, and Homebrew prefixes, and resolves bundled resources such as rg and codex-code-mode-host.
The standalone executor binary starts in codex-rs/…/main.rs, initializes build info, and calls codex_exec_server_cli::run_standalone() in codex-rs/…/lib.rs. It intentionally reuses codex_arg0::arg0_dispatch_or_else so helper modes, .env loading, PATH aliases, and Arg0DispatchPaths match the full codex binary. Its clap surface is smaller: root config overrides plus ExecServerCommand from codex-rs/…/command.rs. The same ExecServerCommand::run() is also used by codex exec-server, so changes to executor startup affect both invocation modes.
codex-rs/…/command.rs turns CLI flags into codex_exec_server::ExecServerRuntimeOptions, requiring codex_self_exe and optionally using codex_linux_sandbox_exe. Local mode loads config best-effort unless --strict-config is set, initializes telemetry from codex-rs/…/exec_server_telemetry.rs, picks --listen or codex_exec_server::DEFAULT_LISTEN_URL, and calls codex_exec_server::run_main_with_telemetry. Remote registration mode requires --remote plus --environment-id, loads cloud config when appropriate via codex-rs/…/config.rs, chooses auth from registration bearer stdin, rotating executor credential stdin, ChatGPT token stdin, AWS SigV4, Agent Identity, or stored ChatGPT/API-key credentials, and then runs either a registered remote environment or a forward bridge. Parent lifetime can be tied to stdin close; exec_server_telemetry::run_until_shutdown() handles parent disconnect and Ctrl-C/SIGTERM, with graceful shutdown for remote registration and immediate shutdown for local serving.
Terminal detection in codex-rs/…/lib.rs is environment-only by design. It caches a TerminalInfo, detects multiplexers first, prioritizes TERM_PROGRAM unless it is tmux, then checks emulator-specific variables and finally TERM. The CLI uses this before TUI launch to guard TERM=dumb; the same crate also formats sanitized user-agent terminal tokens for telemetry and backend calls.
Coupling
- If codex-rs/…/main.rs adds a startup path that can spawn child helpers, pass through
Arg0DispatchPathsfrom codex-rs/…/lib.rs; usingstd::env::current_exe()directly can point at a test harness or miss the per-sessioncodex-linux-sandboxalias. - If adding a subcommand to
Subcommandin codex-rs/…/main.rs, update the post-parse policy helpers in the same file (reject_remote_mode_for_subcommand,unsupported_subcommand_name_for_strict_config,profile_v2_for_subcommand, and worktree handling as applicable). Clap may accept root flags before the dispatcher knows the selected subcommand, so unsupported combinations must be rejected explicitly. - If changing root
-coverride parsing in codex-rs/…/config_override_args.rs, verify subcommand precedence in codex-rs/…/main.rs: root overrides are prepended so subcommand-scoped overrides win, while feature toggles are folded into the same root override list. - If changing alias names or hidden argv sentinels in codex-rs/…/lib.rs, also verify sandbox/apply-patch/exec-server call sites outside this doc's owned crates that re-exec those modes; these dispatch before clap, so broken names produce confusing normal-CLI parsing failures or helper startup failures.
- If changing package layout detection in codex-rs/…/lib.rs, verify codex-rs/…/lib.rs PATH prepending and codex-rs/…/lib.rs manifest version resolution. The package
codex-pathdirectory influences which bundled helper binaries are found during startup. - If changing
ExecServerCommandin codex-rs/…/command.rs, test bothcodex exec-serverand thecodex-exec-serverstandalone binary. They shareExecServerCommand::run()but parse root config overrides through different clap roots (codex-rs/…/main.rs versus codex-rs/…/lib.rs). - If changing codex-rs/…/lib.rs, verify
run_interactive_tui()in codex-rs/…/main.rs;TerminalName::Dumbhas launch-blocking behavior, while other names mainly affect metadata/user-agent formatting.
Risks
- codex-rs/…/lib.rs mutates
PATHand loads dotenv values before the Tokio runtime starts. If new startup work creates threads beforearg0_dispatch()completes, environment mutation becomes racy and helper aliases may not be visible to child processes. - codex-rs/…/lib.rs creates locked helper directories under
$CODEX_HOME/tmp/arg0-<os>and janitors stale entries. If lock handling or platform-specific roots regress, live helper aliases can disappear while a TUI/exec-server session still needs to re-exec sandbox or apply-patch helpers. - codex-rs/…/main.rs keeps large futures boxed or returned from
dispatch_cli()to avoid stack bloat. Inliningcodex_tui::run_main,codex_exec::run_main, or other large async bodies back into the dispatcher can reintroduce oversized futures before control reaches the UI. - codex-rs/…/exec_server_credential.rs treats malformed, oversized, wrong-environment, expired, or closed credential frames as executor-stopping conditions. If the newline-delimited JSON frame contract changes without parent-launcher updates, remote executor registration can succeed but later requests will fail authentication or shut down.