跳到主要内容

Command line options

Options and flags for the Codex terminal client

How to read this reference

This page catalogs every documented Codex CLI command and flag. Use the interactive tables to search by key or description. Each section indicates whether the option is stable or experimental and calls out risky combinations.

The CLI inherits most defaults from ~/.codex/config.toml. Any -c key=value overrides you pass at the command line take precedence for that invocation. See Config basics for more information.

Global flags

KeyTypeDefaultDescription
PROMPTstringOptional text instruction to start the session. Omit to launch the TUI without a pre-filled message.
--image, -ipath[,path...]Attach one or more image files to the initial prompt. Separate multiple paths with commas or repeat the flag.
--model, -mstringOverride the model set in configuration (for example gpt-5.4).
--ossbooleanfalseUse the local open source model provider (equivalent to -c model_provider="oss"). Validates that Ollama is running.
--profile, -pstringConfiguration profile name to load from ~/.codex/config.toml.
--sandbox, -sread-only | workspace-write | danger-full-accessSelect the sandbox policy for model-generated shell commands.
--ask-for-approval, -auntrusted | on-request | neverControl when Codex pauses for human approval before running a command. on-failure is deprecated; prefer on-request for interactive runs or never for non-interactive runs.
--dangerously-bypass-approvals-and-sandbox, --yolobooleanfalseRun every command without approvals or sandboxing. Only use inside an externally hardened environment.
--cd, -CpathSet the working directory for the agent before it starts processing your request.
--searchbooleanfalseEnable live web search (sets web_search = "live" instead of the default "cached").
--add-dirpathGrant additional directories write access alongside the main workspace. Repeat for multiple paths.
--no-alt-screenbooleanfalseDisable alternate screen mode for the TUI (overrides tui.alternate_screen for this run).
--remotews://host:port | wss://host:portConnect the interactive TUI to a remote app-server WebSocket endpoint. Supported for codex, codex resume, and codex fork; other subcommands reject remote mode.
--remote-auth-token-envENV_VARRead a bearer token from this environment variable and send it when connecting with --remote. Requires --remote; tokens are only sent over wss:// URLs or ws:// URLs whose host is localhost, 127.0.0.1, or ::1.
--enablefeatureForce-enable a feature flag (translates to -c features.=true). Repeatable.
--disablefeatureForce-disable a feature flag (translates to -c features.=false). Repeatable.
--config, -ckey=valueOverride configuration values. Values parse as JSON if possible; otherwise the literal string is used.

These options apply to the base codex command and propagate to each subcommand unless a section below specifies otherwise. When you run a subcommand, place global flags after it (for example, codex exec --oss ...) so Codex applies them as intended.

Command overview

The Maturity column uses feature maturity labels such as Experimental, Beta, and Stable. See Feature Maturity for how to interpret these labels.

KeyMaturityDefaultDescription
codexstableLaunch the terminal UI. Accepts the global flags above plus an optional prompt or image attachments.
codex app-serverexperimentalLaunch the Codex app server for local development or debugging over stdio, WebSocket, or a Unix socket.
codex remote-controlexperimentalEnsure the local app-server daemon is running with remote-control support enabled.
codex appstableLaunch the Codex desktop app on macOS or Windows. On macOS, Codex can open a workspace path; on Windows, Codex prints the path to open.
codex debug app-server send-message-v2experimentalDebug app-server by sending a single V2 message through the built-in test client.
codex debug modelsexperimentalPrint the raw model catalog Codex sees, including an option to inspect only the bundled catalog.
codex applystableApply the latest diff generated by a Codex Cloud task to your local working tree. Alias: codex a.
codex cloudexperimentalBrowse or execute Codex Cloud tasks from the terminal without opening the TUI. Alias: codex cloud-tasks.
codex completionstableGenerate shell completion scripts for Bash, Zsh, Fish, or PowerShell.
codex featuresstableList feature flags and persistently enable or disable them in config.toml.
codex execstableRun Codex non-interactively. Alias: codex e. Stream results to stdout or JSONL and optionally resume previous sessions.
codex execpolicyexperimentalEvaluate execpolicy rule files and see whether a command would be allowed, prompted, or blocked.
codex loginstableAuthenticate Codex using ChatGPT OAuth, device auth, an API key, or an access token piped over stdin.
codex logoutstableRemove stored authentication credentials.
codex mcpexperimentalManage Model Context Protocol servers (list, add, remove, authenticate).
codex plugin marketplaceexperimentalAdd, upgrade, or remove plugin marketplaces from Git or local sources.
codex mcp-serverexperimentalRun Codex itself as an MCP server over stdio. Useful when another agent consumes Codex.
codex resumestableContinue a previous interactive session by ID or resume the most recent conversation.
codex forkstableFork a previous interactive session into a new thread, preserving the original transcript.
codex sandboxexperimentalRun arbitrary commands inside Codex-provided macOS, Linux, or Windows sandboxes.
codex updatestableCheck for and apply a Codex CLI update when the installed release supports self-update.

Command details

codex (interactive)

Running codex with no subcommand launches the interactive terminal UI (TUI). The agent accepts the global flags above plus image attachments. Web search defaults to cached mode; use --search to switch to live browsing. For low-friction local work, use --sandbox workspace-write --ask-for-approval on-request.

Use --remote ws://host:port or --remote wss://host:port to connect the TUI to an app server started with codex app-server --listen ws://IP:PORT. Add --remote-auth-token-env <ENV_VAR> when the server requires a bearer token for WebSocket authentication.

codex app-server

Launch the Codex app server locally. This is primarily for development and debugging and may change without notice.

KeyTypeDefaultDescription
--listenstdio:// | ws://IP:PORT | unix:// | unix://PATH | offstdio://Transport listener URL. Use stdio:// for JSONL, ws://IP:PORT for a TCP WebSocket endpoint, unix:// for the default Unix socket, unix://PATH for a custom Unix socket, or off to disable the local transport.
--ws-authcapability-token | signed-bearer-tokenAuthentication mode for app-server WebSocket clients. If omitted, WebSocket auth is disabled; non-local listeners warn during startup.
--ws-token-fileabsolute pathFile containing the shared capability token. Required with --ws-auth capability-token.
--ws-shared-secret-fileabsolute pathFile containing the HMAC shared secret used to validate signed JWT bearer tokens. Required with --ws-auth signed-bearer-token.
--ws-issuerstringExpected iss claim for signed bearer tokens. Requires --ws-auth signed-bearer-token.
--ws-audiencestringExpected aud claim for signed bearer tokens. Requires --ws-auth signed-bearer-token.
--ws-max-clock-skew-secondsnumber30Clock skew allowance when validating signed bearer token exp and nbf claims. Requires --ws-auth signed-bearer-token.
--analytics-default-enabledbooleanfalseDefaults analytics to enabled for first-party app-server clients unless the user opts out in config.

codex app-server --listen stdio:// keeps the default JSONL-over-stdio behavior. --listen ws://IP:PORT enables WebSocket transport for app-server clients. The server accepts ws:// listen URLs; use TLS termination or a secure proxy when clients connect with wss://. Use --listen unix:// to accept WebSocket handshakes on Codex's default Unix socket, or --listen unix:///absolute/path.sock to choose a socket path. If you generate schemas for client bindings, add --experimental to include gated fields and methods.

codex remote-control

Ensure the app-server daemon is running with remote-control support enabled. Managed remote-control clients and SSH remote workflows use this command; it's not a replacement for codex app-server --listen when you are building a local protocol client.

codex app

Launch Codex Desktop from the terminal on macOS or Windows. On macOS, Codex can open a specific workspace path; on Windows, Codex prints the path to open.

KeyTypeDefaultDescription
PATHpath.Workspace path for Codex Desktop. On macOS, Codex opens this path; on Windows, Codex prints the path.
--download-urlurlAdvanced override for the Codex desktop installer URL used during install.

codex app opens an installed Codex Desktop app, or starts the installer when the app is missing. On macOS, Codex opens the provided workspace path; on Windows, it prints the path to open after installation.

codex debug app-server send-message-v2

Send one message through app-server's V2 thread/turn flow using the built-in app-server test client.

KeyTypeDefaultDescription
USER_MESSAGEstringMessage text sent to app-server through the built-in V2 test-client flow.

This debug flow initializes with experimentalApi: true, starts a thread, sends a turn, and streams server notifications. Use it to reproduce and inspect app-server protocol behavior locally.

codex debug models

Print the raw model catalog Codex sees as JSON.

KeyTypeDefaultDescription
--bundledbooleanfalseSkip refresh and print only the model catalog bundled with the current Codex binary.

Use --bundled when you want to inspect only the catalog bundled with the current binary, without refreshing from the remote models endpoint.

codex apply

Apply the most recent diff from a Codex cloud task to your local repository. You must authenticate and have access to the task.

KeyTypeDefaultDescription
TASK_IDstringIdentifier of the Codex Cloud task whose diff should be applied.

Codex prints the patched files and exits non-zero if git apply fails (for example, due to conflicts).

codex cloud

Interact with Codex cloud tasks from the terminal. The default command opens an interactive picker; codex cloud exec submits a task directly, and codex cloud list returns recent tasks for scripting or quick inspection.

KeyTypeDefaultDescription
QUERYstringTask prompt. If omitted, Codex prompts interactively for details.
--envENV_IDTarget Codex Cloud environment identifier (required). Use codex cloud to list options.
--attempts1-41Number of assistant attempts (best-of-N) Codex Cloud should run.

Authentication follows the same credentials as the main CLI. Codex exits non-zero if the task submission fails.

codex cloud list

List recent cloud tasks with optional filtering and pagination.

KeyTypeDefaultDescription
--envENV_IDFilter tasks by environment identifier.
--limit1-2020Maximum number of tasks to return.
--cursorstringPagination cursor returned by a previous request.
--jsonbooleanfalseEmit machine-readable JSON instead of plain text.

Plain-text output prints a task URL followed by status details. Use --json for automation. The JSON payload contains a tasks array plus an optional cursor value. Each task includes id, url, title, status, updated_at, environment_id, environment_label, summary, is_review, and attempt_total.

codex completion

Generate shell completion scripts and redirect the output to the appropriate location, for example codex completion zsh > "${fpath[1]}/_codex".

KeyTypeDefaultDescription
SHELLbash | zsh | fish | power-shell | elvishbashShell to generate completions for. Output prints to stdout.

codex features

Manage feature flags stored in ~/.codex/config.toml. The enable and disable commands persist changes so they apply to future sessions. When you launch with --profile, Codex writes to that profile instead of the root configuration.

KeyTypeDefaultDescription
List subcommandcodex features listShow known feature flags, their maturity stage, and their effective state.
Enable subcommandcodex features enablePersistently enable a feature flag in config.toml. Respects the active --profile when provided.
Disable subcommandcodex features disablePersistently disable a feature flag in config.toml. Respects the active --profile when provided.

codex exec

Use codex exec (or the short form codex e) for scripted or CI-style runs that should finish without human interaction.

KeyTypeDefaultDescription
PROMPTstring | - (read stdin)Initial instruction for the task. Use - to pipe the prompt from stdin.
--image, -ipath[,path...]Attach images to the first message. Repeatable; supports comma-separated lists.
--model, -mstringOverride the configured model for this run.
--ossbooleanfalseUse the local open source provider (requires a running Ollama instance).
--sandbox, -sread-only | workspace-write | danger-full-accessSandbox policy for model-generated commands. Defaults to configuration.
--profile, -pstringSelect a configuration profile defined in config.toml.
--full-autobooleanfalseDeprecated compatibility flag. Prefer --sandbox workspace-write; Codex prints a warning when this flag is used.
--dangerously-bypass-approvals-and-sandbox, --yolobooleanfalseBypass approval prompts and sandboxing. Dangerous—only use inside an isolated runner.
--cd, -CpathSet the workspace root before executing the task.
--skip-git-repo-checkbooleanfalseAllow running outside a Git repository (useful for one-off directories).
--ephemeralbooleanfalseRun without persisting session rollout files to disk.
--ignore-user-configbooleanfalseDo not load $CODEX_HOME/config.toml. Authentication still uses CODEX_HOME.
--ignore-rulesbooleanfalseDo not load user or project execpolicy .rules files for this run.
--output-schemapathJSON Schema file describing the expected final response shape. Codex validates tool output against it.
--coloralways | never | autoautoControl ANSI color in stdout.
--json, --experimental-jsonbooleanfalsePrint newline-delimited JSON events instead of formatted text.
--output-last-message, -opathWrite the assistant’s final message to a file. Useful for downstream scripting.
Resume subcommandcodex exec resume [SESSION_ID]Resume an exec session by ID or add --last to continue the most recent session from the current working directory. Add --all to consider sessions from any directory. Accepts an optional follow-up prompt.
-c, --configkey=valueInline configuration override for the non-interactive run (repeatable).

Codex writes formatted output by default. Add --json to receive newline-delimited JSON events (one per state change). The optional resume subcommand lets you continue non-interactive tasks. Use --last to pick the most recent session from the current working directory, or add --all to search across all sessions:

KeyTypeDefaultDescription
SESSION_IDuuidResume the specified session. Omit and use --last to continue the most recent session.
--lastbooleanfalseResume the most recent conversation from the current working directory.
--allbooleanfalseInclude sessions outside the current working directory when selecting the most recent session.
--image, -ipath[,path...]Attach one or more images to the follow-up prompt. Separate multiple paths with commas or repeat the flag.
PROMPTstring | - (read stdin)Optional follow-up instruction sent immediately after resuming.

codex execpolicy

Check execpolicy rule files before you save them. codex execpolicy check accepts one or more --rules flags (for example, files under ~/.codex/rules) and emits JSON showing the strictest decision and any matching rules. Add --pretty to format the output. The execpolicy command is currently in preview.

KeyTypeDefaultDescription
--rules, -rpath (repeatable)Path to an execpolicy rule file to evaluate. Provide multiple flags to combine rules across files.
--prettybooleanfalsePretty-print the JSON result.
COMMAND...var-argsCommand to be checked against the specified policies.

codex login

Authenticate the CLI with a ChatGPT account, API key, or access token. With no flags, Codex opens a browser for the ChatGPT OAuth flow.

KeyTypeDefaultDescription
--with-api-keybooleanRead an API key from stdin (for example printenv OPENAI_API_KEY | codex login --with-api-key).
--with-access-tokenbooleanRead an access token from stdin (for example printenv CODEX_ACCESS_TOKEN | codex login --with-access-token).
--device-authbooleanUse OAuth device code flow instead of launching a browser window.
status subcommandcodex login statusPrint the active authentication mode and exit with 0 when logged in.

codex login status exits with 0 when credentials are present, which is helpful in automation scripts.

codex logout

Remove saved credentials for both API key and ChatGPT authentication. This command has no flags.

codex mcp

Manage Model Context Protocol server entries stored in ~/.codex/config.toml.

KeyTypeDefaultDescription
list--jsonList configured MCP servers. Add --json for machine-readable output.
get--jsonShow a specific server configuration. --json prints the raw config entry.
add-- | --urlRegister a server using a stdio launcher command or a streamable HTTP URL. Supports --env KEY=VALUE for stdio transports.
removeDelete a stored MCP server definition.
login--scopes scope1,scope2Start an OAuth login for a streamable HTTP server (servers that support OAuth only).
logoutRemove stored OAuth credentials for a streamable HTTP server.

The add subcommand supports both stdio and streamable HTTP transports:

KeyTypeDefaultDescription
COMMAND...stdio transportExecutable plus arguments to launch the MCP server. Provide after --.
--env KEY=VALUErepeatableEnvironment variable assignments applied when launching a stdio server.
--urlhttps://…Register a streamable HTTP server instead of stdio. Mutually exclusive with COMMAND....
--bearer-token-env-varENV_VAREnvironment variable whose value is sent as a bearer token when connecting to a streamable HTTP server.

OAuth actions (login, logout) only work with streamable HTTP servers (and only when the server supports OAuth).

codex plugin marketplace

Manage plugin marketplace sources that Codex can browse and install from.

KeyTypeDefaultDescription
add[--ref REF] [--sparse PATH]Install a plugin marketplace from GitHub shorthand, a Git URL, an SSH URL, or a local marketplace root directory. --sparse is supported only for Git sources and can be repeated.
upgrade [marketplace-name]Refresh one configured Git marketplace, or all configured Git marketplaces when no name is provided.
removeRemove a configured plugin marketplace.

codex plugin marketplace add accepts GitHub shorthand such as owner/repo or owner/repo@ref, HTTP or HTTPS Git URLs, SSH Git URLs, and local marketplace root directories. Use --ref to pin a Git ref, and repeat --sparse PATH to use a sparse checkout for Git-backed marketplace repositories.

codex mcp-server

Run Codex as an MCP server over stdio so that other tools can connect. This command inherits global configuration overrides and exits when the downstream client closes the connection.

codex resume

Continue an interactive session by ID or resume the most recent conversation. codex resume scopes --last to the current working directory unless you pass --all. It accepts the same global flags as codex, including model and sandbox overrides.

KeyTypeDefaultDescription
SESSION_IDuuidResume the specified session. Omit and use --last to continue the most recent session.
--lastbooleanfalseSkip the picker and resume the most recent conversation from the current working directory.
--allbooleanfalseInclude sessions outside the current working directory when selecting the most recent session.

codex fork

Fork a previous interactive session into a new thread. By default, codex fork opens the session picker; add --last to fork your most recent session instead.

KeyTypeDefaultDescription
SESSION_IDuuidFork the specified session. Omit and use --last to fork the most recent session.
--lastbooleanfalseSkip the picker and fork the most recent conversation automatically.
--allbooleanfalseShow sessions beyond the current working directory in the picker.

codex sandbox

Use the sandbox helper to run a command under the same policies Codex uses internally.

macOS seatbelt

KeyTypeDefaultDescription
--permissions-profileNAMEApply a named permissions profile from the active configuration stack.
--cd, -CDIRWorking directory used for profile resolution and command execution. Requires --permissions-profile.
--include-managed-configbooleanfalseInclude managed requirements while resolving an explicit permissions profile. Requires --permissions-profile.
--allow-unix-socketpathAllow the sandboxed command to bind or connect Unix sockets rooted at this path. Repeat to allow multiple paths.
--log-denialsbooleanfalseCapture macOS sandbox denials with log stream while the command runs and print them after exit.
--config, -ckey=valuePass configuration overrides into the sandboxed run (repeatable).
COMMAND...var-argsShell command to execute under macOS Seatbelt. Everything after -- is forwarded.

Linux Landlock

KeyTypeDefaultDescription
--permissions-profileNAMEApply a named permissions profile from the active configuration stack.
--cd, -CDIRWorking directory used for profile resolution and command execution. Requires --permissions-profile.
--include-managed-configbooleanfalseInclude managed requirements while resolving an explicit permissions profile. Requires --permissions-profile.
--config, -ckey=valueConfiguration overrides applied before launching the sandbox (repeatable).
COMMAND...var-argsCommand to execute under Landlock + seccomp. Provide the executable after --.

Windows

KeyTypeDefaultDescription
--permissions-profileNAMEApply a named permissions profile from the active configuration stack.
--cd, -CDIRWorking directory used for profile resolution and command execution. Requires --permissions-profile.
--include-managed-configbooleanfalseInclude managed requirements while resolving an explicit permissions profile. Requires --permissions-profile.
--config, -ckey=valueConfiguration overrides applied before launching the sandbox (repeatable).
COMMAND...var-argsCommand to execute under the native Windows sandbox. Provide the executable after --.

codex update

Check for and apply a Codex CLI update when the installed release supports self-update. Debug builds print a message telling you to install a release build instead.

Flag combinations and safety tips

  • Use --sandbox workspace-write for unattended local work that can stay inside the workspace, and avoid --dangerously-bypass-approvals-and-sandbox unless you are inside a dedicated sandbox VM.
  • When you need to grant Codex write access to more directories, prefer --add-dir rather than forcing --sandbox danger-full-access.
  • Pair --json with --output-last-message in CI to capture machine-readable progress and a final natural-language summary.