### Run quickstart constructor example Source: https://github.com/openai/codex/blob/main/sdk/python/examples/README.md Execute the quickstart constructor example for an initial sanity check. ```bash python examples/01_quickstart_constructor/sync.py python examples/01_quickstart_constructor/async.py ``` -------------------------------- ### Run example scripts Source: https://github.com/openai/codex/blob/main/sdk/python/examples/README.md Run synchronous or asynchronous versions of any example from the sdk/python directory. ```bash python examples//sync.py python examples//async.py ``` -------------------------------- ### Build and install bubblewrap using meson Source: https://github.com/openai/codex/blob/main/codex-rs/vendor/bubblewrap/README.md Builds bubblewrap from source, runs test verification, and installs the resulting binaries into the system. ```sh meson _builddir meson compile -C _builddir meson test -C _builddir meson install -C _builddir ``` -------------------------------- ### Install development dependencies from repository checkout Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Installs and activates development dependencies using uv in a local repository checkout. ```bash cd sdk/python uv sync --group dev source .venv/bin/activate ``` -------------------------------- ### Install development dependencies from checkout Source: https://github.com/openai/codex/blob/main/sdk/python/examples/README.md Sync development dependencies using uv and activate the virtual environment from sdk/python. ```bash uv sync --group dev source .venv/bin/activate ``` -------------------------------- ### Define setup.json board template Source: https://github.com/openai/codex/blob/main/codex-rs/ext/agent-message-board/README.md Example structure of setup.json defining initial channels and descriptions. An optional top-level timestamp can define the creation time. ```json { "template": { "version": 1, "channels": { "policy": { "description": "Shared policies" } } } } ``` -------------------------------- ### Start a process with process/start Source: https://github.com/openai/codex/blob/main/codex-rs/exec-server/README.md Spawns a process with specified arguments, working directory, and environment settings. Output from the process is streamed back via process/output notifications. ```json {"id":2,"method":"process/start","params":{"processId":"proc-1","argv":["bash","-lc","printf 'ready\n'; while IFS= read -r line; do printf 'echo:%s\n' \"$line\"; done"],"cwd":"file:///tmp","env":{"PATH":"/usr/bin:/bin"},"tty":true,"pipeStdin":false,"arg0":null}} {"id":2,"result":{"processId":"proc-1"}} {"method":"process/output","params":{"processId":"proc-1","seq":1,"stream":"stdout","chunk":"cmVhZHkK"}} ``` -------------------------------- ### Build and run codex app-server test client quickstart Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-test-client/README.md Builds the debug codex binary, launches the websocket app-server in the background, and queries it with model-list. Execute these commands from the /codex-rs directory. ```bash # 1) Build debug codex binary cargo build -p codex-cli --bin codex # 2) Start websocket app-server in background cargo run -p codex-app-server-test-client -- \ --codex-bin ./target/debug/codex \ serve --listen ws://127.0.0.1:4222 --kill # 3) Call app-server (defaults to ws://127.0.0.1:4222) cargo run -p codex-app-server-test-client -- model-list ``` -------------------------------- ### process/start Source: https://github.com/openai/codex/blob/main/codex-rs/exec-server/README.md Starts a new managed process with the specified command, environment variables, working directory, and terminal configurations. ```APIDOC ## RPC Method: `process/start` ### Description Starts a new managed process within the connection lifecycle. ### Request Parameters - **processId** (string) - Required. Caller-chosen stable id for this process within the connection. Reusing an existing ID is rejected. - **argv** (array of strings) - Required. Non-empty command vector. - **cwd** (string) - `file:` URI for the child process working directory. - **env** (object) - Environment variables passed to the child process. - **tty** (boolean) - When `true`, spawns a PTY-backed interactive process. - **pipeStdin** (boolean) - When `true`, keeps non-PTY stdin writable via `process/write`. - **arg0** (string | null) - Optional argv0 override forwarded to `codex-utils-pty`. ### Request Example ```json { "processId": "proc-1", "argv": ["bash", "-lc", "printf 'hello\\n'"], "cwd": "file:///absolute/working/directory", "env": { "PATH": "/usr/bin:/bin" }, "tty": true, "pipeStdin": false, "arg0": null } ``` ### Response - **processId** (string) - The identifier of the started process. ### Response Example ```json { "processId": "proc-1" } ``` ``` -------------------------------- ### Run standalone attach example with cargo Source: https://github.com/openai/codex/blob/main/codex-rs/cloud-client/README.md Runs the attach example against an existing authorized thread and native gRPC origin. Requires CODEX_CLOUD_ACCESS_TOKEN and CODEX_CLOUD_ACCOUNT_ID to be set in your environment. ```sh cargo run -p codex-cloud-client --example attach -- "$CODEX_CLOUD_GRPC_ENDPOINT" "$CODEX_CLOUD_THREAD_ID" ``` -------------------------------- ### Install the published SDK Source: https://github.com/openai/codex/blob/main/sdk/python/examples/README.md Install the openai-codex package and its pinned runtime dependency using pip. Requires Python >=3.10. ```bash python -m pip install openai-codex ``` -------------------------------- ### Install optional Pillow package with uv Source: https://github.com/openai/codex/blob/main/codex-rs/skills/src/assets/samples/imagegen/SKILL.md Installs the optional `pillow` package used for image inspection and downscaling. ```bash uv pip install pillow ``` -------------------------------- ### Configure agent board with setup.json CLI command Source: https://github.com/openai/codex/blob/main/codex-rs/ext/agent-message-board/README.md Loads initial channels for an empty chat before starting agents. Use the same SQLite home directory as Codex (normally $CODEX_HOME or ~/.codex). ```sh just agent-board-config ~/.codex /absolute/path/setup.json ``` -------------------------------- ### Install dependencies and build Codex CLI binary Source: https://github.com/openai/codex/blob/main/scripts/mcp_conformance/README.md Installs frozen workspace dependencies using pnpm and builds the locked Codex CLI binary using cargo. ```bash pnpm install --frozen-lockfile cargo build --locked --manifest-path codex-rs/Cargo.toml -p codex-cli --bin codex ``` -------------------------------- ### Install Codex CLI via Homebrew Source: https://github.com/openai/codex/blob/main/README.md Installs the Codex desktop cask on macOS using Homebrew. ```shell # Install using Homebrew brew install --cask codex ``` -------------------------------- ### Install openai-codex with pip Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Installs the OpenAI Codex Python SDK and its runtime dependencies. Requires Python >= 3.10. ```bash pip install openai-codex ``` -------------------------------- ### NetworkProxy::run() & Handle::shutdown() Source: https://github.com/openai/codex/blob/main/codex-rs/network-proxy/README.md Starts the network proxy listener and provides lifecycle control to gracefully terminate the proxy handle. ```APIDOC ## NetworkProxy Lifecycle ### Description Starts the proxy service execution loop and shuts it down asynchronously. ### Methods - **proxy.run() -> Result** - Spawns the proxy server and returns a control handle. - **handle.shutdown() -> Result<(), Error>** - Initiates graceful shutdown of the running network proxy. ### Example ```rust let handle = proxy.run().await?; handle.shutdown().await?; ``` ``` -------------------------------- ### Install required OpenAI package with uv Source: https://github.com/openai/codex/blob/main/codex-rs/skills/src/assets/samples/imagegen/SKILL.md Installs the required `openai` Python package for CLI fallback operations. ```bash uv pip install openai ``` -------------------------------- ### Run turns asynchronously with AsyncCodex Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Demonstrates starting a thread and running a turn using the asynchronous AsyncCodex context manager. ```python import asyncio from openai_codex import AsyncCodex, Sandbox async def main() -> None: async with AsyncCodex() as codex: thread = await codex.thread_start(sandbox=Sandbox.workspace_write) result = await thread.run("Continue where we left off.") print(result.final_response) asyncio.run(main()) ``` -------------------------------- ### Manage async thread lifecycle, branching, and compaction Source: https://github.com/openai/codex/blob/main/sdk/python/notebooks/sdk_walkthrough.ipynb Demonstrates how to start turns, resume, list, archive, unarchive, fork, and compact threads asynchronously using AsyncCodex. ```python # Cell 9: full thread lifecycle and branching (async) import asyncio async def async_lifecycle_demo(): async with AsyncCodex() as codex: thread = await codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'}) first = await (await thread.turn('One sentence about structured planning.')).run() second = await (await thread.turn('Now restate it for a junior engineer.')).run() reopened = await codex.thread_resume(thread.id) listing_active = await codex.thread_list(limit=20, archived=False) reading = await reopened.read(include_turns=True) _ = await reopened.set_name('sdk-lifecycle-demo') _ = await codex.thread_archive(reopened.id) listing_archived = await codex.thread_list(limit=20, archived=True) unarchived = await codex.thread_unarchive(reopened.id) resumed = await codex.thread_resume( unarchived.id, model='gpt-5.4', config={'model_reasoning_effort': 'high'}, ) resumed_result = await (await resumed.turn('Continue in one short sentence.')).run() forked = await codex.thread_fork(unarchived.id, model='gpt-5.4') forked_result = await (await forked.turn('Take a different angle in one short sentence.')).run() compact_result = await unarchived.compact() print('Lifecycle OK:', thread.id) print('first:', first.id, first.status) print('second:', second.id, second.status) print('read.turns:', len(reading.thread.turns)) print('list.active:', len(listing_active.data)) print('list.archived:', len(listing_archived.data)) print('resumed:', resumed_result.id, resumed_result.status) print('forked:', forked_result.id, forked_result.status) print('compact:', compact_result.model_dump(mode='json', by_alias=True)) await async_lifecycle_demo() ``` -------------------------------- ### Define build options in meson_options.txt Source: https://github.com/openai/codex/blob/main/codex-rs/vendor/bubblewrap/meson_options.txt Configures project build-time options in Bubblewrap using Meson. Allows toggling shell completions, man pages, SELinux, test suites, setuid compatibility, and custom installation paths. ```meson option( 'bash_completion', type : 'feature', description : 'install bash completion script', value : 'enabled', ) option( 'bash_completion_dir', type : 'string', description : 'install bash completion script in this directory', value : '', ) option( 'bwrapdir', type : 'string', description : 'install bwrap in this directory [default: bindir, or libexecdir in subprojects]', ) option( 'build_rpath', type : 'string', description : 'set a RUNPATH or RPATH on the bwrap executable', ) option( 'install_rpath', type : 'string', description : 'set a RUNPATH or RPATH on the bwrap executable', ) option( 'man', type : 'feature', description : 'generate man pages', value : 'auto', ) option( 'program_prefix', type : 'string', description : 'Prepend string to bwrap executable name, for use with subprojects', ) option( 'python', type : 'string', description : 'Path to Python 3, or empty to use python3', ) option( 'support_setuid', type : 'boolean', description : 'Support setuid mode (deprecated)', value : false, ) option( 'require_userns', type : 'boolean', description : 'require user namespaces by default when installed setuid', value : false, ) option( 'selinux', type : 'feature', description : 'enable optional SELINUX support', value : 'auto', ) option( 'tests', type : 'boolean', description : 'build tests', value : true, ) option( 'zsh_completion', type : 'feature', description : 'install zsh completion script', value : 'enabled', ) option( 'zsh_completion_dir', type : 'string', description : 'install zsh completion script in this directory', value : '', ) ``` -------------------------------- ### Start a thread and run a prompt with Codex Source: https://github.com/openai/codex/blob/main/sdk/python/docs/api-reference.md Initialize a Codex context manager, start a thread specifying the model and reasoning effort configuration, and execute a prompt to obtain the final response. ```python from openai_codex import Codex with Codex() as codex: thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) result = thread.run("Say hello in one sentence.") print(result.final_response) ``` -------------------------------- ### Bootstrap local SDK environment and runtime package Source: https://github.com/openai/codex/blob/main/sdk/python/notebooks/sdk_walkthrough.ipynb Locates the local SDK Python directory, verifies Python 3.10+ requirement, installs or verifies runtime dependencies, and sets up sys.path. ```python # Cell 1: bootstrap local SDK imports + pinned runtime package import os import sys from pathlib import Path if sys.version_info < (3, 10): raise RuntimeError( f'Notebook requires Python 3.10+; current interpreter is {sys.version.split()[0]}.' ) def _is_sdk_python_dir(path: Path) -> bool: return (path / 'pyproject.toml').exists() and (path / 'src' / 'openai_codex').exists() def _find_sdk_python_dir(start: Path) -> Path | None: checked = set() def _consider(candidate: Path) -> Path | None: resolved = candidate.resolve() if resolved in checked: return None checked.add(resolved) if _is_sdk_python_dir(resolved): return resolved return None for candidate in [start, *start.parents]: found = _consider(candidate) if found is not None: return found for candidate in [start / 'sdk' / 'python', *(parent / 'sdk' / 'python' for parent in start.parents)]: found = _consider(candidate) if found is not None: return found env_dir = os.environ.get('CODEX_PYTHON_SDK_DIR') if env_dir: found = _consider(Path(env_dir).expanduser()) if found is not None: return found return None repo_python_dir = _find_sdk_python_dir(Path.cwd()) if repo_python_dir is None: raise RuntimeError('Could not locate sdk/python. Set CODEX_PYTHON_SDK_DIR to your sdk/python path.') repo_python_str = str(repo_python_dir) if repo_python_str not in sys.path: sys.path.insert(0, repo_python_str) from _runtime_setup import ensure_runtime_package_installed runtime_version = ensure_runtime_package_installed( sys.executable, repo_python_dir, ) src_dir = repo_python_dir / 'src' examples_dir = repo_python_dir / 'examples' src_str = str(src_dir) examples_str = str(examples_dir) if src_str not in sys.path: sys.path.insert(0, src_str) if examples_str not in sys.path: sys.path.insert(0, examples_str) # Force fresh imports after SDK upgrades in the same notebook kernel. for module_name in list(sys.modules): if module_name == 'openai_codex' or module_name.startswith('openai_codex.'): sys.modules.pop(module_name, None) print('Kernel:', sys.executable) print('SDK source:', src_dir) print('Runtime package:', runtime_version) ``` -------------------------------- ### Build Codex from source and run tests Source: https://github.com/openai/codex/blob/main/docs/install.md Clone the repository, install the Rust toolchain and workspace helper tools, build Codex, and execute formatting and test commands with justfile helpers. Avoid `--all-features` during routine local runs to reduce build time and disk usage. ```bash # Clone the repository and navigate to the root of the Cargo workspace. git clone https://github.com/openai/codex.git cd codex/codex-rs # Install the Rust toolchain, if necessary. curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y source "$HOME/.cargo/env" rustup component add rustfmt rustup component add clippy # Install helper tools used by the workspace justfile: cargo install --locked just # DotSlash fetches pinned development tools such as buildifier on first use. cargo install --locked dotslash # Install nextest for the `just test` helper. cargo install --locked cargo-nextest # Build Codex. cargo build # Launch the TUI with a sample prompt. cargo run --bin codex -- "explain this codebase to me" # After making changes, use the root justfile helpers (they default to codex-rs): just fmt just fix -p # Run the relevant tests (project-specific is fastest), for example: just test -p codex-tui # `just test` runs the test suite via nextest: just test # Avoid `--all-features` for routine local runs because it increases build # time and `target/` disk usage by compiling additional feature combinations. ``` -------------------------------- ### Bootstrap app-server daemon on Windows via PowerShell Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-daemon/README.md Installs Codex and bootstraps the daemon on Windows. Run in a non-elevated PowerShell terminal whose host allows breakaway. ```powershell irm https://chatgpt.com/codex/install.ps1 | iex $codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' } & "$codexHome\packages\standalone\current\bin\codex.exe" app-server daemon bootstrap --remote-control ``` -------------------------------- ### Directory Structure for an apply-patch Test Case Source: https://github.com/openai/codex/blob/main/codex-rs/apply-patch/tests/fixtures/scenarios/README.md Demonstrates the directory layout for a single test case that creates a new file. Organizes the starting file state in input/, the operation in patch.txt, and the target final state in expected/. ```text 001_add/ input/ foo.md expected/ foo.md bar.md patch.txt ``` -------------------------------- ### Codex.thread_start(*, approval_mode=ApprovalMode.auto_review, base_instructions=None, config=None, cwd=None, developer_instructions=None, ephemeral=None, model=None, model_provider=None, personality=None, sandbox: Sandbox | None = None) -> Thread Source: https://github.com/openai/codex/blob/main/sdk/python/docs/api-reference.md Starts a new thread session with configurable instructions, approval modes, and sandboxing. ```APIDOC ## Codex.thread_start ### Description Starts a new conversation thread. ### Signature `thread_start(*, approval_mode=ApprovalMode.auto_review, base_instructions=None, config=None, cwd=None, developer_instructions=None, ephemeral=None, model=None, model_provider=None, personality=None, sandbox: Sandbox | None = None) -> Thread` ### Parameters - **approval_mode** (optional) - Approval mode policy. Defaults to `ApprovalMode.auto_review`. - **base_instructions** (optional) - Base instructions for the model. - **config** (optional) - Thread-level configuration. - **cwd** (optional) - Current working directory. - **developer_instructions** (optional) - Developer instructions. - **ephemeral** (optional) - Indicates whether the thread is ephemeral. - **model** (optional) - Specific model identifier. - **model_provider** (optional) - Provider identifier for the model. - **personality** (optional) - Deprecated. Tone personality setting (e.g. `Personality.none`, `Personality.friendly`, `Personality.pragmatic`). - **sandbox** (`Sandbox | None`, optional) - Sandbox environment definition. Defaults to `None`. ### Return Value - Returns `Thread` ``` -------------------------------- ### Start a thread and run a turn Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Starts a thread configured with workspace write access and executes a single turn, returning the final response and item count. ```python from openai_codex import Codex, Sandbox with Codex() as codex: thread = codex.thread_start(sandbox=Sandbox.workspace_write) result = thread.run("Say hello in one sentence.") print("Thread:", thread.id) print("Text:", result.final_response) print("Items:", len(result.items)) ``` -------------------------------- ### Preview diagram with render example Source: https://github.com/openai/codex/blob/main/codex-rs/mermaid/README.md Previews a Mermaid diagram file from codex-rs, optionally passing an available canvas width limit (such as 180). ```sh cargo run -p codex-mermaid --example render -- 180 < diagram.mmd ``` -------------------------------- ### Start a managed process via process/start Source: https://github.com/openai/codex/blob/main/codex-rs/exec-server/README.md Spawns a new managed child process using specified arguments, environment variables, working directory, and PTY or piped stdin settings. Reusing an existing processId is rejected. ```json { "processId": "proc-1", "argv": ["bash", "-lc", "printf 'hello\\n'"], "cwd": "file:///absolute/working/directory", "env": { "PATH": "/usr/bin:/bin" }, "tty": true, "pipeStdin": false, "arg0": null } ``` ```json { "processId": "proc-1" } ``` -------------------------------- ### Run Standalone Network Proxy with JSON Configuration Source: https://github.com/openai/codex/blob/main/codex-rs/network-proxy/README.md Define a network policy in a standalone JSON file and start the proxy using the --config CLI option. The proxy requires network.enabled to be true and rejects unknown configuration fields. ```json { "network": { "enabled": true, "proxy_url": "http://127.0.0.1:3128", "enable_socks5": false, "enable_socks5_udp": false, "allow_upstream_proxy": false, "allow_local_binding": false, "mode": "full", "mitm": false, "domains": { "api.example.com": "allow" } } } ``` ```bash cargo run -p codex-network-proxy -- --config /path/to/network-proxy.json ``` -------------------------------- ### Run plugin analytics smoke test with plugin-analytics-smoke Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-test-client/README.md Builds a debug binary and tests plugin enable/disable config writes, installation, and mentions while capturing analytics to a local JSONL file. Requires the plugin to be remotely installed and enabled with an authenticated profile. ```bash # Build a debug Codex binary; analytics capture is unavailable in release builds. cargo build -p codex-cli --bin codex cargo run -p codex-app-server-test-client -- \ --codex-bin ./target/debug/codex \ plugin-analytics-smoke \ --plugin-id linear@openai-curated-remote ``` -------------------------------- ### Run a sandboxed shell with bwrap Source: https://github.com/openai/codex/blob/main/codex-rs/vendor/bubblewrap/README.md Creates a new mount namespace reusing the host's /usr directory with read-only access and starts a bash shell session in an isolated PID namespace. ```sh bwrap \ --ro-bind /usr /usr \ --symlink usr/lib64 /lib64 \ --proc /proc \ --dev /dev \ --unshare-pid \ --new-session \ bash ``` -------------------------------- ### Bootstrap app-server daemon on Linux or macOS Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-daemon/README.md Installs Codex via curl and bootstraps the app-server daemon with remote control on a new Linux or macOS machine. ```sh curl -fsSL https://chatgpt.com/codex/install.sh | sh $HOME/.codex/packages/standalone/current/codex app-server daemon bootstrap --remote-control ``` -------------------------------- ### Manage app-server daemon lifecycle with CLI commands Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-daemon/README.md Execute daemon lifecycle commands including start, restart, update, remote control toggling, stop, version inspection, and bootstrap. Each successful command writes exactly one JSON object to stdout containing lifecycle and version metadata. ```sh codex app-server daemon start codex app-server daemon restart codex app-server daemon update codex app-server daemon enable-remote-control codex app-server daemon disable-remote-control codex app-server daemon stop codex app-server daemon version codex app-server daemon bootstrap --remote-control ``` -------------------------------- ### Run codex-responses-api-proxy against Azure OpenAI Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md Example for Azure deployments that accept Authorization: Bearer . It unsets AZURE_OPENAI_API_KEY from the environment after piping it into the proxy, enables GET /shutdown, writes server info to /tmp/server-info.json, and forwards to the Azure responses endpoint. ```shell printenv AZURE_OPENAI_API_KEY | env -u AZURE_OPENAI_API_KEY codex-responses-api-proxy \ --http-shutdown \ --server-info /tmp/server-info.json \ --upstream-url "https://YOUR_PROJECT_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT/responses?api-version=2025-04-01-preview" ``` -------------------------------- ### Start proxy as privileged user with --http-shutdown Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md Run the proxy as a privileged user (root or sudo) with access to OPENAI_API_KEY. The proxy reads the auth token from stdin. The --http-shutdown flag allows an unprivileged user to shut down the server via GET /shutdown. ```shell printenv OPENAI_API_KEY | env -u OPENAI_API_KEY codex-responses-api-proxy --http-shutdown --server-info /tmp/server-info.json ``` -------------------------------- ### Install @openai/codex-sdk with npm Source: https://github.com/openai/codex/blob/main/sdk/typescript/README.md Installs the Codex TypeScript SDK package. Requires Node.js 18 or higher. ```bash npm install @openai/codex-sdk ``` -------------------------------- ### Build, sign, and run the native hardware test bundle Source: https://github.com/openai/codex/blob/main/codex-rs/user-verification/README.md Builds the hardware test binary, packages it into an app bundle with entitlements copied from TEMPLATE_APP, signs it with SIGNING_IDENTITY, and executes the ignored test. ```bash set -euo pipefail : "${TEMPLATE_APP:?Set the path to the isolated signed development app}" : "${SIGNING_IDENTITY:?Set its Apple Development identity}" run_dir=$(mktemp -d) app="$run_dir/HardwareTest.app" (cd codex-rs && cargo build --locked -p codex-user-verification --test hardware \ --message-format=json) > "$run_dir/build.jsonl" binary=$(jq -r 'select(.reason == "compiler-artifact" and .target.name == "hardware" and .executable != null) | .executable' "$run_dir/build.jsonl") mkdir -p "$app/Contents/MacOS" cp "$binary" "$app/Contents/MacOS/hardware" cp "$TEMPLATE_APP/Contents/Info.plist" "$app/Contents/Info.plist" cp "$TEMPLATE_APP/Contents/embedded.provisionprofile" "$app/Contents/embedded.provisionprofile" /usr/libexec/PlistBuddy -c 'Set :CFBundleExecutable hardware' "$app/Contents/Info.plist" codesign -d --xml --entitlements - "$TEMPLATE_APP" > "$run_dir/entitlements.plist" codesign --force --options runtime --entitlements "$run_dir/entitlements.plist" \ --sign "$SIGNING_IDENTITY" "$app" codesign --verify --strict "$app" echo "Test bundle: $app" "$app/Contents/MacOS/hardware" --ignored --exact \ persisted_key_signing_cancellation_and_retry --nocapture --test-threads=1 ``` -------------------------------- ### Launch proxy and configure Codex to use it Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md Build and run the proxy, then add the provider configuration to ~/.codex/config.toml and use it with codex -p proxy. ```shell # Launch the proxy, dump request/response pairs to /tmp/proxy cd path/to/codex/codex-rs cargo build echo $OPENAI_API_KEY | ./target/debug/codex-responses-api-proxy \ --port 60001 \ --dump-dir /tmp/proxy # Add this to ~/.codex/config.toml: [model_providers.codex-responses-api-proxy] name = 'codex-responses-api-proxy' base_url = 'http://127.0.0.1:60001/v1' wire_api='responses' [profiles.proxy] model_provider = "codex-responses-api-proxy" # Use it codex -p proxy ``` -------------------------------- ### Install Codex CLI via npm Source: https://github.com/openai/codex/blob/main/README.md Installs Codex CLI globally using the npm package manager. ```shell # Install using npm npm install -g @openai/codex ``` -------------------------------- ### Install Codex CLI on macOS or Linux Source: https://github.com/openai/codex/blob/main/README.md Downloads and runs the standalone install script for macOS or Linux environments. ```shell curl -fsSL https://chatgpt.com/codex/install.sh | sh ``` -------------------------------- ### Exercise generic remote configuration with run_bazel_with_buildbuddy.py Source: https://github.com/openai/codex/blob/main/codex-rs/docs/bazel.md Runs a Bazel build through the BuildBuddy wrapper using an API key and a repository override to invoke the generic remote host configuration. ```bash BUILDBUDDY_API_KEY=... GITHUB_REPOSITORY=my-fork/codex \ ./.github/scripts/run_bazel_with_buildbuddy.py \ build --config=ci-linux //codex-rs/cli:codex ``` -------------------------------- ### Inspect SDK documentation using help() Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Uses Python's built-in help function to inspect the SDK and core classes. ```python import openai_codex from openai_codex import Codex, CodexConfig help(openai_codex) help(Codex) help(CodexConfig) ``` -------------------------------- ### Install Codex CLI on Windows via PowerShell Source: https://github.com/openai/codex/blob/main/README.md Runs the Windows installation script directly in PowerShell with execution policy bypassed. ```shell powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex" ``` -------------------------------- ### Force GitHub Releases download on Windows PowerShell installer Source: https://github.com/openai/codex/blob/main/README.md Sets the environment variable to force GitHub Releases download before running the PowerShell installer. ```powershell $env:CODEX_INSTALLER_USE_RELEASES_OPENAI_COM='false'; irm https://chatgpt.com/codex/install.ps1 | iex ``` -------------------------------- ### Force GitHub Releases download on macOS/Linux installer Source: https://github.com/openai/codex/blob/main/README.md Installs Codex CLI on macOS or Linux while forcing downloads from GitHub Releases instead of releases.openai.com. ```shell curl -fsSL https://chatgpt.com/codex/install.sh | CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false sh ``` -------------------------------- ### Initialize OtelProvider with OtelSettings and tracing_subscriber Source: https://github.com/openai/codex/blob/main/codex-rs/otel/README.md Constructs an OtelSettings instance and initializes an OtelProvider, attaching its logger and tracing layers to the tracing_subscriber registry. The provider also configures metrics when enabled. ```rust use codex_otel::config::OtelExporter; use codex_otel::config::OtelHttpProtocol; use codex_otel::config::OtelSettings; use codex_otel::OtelProvider; use tracing_subscriber::prelude::*; let settings = OtelSettings { environment: "dev".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), codex_home: std::path::PathBuf::from("/tmp"), exporter: OtelExporter::OtlpHttp { endpoint: "https://otlp.example.com".to_string(), headers: std::collections::HashMap::new(), protocol: OtelHttpProtocol::Binary, tls: None, }, trace_exporter: OtelExporter::OtlpHttp { endpoint: "https://otlp.example.com".to_string(), headers: std::collections::HashMap::new(), protocol: OtelHttpProtocol::Binary, tls: None, }, metrics_exporter: OtelExporter::None, span_attributes: std::collections::BTreeMap::new(), tracestate: std::collections::BTreeMap::new(), }; if let Some(provider) = OtelProvider::try_new(&settings)? { let registry = tracing_subscriber::registry() .with(provider.logger_layer()) .with(provider.tracing_layer()); registry.init(); } ``` -------------------------------- ### Inspect SDK documentation using pydoc Source: https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md Runs pydoc CLI to display SDK module documentation. ```bash python -m pydoc openai_codex ``` -------------------------------- ### Start a thread and run a turn with Codex Source: https://github.com/openai/codex/blob/main/sdk/python/README.md Reuses existing Codex authentication to start a thread and execute a turn. Returns a TurnResult containing the final response, collected items, and token usage. ```python from openai_codex import Codex with Codex() as codex: thread = codex.thread_start() result = thread.run("Explain this repository in three bullets.") print(result.final_response) ``` -------------------------------- ### Test remote install and uninstall analytics with plugin-analytics-mutation-smoke Source: https://github.com/openai/codex/blob/main/codex-rs/app-server-test-client/README.md Performs a live smoke test by temporarily installing and uninstalling a remote plugin to validate mutation analytics events. Provide the backend identifier to `--remote-plugin-id` rather than the local plugin ID. ```bash cargo run -p codex-app-server-test-client -- \ --codex-bin ./target/debug/codex \ plugin-analytics-mutation-smoke \ --remote-plugin-id \ --confirm-account-mutation \ --capture-file /tmp/plugin-mutation-analytics.jsonl ``` -------------------------------- ### Using AsyncCodex Context Manager for Preferred Usage Source: https://github.com/openai/codex/blob/main/sdk/python/docs/api-reference.md AsyncCodex initializes lazily; context entry is standard to ensure startup and shutdown are explicitly paired. ```python async with AsyncCodex() as codex: ... ``` -------------------------------- ### GET /shutdown Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md Shuts down the proxy process with exit code 0. Only available when the `--http-shutdown` flag is set. ```APIDOC ## GET /shutdown ### Description Exits the proxy process with code `0`. Only enabled when the `--http-shutdown` flag is provided. ### Method GET ### Endpoint /shutdown ### Parameters None. ### Response #### Success Response Process exits with code `0`. ### Notes - This endpoint is only available if `--http-shutdown` is set. ``` -------------------------------- ### Execute synchronous single-turn conversation Source: https://github.com/openai/codex/blob/main/sdk/python/notebooks/sdk_walkthrough.ipynb Starts a thread with specified model configuration and executes a single prompt using thread.run. ```python # Cell 3: simple sync conversation with Codex() as codex: thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'}) result = thread.run('Explain gradient descent in 3 bullets.') print(result.final_response) ``` -------------------------------- ### GET /shutdown Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md Terminates the proxy process with exit code 0. This endpoint is only available when the --http-shutdown option is enabled. ```APIDOC ## GET /shutdown ### Description Terminates the proxy process with exit code 0. This endpoint is only available when the --http-shutdown option is enabled. ### Method GET ### Endpoint /shutdown ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example GET /shutdown ### Response #### Success Response The process terminates with exit code 0. #### Response Example No response body. ``` -------------------------------- ### Configuring BuildBuddy API key in ~/.bazelrc Source: https://github.com/openai/codex/blob/main/codex-rs/docs/bazel.md Configures the BuildBuddy API key in ~/.bazelrc or %workspace%/user.bazelrc for authentication. Keeping credentials in ~/.bazelrc prevents accidentally committing them to the workspace repository. ```bazelrc # Local machine only; this file contains a BuildBuddy credential. common --remote_header=x-buildbuddy-api-key= ``` -------------------------------- ### account/gatewayOAuth/login Source: https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md Starts browser authorization for gateway OAuth for the current provider. Returns once credentials have been saved and emits status notifications during authorization. ```APIDOC ## account/gatewayOAuth/login ### Description Starts the browser authorization flow for gateway OAuth. The initiating connection receives a `started` notification with `authUrl` to open in a browser. A second login request fails while a login is active. ### Type RPC Method ### Parameters None. Takes no params. ### Response Returns `{}` after the credential has been saved. ``` -------------------------------- ### Create Hero Image Generation Prompt Source: https://github.com/openai/codex/blob/main/codex-rs/skills/src/assets/samples/imagegen/SKILL.md Sample prompt applying the scaffolding schema to generate a clean product photograph of a ceramic coffee mug for a landing page. ```text Use case: product-mockup Asset type: landing page hero Primary request: a minimal hero image of a ceramic coffee mug Style/medium: clean product photography Composition/framing: wide composition with usable negative space for page copy if needed Lighting/mood: soft studio lighting Constraints: no logos, no text, no watermark ``` -------------------------------- ### Authenticate using browser login handle lifecycle Source: https://github.com/openai/codex/blob/main/sdk/python/notebooks/sdk_walkthrough.ipynb Initiates ChatGPT login flow using login_chatgpt, waits for completion, and inspects account details. ```python # Cell 2b: browser login handle lifecycle with Codex() as codex: # Open this URL and call `wait()` without canceling when completing login for real. login = codex.login_chatgpt() print('Please complete login at:', login.auth_url) completed = login.wait() account = codex.account() print('login.id:', login.login_id) print('login.auth_url:', login.auth_url) print('login.completed.success:', completed.success) print('account:', account.email) ``` -------------------------------- ### Configure HTTP and HTTPS Client Proxy Environment Variables Source: https://github.com/openai/codex/blob/main/codex-rs/network-proxy/README.md Direct HTTP, HTTPS, and WebSocket client traffic to the running proxy listener. Export these variables in your client environment. ```bash export HTTP_PROXY="http://127.0.0.1:3128" export HTTPS_PROXY="http://127.0.0.1:3128" export WS_PROXY="http://127.0.0.1:3128" export WSS_PROXY="http://127.0.0.1:3128" ``` -------------------------------- ### Shutdown proxy via curl Source: https://github.com/openai/codex/blob/main/codex-rs/responses-api-proxy/README.md When finished, an unprivileged user can shut down the proxy server using curl to GET /shutdown, since kill -SIGTERM is not available. ```shell curl --fail --silent --show-error "${PROXY_BASE_URL}/shutdown" ``` -------------------------------- ### Control streaming turns with steer and interrupt Source: https://github.com/openai/codex/blob/main/sdk/python/notebooks/sdk_walkthrough.ipynb Shows how to guide an in-progress streaming turn using steer and cancel or halt turn generation using interrupt. ```python # Cell 10: async turn controls (steer + interrupt) import asyncio async def async_stream_demo(): async with AsyncCodex() as codex: thread = await codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'}) steer_turn = await thread.turn('Count from 1 to 40 with commas, then one summary sentence.') steer_result = await steer_turn.steer('Keep it brief and stop after 10 numbers.') steer_event_count = 0 steer_completed_status = None steer_deltas = [] async for event in steer_turn.stream(): steer_event_count += 1 if event.method == 'item/agentMessage/delta': steer_deltas.append(event.payload.delta) continue if event.method == 'turn/completed': steer_completed_status = event.payload.turn.status.value if steer_completed_status is None: raise RuntimeError('stream ended without turn/completed') steer_preview = ''.join(steer_deltas).strip() interrupt_turn = await thread.turn('Count from 1 to 200 with commas, then one summary sentence.') interrupt_result = await interrupt_turn.interrupt() interrupt_event_count = 0 interrupt_completed_status = None interrupt_deltas = [] async for event in interrupt_turn.stream(): interrupt_event_count += 1 if event.method == 'item/agentMessage/delta': interrupt_deltas.append(event.payload.delta) continue if event.method == 'turn/completed': interrupt_completed_status = event.payload.turn.status.value if interrupt_completed_status is None: raise RuntimeError('stream ended without turn/completed') interrupt_preview = ''.join(interrupt_deltas).strip() print('steer.result:', steer_result.model_dump(mode='json', by_alias=True)) print('steer.final.status:', steer_completed_status) print('steer.events.count:', steer_event_count) print('steer.assistant.preview:', steer_preview) print('interrupt.result:', interrupt_result.model_dump(mode='json', by_alias=True)) print('interrupt.final.status:', interrupt_completed_status) print('interrupt.events.count:', interrupt_event_count) print('interrupt.assistant.preview:', interrupt_preview) await async_stream_demo() ``` -------------------------------- ### Parse and render templates using Template and render Source: https://github.com/openai/codex/blob/main/codex-rs/utils/template/README.md Demonstrates parsing a template with placeholder substitutions and literal braces, rendering it with key-value pairs, and using the one-shot render function. ```rust use codex_utils_template::Template; use codex_utils_template::render; let template = Template::parse( "Hello, {{ name }}.\nLiteral braces: {{{{ and }}}}.\nMode: {{ mode }}", )?; let rendered = template.render([ ("name", "Codex"), ("mode", "strict"), ])?; assert_eq!( rendered, "Hello, Codex.\nLiteral braces: {{ and }}.\nMode: strict" ); let one_shot = render("Hi {{ who }}!", [("who", "there")])?; assert_eq!(one_shot, "Hi there!"); # Ok::<(), Box>(()) ``` -------------------------------- ### Initialize exec server session Source: https://github.com/openai/codex/blob/main/codex-rs/exec-server/README.md Initializes a client session with the exec server. The server responds with session and environment information before the client confirms initialization. ```json {"id":1,"method":"initialize","params":{"clientName":"example-client"}} {"id":1,"result":{"sessionId":"00000000-0000-4000-8000-000000000001","environmentInfo":{"shell":{"name":"bash","path":"/bin/bash"},"cwd":"file:///tmp"}}} {"method":"initialized","params":{}} ```