2025-09-14 14:38:26 -07:00
|
|
|
|
use crate::exec::ExecToolCallOutput;
|
2025-09-11 18:01:25 -04:00
|
|
|
|
use crate::token_data::KnownPlan;
|
|
|
|
|
|
use crate::token_data::PlanType;
|
2025-09-07 20:22:25 -07:00
|
|
|
|
use codex_protocol::mcp_protocol::ConversationId;
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
use reqwest::StatusCode;
|
|
|
|
|
|
use serde_json;
|
|
|
|
|
|
use std::io;
|
2025-08-13 15:43:54 -07:00
|
|
|
|
use std::time::Duration;
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
use thiserror::Error;
|
|
|
|
|
|
use tokio::task::JoinError;
|
|
|
|
|
|
|
|
|
|
|
|
pub type Result<T> = std::result::Result<T, CodexErr>;
|
|
|
|
|
|
|
|
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
|
|
pub enum SandboxErr {
|
|
|
|
|
|
/// Error from sandbox execution
|
2025-09-14 14:38:26 -07:00
|
|
|
|
#[error(
|
|
|
|
|
|
"sandbox denied exec error, exit code: {}, stdout: {}, stderr: {}",
|
|
|
|
|
|
.output.exit_code, .output.stdout.text, .output.stderr.text
|
|
|
|
|
|
)]
|
|
|
|
|
|
Denied { output: Box<ExecToolCallOutput> },
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
|
|
|
|
|
|
/// Error from linux seccomp filter setup
|
|
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
|
|
#[error("seccomp setup error")]
|
|
|
|
|
|
SeccompInstall(#[from] seccompiler::Error),
|
|
|
|
|
|
|
|
|
|
|
|
/// Error from linux seccomp backend
|
|
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
|
|
#[error("seccomp backend error")]
|
|
|
|
|
|
SeccompBackend(#[from] seccompiler::BackendError),
|
|
|
|
|
|
|
2025-04-25 12:56:20 -07:00
|
|
|
|
/// Command timed out
|
|
|
|
|
|
#[error("command timed out")]
|
2025-09-14 14:38:26 -07:00
|
|
|
|
Timeout { output: Box<ExecToolCallOutput> },
|
2025-04-25 12:56:20 -07:00
|
|
|
|
|
|
|
|
|
|
/// Command was killed by a signal
|
|
|
|
|
|
#[error("command was killed by a signal")]
|
|
|
|
|
|
Signal(i32),
|
|
|
|
|
|
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
/// Error from linux landlock
|
|
|
|
|
|
#[error("Landlock was not able to fully enforce all sandbox rules")]
|
|
|
|
|
|
LandlockRestrict,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
|
|
pub enum CodexErr {
|
|
|
|
|
|
/// Returned by ResponsesClient when the SSE stream disconnects or errors out **after** the HTTP
|
|
|
|
|
|
/// handshake has succeeded but **before** it finished emitting `response.completed`.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// The Session loop treats this as a transient error and will automatically retry the turn.
|
2025-08-13 15:43:54 -07:00
|
|
|
|
///
|
|
|
|
|
|
/// Optionally includes the requested delay before retrying the turn.
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
#[error("stream disconnected before completion: {0}")]
|
2025-08-13 15:43:54 -07:00
|
|
|
|
Stream(String, Option<Duration>),
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
|
chore: introduce ConversationManager as a clearinghouse for all conversations (#2240)
This PR does two things because after I got deep into the first one I
started pulling on the thread to the second:
- Makes `ConversationManager` the place where all in-memory
conversations are created and stored. Previously, `MessageProcessor` in
the `codex-mcp-server` crate was doing this via its `session_map`, but
this is something that should be done in `codex-core`.
- It unwinds the `ctrl_c: tokio::sync::Notify` that was threaded
throughout our code. I think this made sense at one time, but now that
we handle Ctrl-C within the TUI and have a proper `Op::Interrupt` event,
I don't think this was quite right, so I removed it. For `codex exec`
and `codex proto`, we now use `tokio::signal::ctrl_c()` directly, but we
no longer make `Notify` a field of `Codex` or `CodexConversation`.
Changes of note:
- Adds the files `conversation_manager.rs` and `codex_conversation.rs`
to `codex-core`.
- `Codex` and `CodexSpawnOk` are no longer exported from `codex-core`:
other crates must use `CodexConversation` instead (which is created via
`ConversationManager`).
- `core/src/codex_wrapper.rs` has been deleted in favor of
`ConversationManager`.
- `ConversationManager::new_conversation()` returns `NewConversation`,
which is in line with the `new_conversation` tool we want to add to the
MCP server. Note `NewConversation` includes `SessionConfiguredEvent`, so
we eliminate checks in cases like `codex-rs/core/tests/client.rs` to
verify `SessionConfiguredEvent` is the first event because that is now
internal to `ConversationManager`.
- Quite a bit of code was deleted from
`codex-rs/mcp-server/src/message_processor.rs` since it no longer has to
manage multiple conversations itself: it goes through
`ConversationManager` instead.
- `core/tests/live_agent.rs` has been deleted because I had to update a
bunch of tests and all the tests in here were ignored, and I don't think
anyone ever ran them, so this was just technical debt, at this point.
- Removed `notify_on_sigint()` from `util.rs` (and in a follow-up, I
hope to refactor the blandly-named `util.rs` into more descriptive
files).
- In general, I started replacing local variables named `codex` as
`conversation`, where appropriate, though admittedly I didn't do it
through all the integration tests because that would have added a lot of
noise to this PR.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/openai/codex/pull/2240).
* #2264
* #2263
* __->__ #2240
2025-08-13 13:38:18 -07:00
|
|
|
|
#[error("no conversation with id: {0}")]
|
2025-09-07 20:22:25 -07:00
|
|
|
|
ConversationNotFound(ConversationId),
|
chore: introduce ConversationManager as a clearinghouse for all conversations (#2240)
This PR does two things because after I got deep into the first one I
started pulling on the thread to the second:
- Makes `ConversationManager` the place where all in-memory
conversations are created and stored. Previously, `MessageProcessor` in
the `codex-mcp-server` crate was doing this via its `session_map`, but
this is something that should be done in `codex-core`.
- It unwinds the `ctrl_c: tokio::sync::Notify` that was threaded
throughout our code. I think this made sense at one time, but now that
we handle Ctrl-C within the TUI and have a proper `Op::Interrupt` event,
I don't think this was quite right, so I removed it. For `codex exec`
and `codex proto`, we now use `tokio::signal::ctrl_c()` directly, but we
no longer make `Notify` a field of `Codex` or `CodexConversation`.
Changes of note:
- Adds the files `conversation_manager.rs` and `codex_conversation.rs`
to `codex-core`.
- `Codex` and `CodexSpawnOk` are no longer exported from `codex-core`:
other crates must use `CodexConversation` instead (which is created via
`ConversationManager`).
- `core/src/codex_wrapper.rs` has been deleted in favor of
`ConversationManager`.
- `ConversationManager::new_conversation()` returns `NewConversation`,
which is in line with the `new_conversation` tool we want to add to the
MCP server. Note `NewConversation` includes `SessionConfiguredEvent`, so
we eliminate checks in cases like `codex-rs/core/tests/client.rs` to
verify `SessionConfiguredEvent` is the first event because that is now
internal to `ConversationManager`.
- Quite a bit of code was deleted from
`codex-rs/mcp-server/src/message_processor.rs` since it no longer has to
manage multiple conversations itself: it goes through
`ConversationManager` instead.
- `core/tests/live_agent.rs` has been deleted because I had to update a
bunch of tests and all the tests in here were ignored, and I don't think
anyone ever ran them, so this was just technical debt, at this point.
- Removed `notify_on_sigint()` from `util.rs` (and in a follow-up, I
hope to refactor the blandly-named `util.rs` into more descriptive
files).
- In general, I started replacing local variables named `codex` as
`conversation`, where appropriate, though admittedly I didn't do it
through all the integration tests because that would have added a lot of
noise to this PR.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/openai/codex/pull/2240).
* #2264
* #2263
* __->__ #2240
2025-08-13 13:38:18 -07:00
|
|
|
|
|
|
|
|
|
|
#[error("session configured event was not the first event in the stream")]
|
|
|
|
|
|
SessionConfiguredNotFirstEvent,
|
|
|
|
|
|
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
/// Returned by run_command_stream when the spawned child process timed out (10s).
|
|
|
|
|
|
#[error("timeout waiting for child process to exit")]
|
|
|
|
|
|
Timeout,
|
|
|
|
|
|
|
|
|
|
|
|
/// Returned by run_command_stream when the child could not be spawned (its stdout/stderr pipes
|
|
|
|
|
|
/// could not be captured). Analogous to the previous `CodexError::Spawn` variant.
|
|
|
|
|
|
#[error("spawn failed: child stdout/stderr not captured")]
|
|
|
|
|
|
Spawn,
|
|
|
|
|
|
|
|
|
|
|
|
/// Returned by run_command_stream when the user pressed Ctrl‑C (SIGINT). Session uses this to
|
|
|
|
|
|
/// surface a polite FunctionCallOutput back to the model instead of crashing the CLI.
|
2025-05-08 21:46:06 -07:00
|
|
|
|
#[error("interrupted (Ctrl-C)")]
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
Interrupted,
|
|
|
|
|
|
|
|
|
|
|
|
/// Unexpected HTTP status code.
|
|
|
|
|
|
#[error("unexpected status {0}: {1}")]
|
|
|
|
|
|
UnexpectedStatus(StatusCode, String),
|
|
|
|
|
|
|
2025-08-07 18:24:34 -07:00
|
|
|
|
#[error("{0}")]
|
|
|
|
|
|
UsageLimitReached(UsageLimitReachedError),
|
2025-08-07 09:46:13 -07:00
|
|
|
|
|
2025-08-07 18:24:34 -07:00
|
|
|
|
#[error(
|
|
|
|
|
|
"To use Codex with your ChatGPT plan, upgrade to Plus: https://openai.com/chatgpt/pricing."
|
|
|
|
|
|
)]
|
2025-08-07 09:46:13 -07:00
|
|
|
|
UsageNotIncluded,
|
|
|
|
|
|
|
2025-08-07 19:01:53 -07:00
|
|
|
|
#[error("We're currently experiencing high demand, which may cause temporary errors.")]
|
2025-08-07 10:46:43 -07:00
|
|
|
|
InternalServerError,
|
|
|
|
|
|
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
/// Retry limit exceeded.
|
|
|
|
|
|
#[error("exceeded retry limit, last status: {0}")]
|
|
|
|
|
|
RetryLimit(StatusCode),
|
|
|
|
|
|
|
|
|
|
|
|
/// Agent loop died unexpectedly
|
|
|
|
|
|
#[error("internal error; agent loop died unexpectedly")]
|
|
|
|
|
|
InternalAgentDied,
|
|
|
|
|
|
|
|
|
|
|
|
/// Sandbox error
|
|
|
|
|
|
#[error("sandbox error: {0}")]
|
|
|
|
|
|
Sandbox(#[from] SandboxErr),
|
|
|
|
|
|
|
fix: overhaul how we spawn commands under seccomp/landlock on Linux (#1086)
Historically, we spawned the Seatbelt and Landlock sandboxes in
substantially different ways:
For **Seatbelt**, we would run `/usr/bin/sandbox-exec` with our policy
specified as an arg followed by the original command:
https://github.com/openai/codex/blob/d1de7bb383552e8fadd94be79d65d188e00fd562/codex-rs/core/src/exec.rs#L147-L219
For **Landlock/Seccomp**, we would do
`tokio::runtime::Builder::new_current_thread()`, _invoke
Landlock/Seccomp APIs to modify the permissions of that new thread_, and
then spawn the command:
https://github.com/openai/codex/blob/d1de7bb383552e8fadd94be79d65d188e00fd562/codex-rs/core/src/exec_linux.rs#L28-L49
While it is neat that Landlock/Seccomp supports applying a policy to
only one thread without having to apply it to the entire process, it
requires us to maintain two different codepaths and is a bit harder to
reason about. The tipping point was
https://github.com/openai/codex/pull/1061, in which we had to start
building up the `env` in an unexpected way for the existing
Landlock/Seccomp approach to continue to work.
This PR overhauls things so that we do similar things for Mac and Linux.
It turned out that we were already building our own "helper binary"
comparable to Mac's `sandbox-exec` as part of the `cli` crate:
https://github.com/openai/codex/blob/d1de7bb383552e8fadd94be79d65d188e00fd562/codex-rs/cli/Cargo.toml#L10-L12
We originally created this to build a small binary to include with the
Node.js version of the Codex CLI to provide support for Linux
sandboxing.
Though the sticky bit is that, at this point, we still want to deploy
the Rust version of Codex as a single, standalone binary rather than a
CLI and a supporting sandboxing binary. To satisfy this goal, we use
"the arg0 trick," in which we:
* use `std::env::current_exe()` to get the path to the CLI that is
currently running
* use the CLI as the `program` for the `Command`
* set `"codex-linux-sandbox"` as arg0 for the `Command`
A CLI that supports sandboxing should check arg0 at the start of the
program. If it is `"codex-linux-sandbox"`, it must invoke
`codex_linux_sandbox::run_main()`, which runs the CLI as if it were
`codex-linux-sandbox`. When acting as `codex-linux-sandbox`, we make the
appropriate Landlock/Seccomp API calls and then use `execvp(3)` to spawn
the original command, so do _replace_ the process rather than spawn a
subprocess. Incidentally, we do this before starting the Tokio runtime,
so the process should only have one thread when `execvp(3)` is called.
Because the `core` crate that needs to spawn the Linux sandboxing is not
a CLI in its own right, this means that every CLI that includes `core`
and relies on this behavior has to (1) implement it and (2) provide the
path to the sandboxing executable. While the path is almost always
`std::env::current_exe()`, we needed to make this configurable for
integration tests, so `Config` now has a `codex_linux_sandbox_exe:
Option<PathBuf>` property to facilitate threading this through,
introduced in https://github.com/openai/codex/pull/1089.
This common pattern is now captured in
`codex_linux_sandbox::run_with_sandbox()` and all of the `main.rs`
functions that should use it have been updated as part of this PR.
The `codex-linux-sandbox` crate added to the Cargo workspace as part of
this PR now has the bulk of the Landlock/Seccomp logic, which makes
`core` a bit simpler. Indeed, `core/src/exec_linux.rs` and
`core/src/landlock.rs` were removed/ported as part of this PR. I also
moved the unit tests for this code into an integration test,
`linux-sandbox/tests/landlock.rs`, in which I use
`env!("CARGO_BIN_EXE_codex-linux-sandbox")` as the value for
`codex_linux_sandbox_exe` since `std::env::current_exe()` is not
appropriate in that case.
2025-05-23 11:37:07 -07:00
|
|
|
|
#[error("codex-linux-sandbox was required but not provided")]
|
|
|
|
|
|
LandlockSandboxExecutableNotProvided,
|
|
|
|
|
|
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
|
|
// Automatic conversions for common external error types
|
|
|
|
|
|
// -----------------------------------------------------------------
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
Io(#[from] io::Error),
|
|
|
|
|
|
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
Reqwest(#[from] reqwest::Error),
|
|
|
|
|
|
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
Json(#[from] serde_json::Error),
|
|
|
|
|
|
|
|
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
LandlockRuleset(#[from] landlock::RulesetError),
|
|
|
|
|
|
|
|
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
LandlockPathFd(#[from] landlock::PathFdError),
|
|
|
|
|
|
|
|
|
|
|
|
#[error(transparent)]
|
|
|
|
|
|
TokioJoin(#[from] JoinError),
|
|
|
|
|
|
|
2025-05-08 21:46:06 -07:00
|
|
|
|
#[error("{0}")]
|
|
|
|
|
|
EnvVar(EnvVarError),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-07 18:24:34 -07:00
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
|
pub struct UsageLimitReachedError {
|
2025-09-11 18:01:25 -04:00
|
|
|
|
pub(crate) plan_type: Option<PlanType>,
|
|
|
|
|
|
pub(crate) resets_in_seconds: Option<u64>,
|
2025-08-07 18:24:34 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Display for UsageLimitReachedError {
|
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2025-09-11 18:01:25 -04:00
|
|
|
|
let message = match self.plan_type.as_ref() {
|
|
|
|
|
|
Some(PlanType::Known(KnownPlan::Plus)) => format!(
|
|
|
|
|
|
"You've hit your usage limit. Upgrade to Pro (https://openai.com/chatgpt/pricing){}",
|
|
|
|
|
|
retry_suffix_after_or(self.resets_in_seconds)
|
|
|
|
|
|
),
|
|
|
|
|
|
Some(PlanType::Known(KnownPlan::Team)) | Some(PlanType::Known(KnownPlan::Business)) => {
|
|
|
|
|
|
format!(
|
|
|
|
|
|
"You've hit your usage limit. To get more access now, send a request to your admin{}",
|
|
|
|
|
|
retry_suffix_after_or(self.resets_in_seconds)
|
|
|
|
|
|
)
|
2025-08-25 21:42:10 -07:00
|
|
|
|
}
|
2025-09-11 18:01:25 -04:00
|
|
|
|
Some(PlanType::Known(KnownPlan::Free)) => {
|
|
|
|
|
|
"To use Codex with your ChatGPT plan, upgrade to Plus: https://openai.com/chatgpt/pricing."
|
|
|
|
|
|
.to_string()
|
2025-08-25 21:42:10 -07:00
|
|
|
|
}
|
2025-09-11 18:01:25 -04:00
|
|
|
|
Some(PlanType::Known(KnownPlan::Pro))
|
|
|
|
|
|
| Some(PlanType::Known(KnownPlan::Enterprise))
|
|
|
|
|
|
| Some(PlanType::Known(KnownPlan::Edu)) => format!(
|
|
|
|
|
|
"You've hit your usage limit.{}",
|
|
|
|
|
|
retry_suffix(self.resets_in_seconds)
|
|
|
|
|
|
),
|
|
|
|
|
|
Some(PlanType::Unknown(_)) | None => format!(
|
|
|
|
|
|
"You've hit your usage limit.{}",
|
|
|
|
|
|
retry_suffix(self.resets_in_seconds)
|
|
|
|
|
|
),
|
|
|
|
|
|
};
|
2025-08-25 21:42:10 -07:00
|
|
|
|
|
2025-09-11 18:01:25 -04:00
|
|
|
|
write!(f, "{message}")
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn retry_suffix(resets_in_seconds: Option<u64>) -> String {
|
|
|
|
|
|
if let Some(secs) = resets_in_seconds {
|
|
|
|
|
|
let reset_duration = format_reset_duration(secs);
|
|
|
|
|
|
format!(" Try again in {reset_duration}.")
|
|
|
|
|
|
} else {
|
|
|
|
|
|
" Try again later.".to_string()
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn retry_suffix_after_or(resets_in_seconds: Option<u64>) -> String {
|
|
|
|
|
|
if let Some(secs) = resets_in_seconds {
|
|
|
|
|
|
let reset_duration = format_reset_duration(secs);
|
|
|
|
|
|
format!(" or try again in {reset_duration}.")
|
|
|
|
|
|
} else {
|
|
|
|
|
|
" or try again later.".to_string()
|
2025-08-07 18:24:34 -07:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-25 21:42:10 -07:00
|
|
|
|
fn format_reset_duration(total_secs: u64) -> String {
|
|
|
|
|
|
let days = total_secs / 86_400;
|
|
|
|
|
|
let hours = (total_secs % 86_400) / 3_600;
|
|
|
|
|
|
let minutes = (total_secs % 3_600) / 60;
|
|
|
|
|
|
|
|
|
|
|
|
let mut parts: Vec<String> = Vec::new();
|
|
|
|
|
|
if days > 0 {
|
|
|
|
|
|
let unit = if days == 1 { "day" } else { "days" };
|
2025-08-28 11:25:23 -07:00
|
|
|
|
parts.push(format!("{days} {unit}"));
|
2025-08-25 21:42:10 -07:00
|
|
|
|
}
|
|
|
|
|
|
if hours > 0 {
|
|
|
|
|
|
let unit = if hours == 1 { "hour" } else { "hours" };
|
2025-08-28 11:25:23 -07:00
|
|
|
|
parts.push(format!("{hours} {unit}"));
|
2025-08-25 21:42:10 -07:00
|
|
|
|
}
|
|
|
|
|
|
if minutes > 0 {
|
|
|
|
|
|
let unit = if minutes == 1 { "minute" } else { "minutes" };
|
2025-08-28 11:25:23 -07:00
|
|
|
|
parts.push(format!("{minutes} {unit}"));
|
2025-08-25 21:42:10 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if parts.is_empty() {
|
|
|
|
|
|
return "less than a minute".to_string();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
match parts.len() {
|
|
|
|
|
|
1 => parts[0].clone(),
|
|
|
|
|
|
2 => format!("{} {}", parts[0], parts[1]),
|
|
|
|
|
|
_ => format!("{} {} {}", parts[0], parts[1], parts[2]),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-08 21:46:06 -07:00
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
|
pub struct EnvVarError {
|
|
|
|
|
|
/// Name of the environment variable that is missing.
|
|
|
|
|
|
pub var: String,
|
|
|
|
|
|
|
|
|
|
|
|
/// Optional instructions to help the user get a valid value for the
|
|
|
|
|
|
/// variable and set it.
|
|
|
|
|
|
pub instructions: Option<String>,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Display for EnvVarError {
|
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
|
|
write!(f, "Missing environment variable: `{}`.", self.var)?;
|
|
|
|
|
|
if let Some(instructions) = &self.instructions {
|
|
|
|
|
|
write!(f, " {instructions}")?;
|
|
|
|
|
|
}
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
feat: initial import of Rust implementation of Codex CLI in codex-rs/ (#629)
As stated in `codex-rs/README.md`:
Today, Codex CLI is written in TypeScript and requires Node.js 22+ to
run it. For a number of users, this runtime requirement inhibits
adoption: they would be better served by a standalone executable. As
maintainers, we want Codex to run efficiently in a wide range of
environments with minimal overhead. We also want to take advantage of
operating system-specific APIs to provide better sandboxing, where
possible.
To that end, we are moving forward with a Rust implementation of Codex
CLI contained in this folder, which has the following benefits:
- The CLI compiles to small, standalone, platform-specific binaries.
- Can make direct, native calls to
[seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html) and
[landlock](https://man7.org/linux/man-pages/man7/landlock.7.html) in
order to support sandboxing on Linux.
- No runtime garbage collection, resulting in lower memory consumption
and better, more predictable performance.
Currently, the Rust implementation is materially behind the TypeScript
implementation in functionality, so continue to use the TypeScript
implmentation for the time being. We will publish native executables via
GitHub Releases as soon as we feel the Rust version is usable.
2025-04-24 13:31:40 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl CodexErr {
|
|
|
|
|
|
/// Minimal shim so that existing `e.downcast_ref::<CodexErr>()` checks continue to compile
|
|
|
|
|
|
/// after replacing `anyhow::Error` in the return signature. This mirrors the behavior of
|
|
|
|
|
|
/// `anyhow::Error::downcast_ref` but works directly on our concrete enum.
|
|
|
|
|
|
pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
|
|
|
|
|
|
(self as &dyn std::any::Any).downcast_ref::<T>()
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-08-06 23:25:56 -07:00
|
|
|
|
|
|
|
|
|
|
pub fn get_error_message_ui(e: &CodexErr) -> String {
|
|
|
|
|
|
match e {
|
2025-09-14 14:38:26 -07:00
|
|
|
|
CodexErr::Sandbox(SandboxErr::Denied { output }) => output.stderr.text.clone(),
|
2025-08-25 17:52:23 -07:00
|
|
|
|
// Timeouts are not sandbox errors from a UX perspective; present them plainly
|
2025-09-14 14:38:26 -07:00
|
|
|
|
CodexErr::Sandbox(SandboxErr::Timeout { output }) => format!(
|
|
|
|
|
|
"error: command timed out after {} ms",
|
|
|
|
|
|
output.duration.as_millis()
|
|
|
|
|
|
),
|
2025-08-06 23:25:56 -07:00
|
|
|
|
_ => e.to_string(),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-08-07 18:24:34 -07:00
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
|
mod tests {
|
|
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_plus_plan() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
2025-09-11 18:01:25 -04:00
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
resets_in_seconds: None,
|
2025-08-07 18:24:34 -07:00
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
"You've hit your usage limit. Upgrade to Pro (https://openai.com/chatgpt/pricing) or try again later."
|
2025-08-07 18:24:34 -07:00
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-11 18:01:25 -04:00
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_free_plan() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Free)),
|
|
|
|
|
|
resets_in_seconds: Some(3600),
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"To use Codex with your ChatGPT plan, upgrade to Plus: https://openai.com/chatgpt/pricing."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-07 18:24:34 -07:00
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_default_when_none() {
|
2025-08-25 21:42:10 -07:00
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: None,
|
|
|
|
|
|
resets_in_seconds: None,
|
|
|
|
|
|
};
|
2025-08-07 18:24:34 -07:00
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
"You've hit your usage limit. Try again later."
|
2025-08-07 18:24:34 -07:00
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-11 18:01:25 -04:00
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_team_plan() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Team)),
|
|
|
|
|
|
resets_in_seconds: Some(3600),
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. To get more access now, send a request to your admin or try again in 1 hour."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_business_plan_without_reset() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Business)),
|
|
|
|
|
|
resets_in_seconds: None,
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. To get more access now, send a request to your admin or try again later."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-07 18:24:34 -07:00
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_error_formats_default_for_other_plans() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
2025-09-11 18:01:25 -04:00
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Pro)),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
resets_in_seconds: None,
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. Try again later."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_includes_minutes_when_available() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: None,
|
|
|
|
|
|
resets_in_seconds: Some(5 * 60),
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. Try again in 5 minutes."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_includes_hours_and_minutes() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
2025-09-11 18:01:25 -04:00
|
|
|
|
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
resets_in_seconds: Some(3 * 3600 + 32 * 60),
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. Upgrade to Pro (https://openai.com/chatgpt/pricing) or try again in 3 hours 32 minutes."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_includes_days_hours_minutes() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: None,
|
|
|
|
|
|
resets_in_seconds: Some(2 * 86_400 + 3 * 3600 + 5 * 60),
|
|
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
|
|
|
|
|
"You've hit your usage limit. Try again in 2 days 3 hours 5 minutes."
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn usage_limit_reached_less_than_minute() {
|
|
|
|
|
|
let err = UsageLimitReachedError {
|
|
|
|
|
|
plan_type: None,
|
|
|
|
|
|
resets_in_seconds: Some(30),
|
2025-08-07 18:24:34 -07:00
|
|
|
|
};
|
|
|
|
|
|
assert_eq!(
|
|
|
|
|
|
err.to_string(),
|
2025-08-25 21:42:10 -07:00
|
|
|
|
"You've hit your usage limit. Try again in less than a minute."
|
2025-08-07 18:24:34 -07:00
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|