Vendor Codex and land Phase 1 Epiphany state slice
This commit is contained in:
parent
130e074c69
commit
2042687e30
3959 changed files with 953751 additions and 7 deletions
7
vendor/codex/codex-rs/exec/BUILD.bazel
vendored
Normal file
7
vendor/codex/codex-rs/exec/BUILD.bazel
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "exec",
|
||||
crate_name = "codex_exec",
|
||||
test_tags = ["no-sandbox"],
|
||||
)
|
||||
75
vendor/codex/codex-rs/exec/Cargo.toml
vendored
Normal file
75
vendor/codex/codex-rs/exec/Cargo.toml
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
[package]
|
||||
name = "codex-exec"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
autotests = false
|
||||
|
||||
[[bin]]
|
||||
name = "codex-exec"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
name = "codex_exec"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "all"
|
||||
path = "tests/all.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
codex-arg0 = { workspace = true }
|
||||
codex-app-server-client = { workspace = true }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-cloud-requirements = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-feedback = { workspace = true }
|
||||
codex-git-utils = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-otel = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-cli = { workspace = true }
|
||||
codex-utils-oss = { workspace = true }
|
||||
owo-colors = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
supports-color = { workspace = true }
|
||||
tokio = { workspace = true, features = [
|
||||
"io-std",
|
||||
"macros",
|
||||
"process",
|
||||
"rt-multi-thread",
|
||||
"signal",
|
||||
] }
|
||||
tracing = { workspace = true, features = ["log"] }
|
||||
tracing-subscriber = { workspace = true, features = ["env-filter"] }
|
||||
ts-rs = { workspace = true, features = [
|
||||
"uuid-impl",
|
||||
"serde-json-impl",
|
||||
"no-serde-warnings",
|
||||
] }
|
||||
uuid = { workspace = true }
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = { workspace = true }
|
||||
codex-apply-patch = { workspace = true }
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
core_test_support = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
opentelemetry = { workspace = true }
|
||||
opentelemetry_sdk = { workspace = true }
|
||||
predicates = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tracing-opentelemetry = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
walkdir = { workspace = true }
|
||||
wiremock = { workspace = true }
|
||||
285
vendor/codex/codex-rs/exec/src/cli.rs
vendored
Normal file
285
vendor/codex/codex-rs/exec/src/cli.rs
vendored
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
use clap::Args;
|
||||
use clap::FromArgMatches;
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::SharedCliOptions;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
version,
|
||||
override_usage = "codex exec [OPTIONS] [PROMPT]\n codex exec [OPTIONS] <COMMAND> [ARGS]"
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// Action to perform. If omitted, runs a new non-interactive session.
|
||||
#[command(subcommand)]
|
||||
pub command: Option<Command>,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub shared: ExecSharedCliOptions,
|
||||
|
||||
/// Allow running Codex outside a Git repository.
|
||||
#[arg(long = "skip-git-repo-check", global = true, default_value_t = false)]
|
||||
pub skip_git_repo_check: bool,
|
||||
|
||||
/// Run without persisting session files to disk.
|
||||
#[arg(long = "ephemeral", global = true, default_value_t = false)]
|
||||
pub ephemeral: bool,
|
||||
|
||||
/// Do not load `$CODEX_HOME/config.toml`; auth still uses `CODEX_HOME`.
|
||||
#[arg(long = "ignore-user-config", global = true, default_value_t = false)]
|
||||
pub ignore_user_config: bool,
|
||||
|
||||
/// Do not load user or project execpolicy `.rules` files.
|
||||
#[arg(long = "ignore-rules", global = true, default_value_t = false)]
|
||||
pub ignore_rules: bool,
|
||||
|
||||
/// Path to a JSON Schema file describing the model's final response shape.
|
||||
#[arg(long = "output-schema", value_name = "FILE")]
|
||||
pub output_schema: Option<PathBuf>,
|
||||
|
||||
#[clap(skip)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
/// Specifies color settings for use in the output.
|
||||
#[arg(long = "color", value_enum, default_value_t = Color::Auto)]
|
||||
pub color: Color,
|
||||
|
||||
/// Print events to stdout as JSONL.
|
||||
#[arg(
|
||||
long = "json",
|
||||
alias = "experimental-json",
|
||||
default_value_t = false,
|
||||
global = true
|
||||
)]
|
||||
pub json: bool,
|
||||
|
||||
/// Specifies file where the last message from the agent should be written.
|
||||
#[arg(
|
||||
long = "output-last-message",
|
||||
short = 'o',
|
||||
value_name = "FILE",
|
||||
global = true
|
||||
)]
|
||||
pub last_message_file: Option<PathBuf>,
|
||||
|
||||
/// Initial instructions for the agent. If not provided as an argument (or
|
||||
/// if `-` is used), instructions are read from stdin. If stdin is piped and
|
||||
/// a prompt is also provided, stdin is appended as a `<stdin>` block.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Cli {
|
||||
type Target = SharedCliOptions;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.shared.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for Cli {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.shared.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ExecSharedCliOptions(SharedCliOptions);
|
||||
|
||||
impl ExecSharedCliOptions {
|
||||
pub fn into_inner(self) -> SharedCliOptions {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ExecSharedCliOptions {
|
||||
type Target = SharedCliOptions;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for ExecSharedCliOptions {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Args for ExecSharedCliOptions {
|
||||
fn augment_args(cmd: clap::Command) -> clap::Command {
|
||||
mark_exec_global_args(SharedCliOptions::augment_args(cmd))
|
||||
}
|
||||
|
||||
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
|
||||
mark_exec_global_args(SharedCliOptions::augment_args_for_update(cmd))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromArgMatches for ExecSharedCliOptions {
|
||||
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
|
||||
SharedCliOptions::from_arg_matches(matches).map(Self)
|
||||
}
|
||||
|
||||
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
|
||||
self.0.update_from_arg_matches(matches)
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_exec_global_args(cmd: clap::Command) -> clap::Command {
|
||||
cmd.mut_arg("model", |arg| arg.global(true))
|
||||
.mut_arg("full_auto", |arg| arg.global(true))
|
||||
.mut_arg("dangerously_bypass_approvals_and_sandbox", |arg| {
|
||||
arg.global(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub enum Command {
|
||||
/// Resume a previous session by id or pick the most recent with --last.
|
||||
Resume(ResumeArgs),
|
||||
|
||||
/// Run a code review against the current repository.
|
||||
Review(ReviewArgs),
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
struct ResumeArgsRaw {
|
||||
// Note: This is the direct clap shape. We reinterpret the positional when --last is set
|
||||
// so "codex resume --last <prompt>" treats the positional as a prompt, not a session id.
|
||||
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
|
||||
/// If omitted, use --last to pick the most recent recorded session.
|
||||
#[arg(value_name = "SESSION_ID")]
|
||||
session_id: Option<String>,
|
||||
|
||||
/// Resume the most recent recorded session (newest) without specifying an id.
|
||||
#[arg(long = "last", default_value_t = false)]
|
||||
last: bool,
|
||||
|
||||
/// Show all sessions (disables cwd filtering).
|
||||
#[arg(long = "all", default_value_t = false)]
|
||||
all: bool,
|
||||
|
||||
/// Optional image(s) to attach to the prompt sent after resuming.
|
||||
#[arg(
|
||||
long = "image",
|
||||
short = 'i',
|
||||
value_name = "FILE",
|
||||
value_delimiter = ',',
|
||||
num_args = 1
|
||||
)]
|
||||
images: Vec<PathBuf>,
|
||||
|
||||
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResumeArgs {
|
||||
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
|
||||
/// If omitted, use --last to pick the most recent recorded session.
|
||||
pub session_id: Option<String>,
|
||||
|
||||
/// Resume the most recent recorded session (newest) without specifying an id.
|
||||
pub last: bool,
|
||||
|
||||
/// Show all sessions (disables cwd filtering).
|
||||
pub all: bool,
|
||||
|
||||
/// Optional image(s) to attach to the prompt sent after resuming.
|
||||
pub images: Vec<PathBuf>,
|
||||
|
||||
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ResumeArgsRaw> for ResumeArgs {
|
||||
fn from(raw: ResumeArgsRaw) -> Self {
|
||||
// When --last is used without an explicit prompt, treat the positional as the prompt
|
||||
// (clap can’t express this conditional positional meaning cleanly).
|
||||
let (session_id, prompt) = if raw.last && raw.prompt.is_none() {
|
||||
(None, raw.session_id)
|
||||
} else {
|
||||
(raw.session_id, raw.prompt)
|
||||
};
|
||||
Self {
|
||||
session_id,
|
||||
last: raw.last,
|
||||
all: raw.all,
|
||||
images: raw.images,
|
||||
prompt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Args for ResumeArgs {
|
||||
fn augment_args(cmd: clap::Command) -> clap::Command {
|
||||
ResumeArgsRaw::augment_args(cmd)
|
||||
}
|
||||
|
||||
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
|
||||
ResumeArgsRaw::augment_args_for_update(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromArgMatches for ResumeArgs {
|
||||
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
|
||||
ResumeArgsRaw::from_arg_matches(matches).map(Self::from)
|
||||
}
|
||||
|
||||
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
|
||||
*self = ResumeArgsRaw::from_arg_matches(matches).map(Self::from)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct ReviewArgs {
|
||||
/// Review staged, unstaged, and untracked changes.
|
||||
#[arg(
|
||||
long = "uncommitted",
|
||||
default_value_t = false,
|
||||
conflicts_with_all = ["base", "commit", "prompt"]
|
||||
)]
|
||||
pub uncommitted: bool,
|
||||
|
||||
/// Review changes against the given base branch.
|
||||
#[arg(
|
||||
long = "base",
|
||||
value_name = "BRANCH",
|
||||
conflicts_with_all = ["uncommitted", "commit", "prompt"]
|
||||
)]
|
||||
pub base: Option<String>,
|
||||
|
||||
/// Review the changes introduced by a commit.
|
||||
#[arg(
|
||||
long = "commit",
|
||||
value_name = "SHA",
|
||||
conflicts_with_all = ["uncommitted", "base", "prompt"]
|
||||
)]
|
||||
pub commit: Option<String>,
|
||||
|
||||
/// Optional commit title to display in the review summary.
|
||||
#[arg(long = "title", value_name = "TITLE", requires = "commit")]
|
||||
pub commit_title: Option<String>,
|
||||
|
||||
/// Custom review instructions. If `-` is used, read from stdin.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
|
||||
#[value(rename_all = "kebab-case")]
|
||||
pub enum Color {
|
||||
Always,
|
||||
Never,
|
||||
#[default]
|
||||
Auto,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cli_tests.rs"]
|
||||
mod tests;
|
||||
72
vendor/codex/codex-rs/exec/src/cli_tests.rs
vendored
Normal file
72
vendor/codex/codex-rs/exec/src/cli_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn resume_parses_prompt_after_global_flags() {
|
||||
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"--last",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--skip-git-repo-check",
|
||||
"--ephemeral",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert!(cli.ephemeral);
|
||||
assert!(cli.ignore_user_config);
|
||||
assert!(cli.ignore_rules);
|
||||
let Some(Command::Resume(args)) = cli.command else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
let effective_prompt = args.prompt.clone().or_else(|| {
|
||||
if args.last {
|
||||
args.session_id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_accepts_output_last_message_flag_after_subcommand() {
|
||||
const PROMPT: &str = "echo resume-with-output-file";
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"session-123",
|
||||
"-o",
|
||||
"/tmp/resume-output.md",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
cli.last_message_file,
|
||||
Some(PathBuf::from("/tmp/resume-output.md"))
|
||||
);
|
||||
let Some(Command::Resume(args)) = cli.command else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
assert_eq!(args.session_id.as_deref(), Some("session-123"));
|
||||
assert_eq!(args.prompt.as_deref(), Some(PROMPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_config_isolation_flags() {
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
"summarize",
|
||||
]);
|
||||
|
||||
assert!(cli.ignore_user_config);
|
||||
assert!(cli.ignore_rules);
|
||||
}
|
||||
48
vendor/codex/codex-rs/exec/src/event_processor.rs
vendored
Normal file
48
vendor/codex/codex-rs/exec/src/event_processor.rs
vendored
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
use std::path::Path;
|
||||
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::config::Config;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexStatus {
|
||||
Running,
|
||||
InitiateShutdown,
|
||||
}
|
||||
|
||||
pub(crate) trait EventProcessor {
|
||||
/// Print summary of effective configuration and user prompt.
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
);
|
||||
|
||||
/// Handle a single typed app-server notification emitted by the agent.
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus;
|
||||
|
||||
/// Handle a local exec warning that is not represented as an app-server notification.
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus;
|
||||
|
||||
fn print_final_output(&mut self) {}
|
||||
}
|
||||
|
||||
pub(crate) fn handle_last_message(last_agent_message: Option<&str>, output_file: &Path) {
|
||||
let message = last_agent_message.unwrap_or_default();
|
||||
write_last_message_file(message, Some(output_file));
|
||||
if last_agent_message.is_none() {
|
||||
eprintln!(
|
||||
"Warning: no last agent message; wrote empty content to {}",
|
||||
output_file.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_last_message_file(contents: &str, last_message_path: Option<&Path>) {
|
||||
if let Some(path) = last_message_path
|
||||
&& let Err(e) = std::fs::write(path, contents)
|
||||
{
|
||||
eprintln!("Failed to write last message file {path:?}: {e}");
|
||||
}
|
||||
}
|
||||
568
vendor/codex/codex-rs/exec/src/event_processor_with_human_output.rs
vendored
Normal file
568
vendor/codex/codex-rs/exec/src/event_processor_with_human_output.rs
vendored
Normal file
|
|
@ -0,0 +1,568 @@
|
|||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_app_server_protocol::CommandExecutionStatus;
|
||||
use codex_app_server_protocol::McpToolCallStatus;
|
||||
use codex_app_server_protocol::PatchApplyStatus;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::Config;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_protocol::num_format::format_with_separators;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use owo_colors::OwoColorize;
|
||||
use owo_colors::Style;
|
||||
|
||||
use crate::event_processor::CodexStatus;
|
||||
use crate::event_processor::EventProcessor;
|
||||
use crate::event_processor::handle_last_message;
|
||||
|
||||
pub(crate) struct EventProcessorWithHumanOutput {
|
||||
bold: Style,
|
||||
cyan: Style,
|
||||
dimmed: Style,
|
||||
green: Style,
|
||||
italic: Style,
|
||||
magenta: Style,
|
||||
red: Style,
|
||||
yellow: Style,
|
||||
show_agent_reasoning: bool,
|
||||
show_raw_agent_reasoning: bool,
|
||||
last_message_path: Option<PathBuf>,
|
||||
final_message: Option<String>,
|
||||
final_message_rendered: bool,
|
||||
emit_final_message_on_shutdown: bool,
|
||||
last_total_token_usage: Option<ThreadTokenUsage>,
|
||||
}
|
||||
|
||||
impl EventProcessorWithHumanOutput {
|
||||
pub(crate) fn create_with_ansi(
|
||||
with_ansi: bool,
|
||||
config: &Config,
|
||||
last_message_path: Option<PathBuf>,
|
||||
) -> Self {
|
||||
let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain };
|
||||
Self {
|
||||
bold: style(Style::new().bold(), Style::new()),
|
||||
cyan: style(Style::new().cyan(), Style::new()),
|
||||
dimmed: style(Style::new().dimmed(), Style::new()),
|
||||
green: style(Style::new().green(), Style::new()),
|
||||
italic: style(Style::new().italic(), Style::new()),
|
||||
magenta: style(Style::new().magenta(), Style::new()),
|
||||
red: style(Style::new().red(), Style::new()),
|
||||
yellow: style(Style::new().yellow(), Style::new()),
|
||||
show_agent_reasoning: !config.hide_agent_reasoning,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
last_message_path,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_started(&self, item: &ThreadItem) {
|
||||
match item {
|
||||
ThreadItem::CommandExecution { command, cwd, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{} in {}",
|
||||
"exec".style(self.italic).style(self.magenta),
|
||||
command.style(self.bold),
|
||||
cwd.display()
|
||||
);
|
||||
}
|
||||
ThreadItem::McpToolCall { server, tool, .. } => {
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
"mcp:".style(self.bold),
|
||||
format!("{server}/{tool}").style(self.cyan),
|
||||
"started".style(self.dimmed)
|
||||
);
|
||||
}
|
||||
ThreadItem::WebSearch { query, .. } => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), query);
|
||||
}
|
||||
ThreadItem::FileChange { .. } => {
|
||||
eprintln!("{}", "apply patch".style(self.bold));
|
||||
}
|
||||
ThreadItem::CollabAgentToolCall { tool, .. } => {
|
||||
eprintln!("{} {:?}", "collab:".style(self.bold), tool);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_completed(&mut self, item: ThreadItem) {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { text, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"codex".style(self.italic).style(self.magenta),
|
||||
text
|
||||
);
|
||||
self.final_message = Some(text);
|
||||
self.final_message_rendered = true;
|
||||
}
|
||||
ThreadItem::Reasoning {
|
||||
summary, content, ..
|
||||
} => {
|
||||
if self.show_agent_reasoning
|
||||
&& let Some(text) =
|
||||
reasoning_text(&summary, &content, self.show_raw_agent_reasoning)
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
eprintln!("{}", text.style(self.dimmed));
|
||||
}
|
||||
}
|
||||
ThreadItem::CommandExecution {
|
||||
command: _,
|
||||
aggregated_output,
|
||||
exit_code,
|
||||
status,
|
||||
duration_ms,
|
||||
..
|
||||
} => {
|
||||
let duration_suffix = duration_ms
|
||||
.map(|duration_ms| format!(" in {duration_ms}ms"))
|
||||
.unwrap_or_default();
|
||||
match status {
|
||||
CommandExecutionStatus::Completed => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" succeeded{duration_suffix}:").style(self.green)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::Failed => {
|
||||
let exit_code = exit_code.unwrap_or(1);
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" exited {exit_code}{duration_suffix}:").style(self.red)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::Declined => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" declined{duration_suffix}:").style(self.yellow)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::InProgress => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" in progress{duration_suffix}:").style(self.dimmed)
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(output) = aggregated_output
|
||||
&& !output.trim().is_empty()
|
||||
{
|
||||
eprintln!("{output}");
|
||||
}
|
||||
}
|
||||
ThreadItem::FileChange {
|
||||
changes, status, ..
|
||||
} => {
|
||||
let status_text = match status {
|
||||
PatchApplyStatus::Completed => "completed",
|
||||
PatchApplyStatus::Failed => "failed",
|
||||
PatchApplyStatus::Declined => "declined",
|
||||
PatchApplyStatus::InProgress => "in_progress",
|
||||
};
|
||||
eprintln!("{} {}", "patch:".style(self.bold), status_text);
|
||||
for change in changes {
|
||||
eprintln!("{}", change.path.style(self.dimmed));
|
||||
}
|
||||
}
|
||||
ThreadItem::McpToolCall {
|
||||
server,
|
||||
tool,
|
||||
status,
|
||||
error,
|
||||
..
|
||||
} => {
|
||||
let status_text = match status {
|
||||
McpToolCallStatus::Completed => "completed".style(self.green),
|
||||
McpToolCallStatus::Failed => "failed".style(self.red),
|
||||
McpToolCallStatus::InProgress => "in_progress".style(self.dimmed),
|
||||
};
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
"mcp:".style(self.bold),
|
||||
format!("{server}/{tool}").style(self.cyan),
|
||||
format!("({status_text})").style(self.dimmed)
|
||||
);
|
||||
if let Some(error) = error {
|
||||
eprintln!("{}", error.message.style(self.red));
|
||||
}
|
||||
}
|
||||
ThreadItem::WebSearch { query, .. } => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), query);
|
||||
}
|
||||
ThreadItem::ContextCompaction { .. } => {
|
||||
eprintln!("{}", "context compacted".style(self.dimmed));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventProcessor for EventProcessorWithHumanOutput {
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
) {
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
eprintln!("OpenAI Codex v{VERSION} (research preview)\n--------");
|
||||
for (key, value) in config_summary_entries(config, session_configured_event) {
|
||||
eprintln!("{} {}", format!("{key}:").style(self.bold), value);
|
||||
}
|
||||
eprintln!("--------");
|
||||
eprintln!("{}\n{}", "user".style(self.cyan), prompt);
|
||||
}
|
||||
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
|
||||
match notification {
|
||||
ServerNotification::ConfigWarning(notification) => {
|
||||
let details = notification
|
||||
.details
|
||||
.map(|details| format!(" ({details})"))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"{} {}{}",
|
||||
"warning:".style(self.yellow).style(self.bold),
|
||||
notification.summary,
|
||||
details
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::Error(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"ERROR:".style(self.red).style(self.bold),
|
||||
notification.error
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::DeprecationNotice(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"deprecated:".style(self.yellow).style(self.bold),
|
||||
notification.summary
|
||||
);
|
||||
if let Some(details) = notification.details {
|
||||
eprintln!("{}", details.style(self.dimmed));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookStarted(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"hook:".style(self.bold),
|
||||
format!("{:?}", notification.run.event_name).style(self.dimmed)
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookCompleted(notification) => {
|
||||
eprintln!(
|
||||
"{} {} {:?}",
|
||||
"hook:".style(self.bold),
|
||||
format!("{:?}", notification.run.event_name).style(self.dimmed),
|
||||
notification.run.status
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemStarted(notification) => {
|
||||
self.render_item_started(¬ification.item);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
self.render_item_completed(notification.item);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelRerouted(notification) => {
|
||||
eprintln!(
|
||||
"{} {} -> {}",
|
||||
"model rerouted:".style(self.yellow).style(self.bold),
|
||||
notification.from_model,
|
||||
notification.to_model
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification) => {
|
||||
self.last_total_token_usage = Some(notification.token_usage);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnCompleted(notification) => match notification.turn.status {
|
||||
TurnStatus::Completed => {
|
||||
let rendered_message = self
|
||||
.final_message_rendered
|
||||
.then(|| self.final_message.clone())
|
||||
.flatten();
|
||||
if let Some(final_message) =
|
||||
final_message_from_turn_items(notification.turn.items.as_slice())
|
||||
{
|
||||
self.final_message_rendered =
|
||||
rendered_message.as_deref() == Some(final_message.as_str());
|
||||
self.final_message = Some(final_message);
|
||||
}
|
||||
self.emit_final_message_on_shutdown = true;
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Failed => {
|
||||
self.final_message = None;
|
||||
self.final_message_rendered = false;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
if let Some(error) = notification.turn.error {
|
||||
eprintln!("{} {}", "ERROR:".style(self.red).style(self.bold), error);
|
||||
}
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Interrupted => {
|
||||
self.final_message = None;
|
||||
self.final_message_rendered = false;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
eprintln!("{}", "turn interrupted".style(self.dimmed));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::InProgress => CodexStatus::Running,
|
||||
},
|
||||
ServerNotification::TurnDiffUpdated(notification) => {
|
||||
if !notification.diff.trim().is_empty() {
|
||||
eprintln!("{}", notification.diff);
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnPlanUpdated(notification) => {
|
||||
if let Some(explanation) = notification.explanation {
|
||||
eprintln!("{}", explanation.style(self.italic));
|
||||
}
|
||||
for step in notification.plan {
|
||||
match step.status {
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Completed => {
|
||||
eprintln!(" {} {}", "✓".style(self.green), step.step);
|
||||
}
|
||||
codex_app_server_protocol::TurnPlanStepStatus::InProgress => {
|
||||
eprintln!(" {} {}", "→".style(self.cyan), step.step);
|
||||
}
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Pending => {
|
||||
eprintln!(
|
||||
" {} {}",
|
||||
"•".style(self.dimmed),
|
||||
step.step.style(self.dimmed)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnStarted(_) => CodexStatus::Running,
|
||||
_ => CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus {
|
||||
eprintln!(
|
||||
"{} {message}",
|
||||
"warning:".style(self.yellow).style(self.bold)
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
|
||||
fn print_final_output(&mut self) {
|
||||
if self.emit_final_message_on_shutdown
|
||||
&& let Some(path) = self.last_message_path.as_deref()
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path);
|
||||
}
|
||||
|
||||
if let Some(usage) = &self.last_total_token_usage {
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"tokens used".style(self.dimmed),
|
||||
format_with_separators(blended_total(usage))
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stdout)]
|
||||
if should_print_final_message_to_stdout(
|
||||
self.emit_final_message_on_shutdown
|
||||
.then_some(self.final_message.as_deref())
|
||||
.flatten(),
|
||||
std::io::stdout().is_terminal(),
|
||||
std::io::stderr().is_terminal(),
|
||||
) && let Some(message) = self.final_message.as_deref()
|
||||
{
|
||||
println!("{message}");
|
||||
} else if should_print_final_message_to_tty(
|
||||
self.emit_final_message_on_shutdown
|
||||
.then_some(self.final_message.as_deref())
|
||||
.flatten(),
|
||||
self.final_message_rendered,
|
||||
std::io::stdout().is_terminal(),
|
||||
std::io::stderr().is_terminal(),
|
||||
) && let Some(message) = self.final_message.as_deref()
|
||||
{
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"codex".style(self.italic).style(self.magenta),
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn config_summary_entries(
|
||||
config: &Config,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let mut entries = vec![
|
||||
("workdir", config.cwd.display().to_string()),
|
||||
("model", session_configured_event.model.clone()),
|
||||
(
|
||||
"provider",
|
||||
session_configured_event.model_provider_id.clone(),
|
||||
),
|
||||
(
|
||||
"approval",
|
||||
config.permissions.approval_policy.value().to_string(),
|
||||
),
|
||||
(
|
||||
"sandbox",
|
||||
summarize_sandbox_policy(config.permissions.sandbox_policy.get()),
|
||||
),
|
||||
];
|
||||
if config.model_provider.wire_api == WireApi::Responses {
|
||||
entries.push((
|
||||
"reasoning effort",
|
||||
config
|
||||
.model_reasoning_effort
|
||||
.map(|effort| effort.to_string())
|
||||
.unwrap_or_else(|| "none".to_string()),
|
||||
));
|
||||
entries.push((
|
||||
"reasoning summaries",
|
||||
config
|
||||
.model_reasoning_summary
|
||||
.map(|summary| summary.to_string())
|
||||
.unwrap_or_else(|| "none".to_string()),
|
||||
));
|
||||
}
|
||||
entries.push((
|
||||
"session id",
|
||||
session_configured_event.session_id.to_string(),
|
||||
));
|
||||
entries
|
||||
}
|
||||
|
||||
fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String {
|
||||
match sandbox_policy {
|
||||
SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(),
|
||||
SandboxPolicy::ReadOnly { network_access, .. } => {
|
||||
let mut summary = "read-only".to_string();
|
||||
if *network_access {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
SandboxPolicy::ExternalSandbox { network_access } => {
|
||||
let mut summary = "external-sandbox".to_string();
|
||||
if matches!(
|
||||
network_access,
|
||||
codex_protocol::protocol::NetworkAccess::Enabled
|
||||
) {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots,
|
||||
network_access,
|
||||
exclude_tmpdir_env_var,
|
||||
exclude_slash_tmp,
|
||||
read_only_access: _,
|
||||
} => {
|
||||
let mut summary = "workspace-write".to_string();
|
||||
let mut writable_entries = vec!["workdir".to_string()];
|
||||
if !*exclude_slash_tmp {
|
||||
writable_entries.push("/tmp".to_string());
|
||||
}
|
||||
if !*exclude_tmpdir_env_var {
|
||||
writable_entries.push("$TMPDIR".to_string());
|
||||
}
|
||||
writable_entries.extend(
|
||||
writable_roots
|
||||
.iter()
|
||||
.map(|path| path.to_string_lossy().to_string()),
|
||||
);
|
||||
summary.push_str(&format!(" [{}]", writable_entries.join(", ")));
|
||||
if *network_access {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reasoning_text(
|
||||
summary: &[String],
|
||||
content: &[String],
|
||||
show_raw_agent_reasoning: bool,
|
||||
) -> Option<String> {
|
||||
let entries = if show_raw_agent_reasoning && !content.is_empty() {
|
||||
content
|
||||
} else {
|
||||
summary
|
||||
};
|
||||
if entries.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(entries.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn final_message_from_turn_items(items: &[ThreadItem]) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item {
|
||||
ThreadItem::Plan { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn blended_total(usage: &ThreadTokenUsage) -> i64 {
|
||||
let cached_input = usage.total.cached_input_tokens.max(0);
|
||||
let non_cached_input = (usage.total.input_tokens - cached_input).max(0);
|
||||
(non_cached_input + usage.total.output_tokens.max(0)).max(0)
|
||||
}
|
||||
|
||||
fn should_print_final_message_to_stdout(
|
||||
final_message: Option<&str>,
|
||||
stdout_is_terminal: bool,
|
||||
stderr_is_terminal: bool,
|
||||
) -> bool {
|
||||
final_message.is_some() && !(stdout_is_terminal && stderr_is_terminal)
|
||||
}
|
||||
|
||||
fn should_print_final_message_to_tty(
|
||||
final_message: Option<&str>,
|
||||
final_message_rendered: bool,
|
||||
stdout_is_terminal: bool,
|
||||
stderr_is_terminal: bool,
|
||||
) -> bool {
|
||||
final_message.is_some() && !final_message_rendered && stdout_is_terminal && stderr_is_terminal
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_processor_with_human_output_tests.rs"]
|
||||
mod tests;
|
||||
361
vendor/codex/codex-rs/exec/src/event_processor_with_human_output_tests.rs
vendored
Normal file
361
vendor/codex/codex-rs/exec/src/event_processor_with_human_output_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use owo_colors::Style;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::EventProcessorWithHumanOutput;
|
||||
use super::final_message_from_turn_items;
|
||||
use super::reasoning_text;
|
||||
use super::should_print_final_message_to_stdout;
|
||||
use super::should_print_final_message_to_tty;
|
||||
use crate::event_processor::EventProcessor;
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_stdout_message_when_both_streams_are_terminals() {
|
||||
assert!(!should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_stdout_message_when_stdout_is_not_terminal() {
|
||||
assert!(should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ false,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_stdout_message_when_stderr_is_not_terminal() {
|
||||
assert!(should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_stdout_message_when_missing() {
|
||||
assert!(!should_print_final_message_to_stdout(
|
||||
/*final_message*/ None, /*stdout_is_terminal*/ false,
|
||||
/*stderr_is_terminal*/ false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_tty_message_when_not_yet_rendered() {
|
||||
assert!(should_print_final_message_to_tty(
|
||||
Some("hello"),
|
||||
/*final_message_rendered*/ false,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_tty_message_when_already_rendered() {
|
||||
assert!(!should_print_final_message_to_tty(
|
||||
Some("hello"),
|
||||
/*final_message_rendered*/ true,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_text_prefers_summary_when_raw_reasoning_is_hidden() {
|
||||
let text = reasoning_text(
|
||||
&["summary".to_string()],
|
||||
&["raw".to_string()],
|
||||
/*show_raw_agent_reasoning*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(text.as_deref(), Some("summary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_text_uses_raw_content_when_enabled() {
|
||||
let text = reasoning_text(
|
||||
&["summary".to_string()],
|
||||
&["raw".to_string()],
|
||||
/*show_raw_agent_reasoning*/ true,
|
||||
);
|
||||
|
||||
assert_eq!(text.as_deref(), Some("raw"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_message_from_turn_items_uses_latest_agent_message() {
|
||||
let message = final_message_from_turn_items(&[
|
||||
ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "first".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
},
|
||||
ThreadItem::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "plan".to_string(),
|
||||
},
|
||||
ThreadItem::AgentMessage {
|
||||
id: "msg-2".to_string(),
|
||||
text: "second".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(message.as_deref(), Some("second"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_message_from_turn_items_falls_back_to_latest_plan() {
|
||||
let message = final_message_from_turn_items(&[
|
||||
ThreadItem::Reasoning {
|
||||
id: "reasoning-1".to_string(),
|
||||
summary: vec!["inspect".to_string()],
|
||||
content: Vec::new(),
|
||||
},
|
||||
ThreadItem::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "first plan".to_string(),
|
||||
},
|
||||
ThreadItem::Plan {
|
||||
id: "plan-2".to_string(),
|
||||
text: "final plan".to_string(),
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(message.as_deref(), Some("final plan"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_recovers_final_message_from_turn_items() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: vec![ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
}],
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_overwrites_stale_final_message_from_turn_items() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("stale answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: vec![ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
}],
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
|
||||
assert!(!processor.final_message_rendered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("streamed answer".to_string()),
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("streamed answer"));
|
||||
assert!(processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_failed_clears_stale_final_message() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("partial answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: true,
|
||||
last_total_token_usage: None,
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Failed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message, None);
|
||||
assert!(!processor.final_message_rendered);
|
||||
assert!(!processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_interrupted_clears_stale_final_message() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("partial answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: true,
|
||||
last_total_token_usage: None,
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Interrupted,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message, None);
|
||||
assert!(!processor.final_message_rendered);
|
||||
assert!(!processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
625
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output.rs
vendored
Normal file
625
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output.rs
vendored
Normal file
|
|
@ -0,0 +1,625 @@
|
|||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_app_server_protocol::CollabAgentTool;
|
||||
use codex_app_server_protocol::CollabAgentToolCallStatus;
|
||||
use codex_app_server_protocol::CommandExecutionStatus;
|
||||
use codex_app_server_protocol::McpToolCallStatus;
|
||||
use codex_app_server_protocol::PatchApplyStatus;
|
||||
use codex_app_server_protocol::PatchChangeKind;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::Config;
|
||||
use codex_protocol::models::WebSearchAction;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use serde_json::json;
|
||||
|
||||
pub use crate::event_processor::CodexStatus;
|
||||
use crate::event_processor::EventProcessor;
|
||||
use crate::event_processor::handle_last_message;
|
||||
use crate::exec_events::AgentMessageItem;
|
||||
use crate::exec_events::CollabAgentState;
|
||||
use crate::exec_events::CollabAgentStatus;
|
||||
use crate::exec_events::CollabTool;
|
||||
use crate::exec_events::CollabToolCallItem;
|
||||
use crate::exec_events::CollabToolCallStatus;
|
||||
use crate::exec_events::CommandExecutionItem;
|
||||
use crate::exec_events::CommandExecutionStatus as ExecCommandExecutionStatus;
|
||||
use crate::exec_events::ErrorItem;
|
||||
use crate::exec_events::FileChangeItem;
|
||||
use crate::exec_events::FileUpdateChange;
|
||||
use crate::exec_events::ItemCompletedEvent;
|
||||
use crate::exec_events::ItemStartedEvent;
|
||||
use crate::exec_events::ItemUpdatedEvent;
|
||||
use crate::exec_events::McpToolCallItem;
|
||||
use crate::exec_events::McpToolCallItemError;
|
||||
use crate::exec_events::McpToolCallItemResult;
|
||||
use crate::exec_events::McpToolCallStatus as ExecMcpToolCallStatus;
|
||||
use crate::exec_events::PatchApplyStatus as ExecPatchApplyStatus;
|
||||
use crate::exec_events::PatchChangeKind as ExecPatchChangeKind;
|
||||
use crate::exec_events::ReasoningItem;
|
||||
use crate::exec_events::ThreadErrorEvent;
|
||||
use crate::exec_events::ThreadEvent;
|
||||
use crate::exec_events::ThreadItem as ExecThreadItem;
|
||||
use crate::exec_events::ThreadItemDetails;
|
||||
use crate::exec_events::ThreadStartedEvent;
|
||||
use crate::exec_events::TodoItem;
|
||||
use crate::exec_events::TodoListItem;
|
||||
use crate::exec_events::TurnCompletedEvent;
|
||||
use crate::exec_events::TurnFailedEvent;
|
||||
use crate::exec_events::TurnStartedEvent;
|
||||
use crate::exec_events::Usage;
|
||||
use crate::exec_events::WebSearchItem;
|
||||
|
||||
pub struct EventProcessorWithJsonOutput {
|
||||
last_message_path: Option<PathBuf>,
|
||||
next_item_id: AtomicU64,
|
||||
raw_to_exec_item_id: HashMap<String, String>,
|
||||
running_todo_list: Option<RunningTodoList>,
|
||||
last_total_token_usage: Option<ThreadTokenUsage>,
|
||||
last_critical_error: Option<ThreadErrorEvent>,
|
||||
final_message: Option<String>,
|
||||
emit_final_message_on_shutdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct RunningTodoList {
|
||||
item_id: String,
|
||||
items: Vec<TodoItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct CollectedThreadEvents {
|
||||
pub events: Vec<ThreadEvent>,
|
||||
pub status: CodexStatus,
|
||||
}
|
||||
|
||||
impl EventProcessorWithJsonOutput {
|
||||
pub fn new(last_message_path: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
last_message_path,
|
||||
next_item_id: AtomicU64::new(0),
|
||||
raw_to_exec_item_id: HashMap::new(),
|
||||
running_todo_list: None,
|
||||
last_total_token_usage: None,
|
||||
last_critical_error: None,
|
||||
final_message: None,
|
||||
emit_final_message_on_shutdown: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn final_message(&self) -> Option<&str> {
|
||||
self.final_message.as_deref()
|
||||
}
|
||||
|
||||
fn next_item_id(&self) -> String {
|
||||
format!("item_{}", self.next_item_id.fetch_add(1, Ordering::SeqCst))
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stdout)]
|
||||
fn emit(&self, event: ThreadEvent) {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&event).unwrap_or_else(|err| {
|
||||
json!({
|
||||
"type": "error",
|
||||
"message": format!("failed to serialize exec json event: {err}"),
|
||||
})
|
||||
.to_string()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn usage_from_last_total(&self) -> Usage {
|
||||
let Some(usage) = self.last_total_token_usage.as_ref() else {
|
||||
return Usage::default();
|
||||
};
|
||||
Usage {
|
||||
input_tokens: usage.total.input_tokens,
|
||||
cached_input_tokens: usage.total.cached_input_tokens,
|
||||
output_tokens: usage.total.output_tokens,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_todo_items(plan: &[codex_app_server_protocol::TurnPlanStep]) -> Vec<TodoItem> {
|
||||
plan.iter()
|
||||
.map(|step| TodoItem {
|
||||
text: step.step.clone(),
|
||||
completed: matches!(
|
||||
step.status,
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Completed
|
||||
),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn map_item_with_id(
|
||||
item: ThreadItem,
|
||||
make_id: impl FnOnce() -> String,
|
||||
) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::AgentMessage(AgentMessageItem { text }),
|
||||
}),
|
||||
ThreadItem::Reasoning { summary, .. } => {
|
||||
let text = summary.join("\n");
|
||||
if text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::Reasoning(ReasoningItem { text }),
|
||||
})
|
||||
}
|
||||
ThreadItem::CommandExecution {
|
||||
command,
|
||||
aggregated_output,
|
||||
exit_code,
|
||||
status,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::CommandExecution(CommandExecutionItem {
|
||||
command,
|
||||
aggregated_output: aggregated_output.unwrap_or_default(),
|
||||
exit_code,
|
||||
status: match status {
|
||||
CommandExecutionStatus::InProgress => ExecCommandExecutionStatus::InProgress,
|
||||
CommandExecutionStatus::Completed => ExecCommandExecutionStatus::Completed,
|
||||
CommandExecutionStatus::Failed => ExecCommandExecutionStatus::Failed,
|
||||
CommandExecutionStatus::Declined => ExecCommandExecutionStatus::Declined,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::FileChange {
|
||||
changes, status, ..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::FileChange(FileChangeItem {
|
||||
changes: changes
|
||||
.into_iter()
|
||||
.map(|change| FileUpdateChange {
|
||||
path: change.path,
|
||||
kind: match change.kind {
|
||||
PatchChangeKind::Add => ExecPatchChangeKind::Add,
|
||||
PatchChangeKind::Delete => ExecPatchChangeKind::Delete,
|
||||
PatchChangeKind::Update { .. } => ExecPatchChangeKind::Update,
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
status: match status {
|
||||
PatchApplyStatus::InProgress => ExecPatchApplyStatus::InProgress,
|
||||
PatchApplyStatus::Completed => ExecPatchApplyStatus::Completed,
|
||||
PatchApplyStatus::Failed | PatchApplyStatus::Declined => {
|
||||
ExecPatchApplyStatus::Failed
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::McpToolCall {
|
||||
server,
|
||||
tool,
|
||||
status,
|
||||
arguments,
|
||||
result,
|
||||
error,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::McpToolCall(McpToolCallItem {
|
||||
server,
|
||||
tool,
|
||||
status: match status {
|
||||
McpToolCallStatus::InProgress => ExecMcpToolCallStatus::InProgress,
|
||||
McpToolCallStatus::Completed => ExecMcpToolCallStatus::Completed,
|
||||
McpToolCallStatus::Failed => ExecMcpToolCallStatus::Failed,
|
||||
},
|
||||
arguments,
|
||||
result: result.map(|result| McpToolCallItemResult {
|
||||
content: result.content,
|
||||
structured_content: result.structured_content,
|
||||
}),
|
||||
error: error.map(|error| McpToolCallItemError {
|
||||
message: error.message,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
ThreadItem::CollabAgentToolCall {
|
||||
tool,
|
||||
sender_thread_id,
|
||||
receiver_thread_ids,
|
||||
prompt,
|
||||
agents_states,
|
||||
status,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::CollabToolCall(CollabToolCallItem {
|
||||
tool: match tool {
|
||||
CollabAgentTool::SpawnAgent => CollabTool::SpawnAgent,
|
||||
CollabAgentTool::SendInput => CollabTool::SendInput,
|
||||
CollabAgentTool::ResumeAgent => CollabTool::Wait,
|
||||
CollabAgentTool::Wait => CollabTool::Wait,
|
||||
CollabAgentTool::CloseAgent => CollabTool::CloseAgent,
|
||||
},
|
||||
sender_thread_id,
|
||||
receiver_thread_ids,
|
||||
prompt,
|
||||
agents_states: agents_states
|
||||
.into_iter()
|
||||
.map(|(thread_id, state)| {
|
||||
(
|
||||
thread_id,
|
||||
CollabAgentState {
|
||||
status: match state.status {
|
||||
codex_app_server_protocol::CollabAgentStatus::PendingInit => {
|
||||
CollabAgentStatus::PendingInit
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Running => {
|
||||
CollabAgentStatus::Running
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Interrupted => {
|
||||
CollabAgentStatus::Interrupted
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Completed => {
|
||||
CollabAgentStatus::Completed
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Errored => {
|
||||
CollabAgentStatus::Errored
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Shutdown => {
|
||||
CollabAgentStatus::Shutdown
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::NotFound => {
|
||||
CollabAgentStatus::NotFound
|
||||
}
|
||||
},
|
||||
message: state.message,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
status: match status {
|
||||
CollabAgentToolCallStatus::InProgress => CollabToolCallStatus::InProgress,
|
||||
CollabAgentToolCallStatus::Completed => CollabToolCallStatus::Completed,
|
||||
CollabAgentToolCallStatus::Failed => CollabToolCallStatus::Failed,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::WebSearch {
|
||||
id: raw_id,
|
||||
query,
|
||||
action,
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::WebSearch(WebSearchItem {
|
||||
id: raw_id,
|
||||
query,
|
||||
action: match action {
|
||||
Some(action) => serde_json::from_value(
|
||||
serde_json::to_value(action).unwrap_or_else(|_| json!("other")),
|
||||
)
|
||||
.unwrap_or(WebSearchAction::Other),
|
||||
None => WebSearchAction::Other,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn started_item_id(&mut self, raw_id: &str) -> String {
|
||||
if let Some(existing) = self.raw_to_exec_item_id.get(raw_id) {
|
||||
return existing.clone();
|
||||
}
|
||||
let exec_id = self.next_item_id();
|
||||
self.raw_to_exec_item_id
|
||||
.insert(raw_id.to_string(), exec_id.clone());
|
||||
exec_id
|
||||
}
|
||||
|
||||
fn completed_item_id(&mut self, raw_id: &str) -> String {
|
||||
self.raw_to_exec_item_id
|
||||
.remove(raw_id)
|
||||
.unwrap_or_else(|| self.next_item_id())
|
||||
}
|
||||
|
||||
fn map_started_item(&mut self, item: ThreadItem) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { .. } | ThreadItem::Reasoning { .. } => None,
|
||||
other => {
|
||||
let raw_id = other.id().to_string();
|
||||
Self::map_item_with_id(other, || self.started_item_id(&raw_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_completed_item_mut(&mut self, item: ThreadItem) -> Option<ExecThreadItem> {
|
||||
if let ThreadItem::Reasoning { summary, .. } = &item
|
||||
&& summary.join("\n").trim().is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match &item {
|
||||
ThreadItem::AgentMessage { .. } | ThreadItem::Reasoning { .. } => {
|
||||
Self::map_item_with_id(item, || self.next_item_id())
|
||||
}
|
||||
other => {
|
||||
let raw_id = other.id().to_string();
|
||||
Self::map_item_with_id(item, || self.completed_item_id(&raw_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_unfinished_started_items(
|
||||
&mut self,
|
||||
turn_items: &[ThreadItem],
|
||||
) -> Vec<ThreadEvent> {
|
||||
turn_items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let raw_id = item.id().to_string();
|
||||
if !self.raw_to_exec_item_id.contains_key(&raw_id) {
|
||||
return None;
|
||||
}
|
||||
self.map_completed_item_mut(item.clone())
|
||||
.map(|item| ThreadEvent::ItemCompleted(ItemCompletedEvent { item }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn final_message_from_turn_items(items: &[ThreadItem]) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item {
|
||||
ThreadItem::Plan { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn thread_started_event(session_configured: &SessionConfiguredEvent) -> ThreadEvent {
|
||||
ThreadEvent::ThreadStarted(ThreadStartedEvent {
|
||||
thread_id: session_configured.session_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn collect_warning(&mut self, message: String) -> CollectedThreadEvents {
|
||||
CollectedThreadEvents {
|
||||
events: vec![ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
})],
|
||||
status: CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_thread_events(
|
||||
&mut self,
|
||||
notification: ServerNotification,
|
||||
) -> CollectedThreadEvents {
|
||||
let mut events = Vec::new();
|
||||
let status = match notification {
|
||||
ServerNotification::ConfigWarning(notification) => {
|
||||
let message = match notification.details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.summary)
|
||||
}
|
||||
_ => notification.summary,
|
||||
};
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::Error(notification) => {
|
||||
let message = match notification.error.additional_details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.error.message)
|
||||
}
|
||||
_ => notification.error.message,
|
||||
};
|
||||
let error = ThreadErrorEvent { message };
|
||||
self.last_critical_error = Some(error.clone());
|
||||
events.push(ThreadEvent::Error(error));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::DeprecationNotice(notification) => {
|
||||
let message = match notification.details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.summary)
|
||||
}
|
||||
_ => notification.summary,
|
||||
};
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookStarted(_) | ServerNotification::HookCompleted(_) => {
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemStarted(notification) => {
|
||||
if let Some(item) = self.map_started_item(notification.item) {
|
||||
events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
if let Some(item) = self.map_completed_item_mut(notification.item) {
|
||||
if let ThreadItemDetails::AgentMessage(AgentMessageItem { text }) =
|
||||
&item.details
|
||||
{
|
||||
self.final_message = Some(text.clone());
|
||||
}
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item }));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelRerouted(notification) => {
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem {
|
||||
message: format!(
|
||||
"model rerouted: {} -> {} ({:?})",
|
||||
notification.from_model, notification.to_model, notification.reason
|
||||
),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification) => {
|
||||
self.last_total_token_usage = Some(notification.token_usage);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnCompleted(notification) => {
|
||||
if let Some(running) = self.running_todo_list.take() {
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: running.item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem {
|
||||
items: running.items,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
}
|
||||
events.extend(self.reconcile_unfinished_started_items(¬ification.turn.items));
|
||||
match notification.turn.status {
|
||||
TurnStatus::Completed => {
|
||||
if let Some(final_message) =
|
||||
Self::final_message_from_turn_items(notification.turn.items.as_slice())
|
||||
{
|
||||
self.final_message = Some(final_message);
|
||||
}
|
||||
self.emit_final_message_on_shutdown = true;
|
||||
events.push(ThreadEvent::TurnCompleted(TurnCompletedEvent {
|
||||
usage: self.usage_from_last_total(),
|
||||
}));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Failed => {
|
||||
self.final_message = None;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
let error = notification
|
||||
.turn
|
||||
.error
|
||||
.map(|error| ThreadErrorEvent {
|
||||
message: match error.additional_details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", error.message)
|
||||
}
|
||||
_ => error.message,
|
||||
},
|
||||
})
|
||||
.or_else(|| self.last_critical_error.clone())
|
||||
.unwrap_or_else(|| ThreadErrorEvent {
|
||||
message: "turn failed".to_string(),
|
||||
});
|
||||
events.push(ThreadEvent::TurnFailed(TurnFailedEvent { error }));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Interrupted => {
|
||||
self.final_message = None;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::InProgress => CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
ServerNotification::TurnDiffUpdated(_) => CodexStatus::Running,
|
||||
ServerNotification::TurnPlanUpdated(notification) => {
|
||||
let items = Self::map_todo_items(¬ification.plan);
|
||||
if let Some(running) = self.running_todo_list.as_mut() {
|
||||
running.items = items.clone();
|
||||
let item_id = running.item_id.clone();
|
||||
events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem { items }),
|
||||
},
|
||||
}));
|
||||
} else {
|
||||
let item_id = self.next_item_id();
|
||||
self.running_todo_list = Some(RunningTodoList {
|
||||
item_id: item_id.clone(),
|
||||
items: items.clone(),
|
||||
});
|
||||
events.push(ThreadEvent::ItemStarted(ItemStartedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem { items }),
|
||||
},
|
||||
}));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnStarted(_) => {
|
||||
events.push(ThreadEvent::TurnStarted(TurnStartedEvent {}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
_ => CodexStatus::Running,
|
||||
};
|
||||
|
||||
CollectedThreadEvents { events, status }
|
||||
}
|
||||
}
|
||||
|
||||
impl EventProcessor for EventProcessorWithJsonOutput {
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
_: &Config,
|
||||
_: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
) {
|
||||
self.emit(Self::thread_started_event(session_configured));
|
||||
}
|
||||
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
|
||||
let collected = self.collect_thread_events(notification);
|
||||
for event in collected.events {
|
||||
self.emit(event);
|
||||
}
|
||||
collected.status
|
||||
}
|
||||
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus {
|
||||
let collected = self.collect_warning(message);
|
||||
for event in collected.events {
|
||||
self.emit(event);
|
||||
}
|
||||
collected.status
|
||||
}
|
||||
|
||||
fn print_final_output(&mut self) {
|
||||
if self.emit_final_message_on_shutdown
|
||||
&& let Some(path) = self.last_message_path.as_deref()
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_processor_with_jsonl_output_tests.rs"]
|
||||
mod tests;
|
||||
57
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
vendored
Normal file
57
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn failed_turn_does_not_overwrite_output_last_message_file() {
|
||||
let tempdir = tempdir().expect("create tempdir");
|
||||
let output_path = tempdir.path().join("last-message.txt");
|
||||
std::fs::write(&output_path, "keep existing contents").expect("seed output file");
|
||||
|
||||
let mut processor = EventProcessorWithJsonOutput::new(Some(output_path.clone()));
|
||||
|
||||
let collected = processor.collect_thread_events(ServerNotification::ItemCompleted(
|
||||
codex_app_server_protocol::ItemCompletedNotification {
|
||||
item: ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "partial answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
},
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(collected.status, CodexStatus::Running);
|
||||
assert_eq!(processor.final_message(), Some("partial answer"));
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Failed,
|
||||
error: Some(codex_app_server_protocol::TurnError {
|
||||
message: "turn failed".to_string(),
|
||||
additional_details: None,
|
||||
codex_error_info: None,
|
||||
}),
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(status, CodexStatus::InitiateShutdown);
|
||||
assert_eq!(processor.final_message(), None);
|
||||
|
||||
EventProcessor::print_final_output(&mut processor);
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&output_path).expect("read output file"),
|
||||
"keep existing contents"
|
||||
);
|
||||
}
|
||||
312
vendor/codex/codex-rs/exec/src/exec_events.rs
vendored
Normal file
312
vendor/codex/codex-rs/exec/src/exec_events.rs
vendored
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
use codex_protocol::models::WebSearchAction;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::HashMap;
|
||||
use ts_rs::TS;
|
||||
|
||||
/// Top-level JSONL events emitted by codex exec
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ThreadEvent {
|
||||
/// Emitted when a new thread is started as the first event.
|
||||
#[serde(rename = "thread.started")]
|
||||
ThreadStarted(ThreadStartedEvent),
|
||||
/// Emitted when a turn is started by sending a new prompt to the model.
|
||||
/// A turn encompasses all events that happen while agent is processing the prompt.
|
||||
#[serde(rename = "turn.started")]
|
||||
TurnStarted(TurnStartedEvent),
|
||||
/// Emitted when a turn is completed. Typically right after the assistant's response.
|
||||
#[serde(rename = "turn.completed")]
|
||||
TurnCompleted(TurnCompletedEvent),
|
||||
/// Indicates that a turn failed with an error.
|
||||
#[serde(rename = "turn.failed")]
|
||||
TurnFailed(TurnFailedEvent),
|
||||
/// Emitted when a new item is added to the thread. Typically the item will be in an "in progress" state.
|
||||
#[serde(rename = "item.started")]
|
||||
ItemStarted(ItemStartedEvent),
|
||||
/// Emitted when an item is updated.
|
||||
#[serde(rename = "item.updated")]
|
||||
ItemUpdated(ItemUpdatedEvent),
|
||||
/// Signals that an item has reached a terminal state—either success or failure.
|
||||
#[serde(rename = "item.completed")]
|
||||
ItemCompleted(ItemCompletedEvent),
|
||||
/// Represents an unrecoverable error emitted directly by the event stream.
|
||||
#[serde(rename = "error")]
|
||||
Error(ThreadErrorEvent),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadStartedEvent {
|
||||
/// The identified of the new thread. Can be used to resume the thread later.
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
|
||||
|
||||
pub struct TurnStartedEvent {}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TurnCompletedEvent {
|
||||
pub usage: Usage,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TurnFailedEvent {
|
||||
pub error: ThreadErrorEvent,
|
||||
}
|
||||
|
||||
/// Describes the usage of tokens during a turn.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
|
||||
pub struct Usage {
|
||||
/// The number of input tokens used during the turn.
|
||||
pub input_tokens: i64,
|
||||
/// The number of cached input tokens used during the turn.
|
||||
pub cached_input_tokens: i64,
|
||||
/// The number of output tokens used during the turn.
|
||||
pub output_tokens: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemStartedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemCompletedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemUpdatedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
/// Fatal error emitted by the stream.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadErrorEvent {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Canonical representation of a thread item and its domain-specific payload.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadItem {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub details: ThreadItemDetails,
|
||||
}
|
||||
|
||||
/// Typed payloads for each supported thread item type.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ThreadItemDetails {
|
||||
/// Response from the agent.
|
||||
/// Either a natural-language response or a JSON string when structured output is requested.
|
||||
AgentMessage(AgentMessageItem),
|
||||
/// Agent's reasoning summary.
|
||||
Reasoning(ReasoningItem),
|
||||
/// Tracks a command executed by the agent. The item starts when the command is
|
||||
/// spawned, and completes when the process exits with an exit code.
|
||||
CommandExecution(CommandExecutionItem),
|
||||
/// Represents a set of file changes by the agent. The item is emitted only as a
|
||||
/// completed event once the patch succeeds or fails.
|
||||
FileChange(FileChangeItem),
|
||||
/// Represents a call to an MCP tool. The item starts when the invocation is
|
||||
/// dispatched and completes when the MCP server reports success or failure.
|
||||
McpToolCall(McpToolCallItem),
|
||||
/// Represents a call to a collab tool. The item starts when the collab tool is
|
||||
/// invoked and completes when the collab tool reports success or failure.
|
||||
CollabToolCall(CollabToolCallItem),
|
||||
/// Captures a web search request. It starts when the search is kicked off
|
||||
/// and completes when results are returned to the agent.
|
||||
WebSearch(WebSearchItem),
|
||||
/// Tracks the agent's running to-do list. It starts when the plan is first
|
||||
/// issued, updates as steps change state, and completes when the turn ends.
|
||||
TodoList(TodoListItem),
|
||||
/// Describes a non-fatal error surfaced as an item.
|
||||
Error(ErrorItem),
|
||||
}
|
||||
|
||||
/// Response from the agent.
|
||||
/// Either a natural-language response or a JSON string when structured output is requested.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct AgentMessageItem {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Agent's reasoning summary.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ReasoningItem {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The status of a command execution.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandExecutionStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
Declined,
|
||||
}
|
||||
|
||||
/// A command executed by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct CommandExecutionItem {
|
||||
pub command: String,
|
||||
pub aggregated_output: String,
|
||||
pub exit_code: Option<i32>,
|
||||
pub status: CommandExecutionStatus,
|
||||
}
|
||||
|
||||
/// A set of file changes by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct FileUpdateChange {
|
||||
pub path: String,
|
||||
pub kind: PatchChangeKind,
|
||||
}
|
||||
|
||||
/// The status of a file change.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PatchApplyStatus {
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A set of file changes by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct FileChangeItem {
|
||||
pub changes: Vec<FileUpdateChange>,
|
||||
pub status: PatchApplyStatus,
|
||||
}
|
||||
|
||||
/// Indicates the type of the file change.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PatchChangeKind {
|
||||
Add,
|
||||
Delete,
|
||||
Update,
|
||||
}
|
||||
|
||||
/// The status of an MCP tool call.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpToolCallStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// The status of a collab tool call.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabToolCallStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Supported collab tools.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabTool {
|
||||
SpawnAgent,
|
||||
SendInput,
|
||||
Wait,
|
||||
CloseAgent,
|
||||
}
|
||||
|
||||
/// The status of a collab agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabAgentStatus {
|
||||
PendingInit,
|
||||
Running,
|
||||
Interrupted,
|
||||
Completed,
|
||||
Errored,
|
||||
Shutdown,
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// Last known state of a collab agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
pub struct CollabAgentState {
|
||||
pub status: CollabAgentStatus,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
/// A call to a collab tool.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct CollabToolCallItem {
|
||||
pub tool: CollabTool,
|
||||
pub sender_thread_id: String,
|
||||
pub receiver_thread_ids: Vec<String>,
|
||||
pub prompt: Option<String>,
|
||||
pub agents_states: HashMap<String, CollabAgentState>,
|
||||
pub status: CollabToolCallStatus,
|
||||
}
|
||||
|
||||
/// Result payload produced by an MCP tool invocation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItemResult {
|
||||
// NOTE: `rmcp::model::Content` (and its `RawContent` variants) would be a
|
||||
// more precise Rust representation of MCP content blocks. We intentionally
|
||||
// use `serde_json::Value` here because this crate exports JSON schema + TS
|
||||
// types (`schemars`/`ts-rs`), and the rmcp model types aren't set up to be
|
||||
// schema/TS friendly (and would introduce heavier coupling to rmcp's Rust
|
||||
// representations). Using `JsonValue` keeps the payload wire-shaped and
|
||||
// easy to export.
|
||||
pub content: Vec<JsonValue>,
|
||||
pub structured_content: Option<JsonValue>,
|
||||
}
|
||||
|
||||
/// Error details reported by a failed MCP tool invocation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItemError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// A call to an MCP tool.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItem {
|
||||
pub server: String,
|
||||
pub tool: String,
|
||||
#[serde(default)]
|
||||
pub arguments: JsonValue,
|
||||
pub result: Option<McpToolCallItemResult>,
|
||||
pub error: Option<McpToolCallItemError>,
|
||||
pub status: McpToolCallStatus,
|
||||
}
|
||||
|
||||
/// A web search request.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct WebSearchItem {
|
||||
pub id: String,
|
||||
pub query: String,
|
||||
pub action: WebSearchAction,
|
||||
}
|
||||
|
||||
/// An error notification.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ErrorItem {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// An item in agent's to-do list.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TodoItem {
|
||||
pub text: String,
|
||||
pub completed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TodoListItem {
|
||||
pub items: Vec<TodoItem>,
|
||||
}
|
||||
1799
vendor/codex/codex-rs/exec/src/lib.rs
vendored
Normal file
1799
vendor/codex/codex-rs/exec/src/lib.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
444
vendor/codex/codex-rs/exec/src/lib_tests.rs
vendored
Normal file
444
vendor/codex/codex-rs/exec/src/lib_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,444 @@
|
|||
use super::*;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use opentelemetry::trace::TraceContextExt;
|
||||
use opentelemetry::trace::TraceId;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||
|
||||
fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync {
|
||||
let provider = SdkTracerProvider::builder().build();
|
||||
let tracer = provider.tracer("codex-exec-tests");
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_defaults_analytics_to_enabled() {
|
||||
assert_eq!(DEFAULT_ANALYTICS_ENABLED, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_root_span_can_be_parented_from_trace_context() {
|
||||
let subscriber = test_tracing_subscriber();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let parent = codex_protocol::protocol::W3cTraceContext {
|
||||
traceparent: Some("00-00000000000000000000000000000077-0000000000000088-01".into()),
|
||||
tracestate: Some("vendor=value".into()),
|
||||
};
|
||||
let exec_span = exec_root_span();
|
||||
assert!(set_parent_from_w3c_trace_context(&exec_span, &parent));
|
||||
|
||||
let trace_id = exec_span.context().span().span_context().trace_id();
|
||||
assert_eq!(
|
||||
trace_id,
|
||||
TraceId::from_hex("00000000000000000000000000000077").expect("trace id")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_uncommitted_review_request() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: true,
|
||||
base: None,
|
||||
commit: None,
|
||||
commit_title: None,
|
||||
prompt: None,
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds uncommitted review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::UncommittedChanges,
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_commit_review_request_with_title() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: false,
|
||||
base: None,
|
||||
commit: Some("123456789".to_string()),
|
||||
commit_title: Some("Add review command".to_string()),
|
||||
prompt: None,
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds commit review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::Commit {
|
||||
sha: "123456789".to_string(),
|
||||
title: Some("Add review command".to_string()),
|
||||
},
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_custom_review_request_trims_prompt() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: false,
|
||||
base: None,
|
||||
commit: None,
|
||||
commit_title: None,
|
||||
prompt: Some(" custom review instructions ".to_string()),
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds custom review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::Custom {
|
||||
instructions: "custom review instructions".to_string(),
|
||||
},
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_strips_utf8_bom() {
|
||||
let input = [0xEF, 0xBB, 0xBF, b'h', b'i', b'\n'];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-8 with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_decodes_utf16le_bom() {
|
||||
// UTF-16LE BOM + "hi\n"
|
||||
let input = [0xFF, 0xFE, b'h', 0x00, b'i', 0x00, b'\n', 0x00];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-16le with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_decodes_utf16be_bom() {
|
||||
// UTF-16BE BOM + "hi\n"
|
||||
let input = [0xFE, 0xFF, 0x00, b'h', 0x00, b'i', 0x00, b'\n'];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-16be with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_utf32le_bom() {
|
||||
// UTF-32LE BOM + "hi\n"
|
||||
let input = [
|
||||
0xFF, 0xFE, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00, b'\n', 0x00, 0x00,
|
||||
0x00,
|
||||
];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("utf-32le should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
PromptDecodeError::UnsupportedBom {
|
||||
encoding: "UTF-32LE"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_utf32be_bom() {
|
||||
// UTF-32BE BOM + "hi\n"
|
||||
let input = [
|
||||
0x00, 0x00, 0xFE, 0xFF, 0x00, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00,
|
||||
b'\n',
|
||||
];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("utf-32be should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
PromptDecodeError::UnsupportedBom {
|
||||
encoding: "UTF-32BE"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_invalid_utf8() {
|
||||
// Invalid UTF-8 sequence: 0xC3 0x28
|
||||
let input = [0xC3, 0x28];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("invalid utf-8 should fail");
|
||||
|
||||
assert_eq!(err, PromptDecodeError::InvalidUtf8 { valid_up_to: 0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_with_stdin_context_wraps_stdin_block() {
|
||||
let combined = prompt_with_stdin_context("Summarize this concisely", "my output");
|
||||
|
||||
assert_eq!(
|
||||
combined,
|
||||
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_with_stdin_context_preserves_trailing_newline() {
|
||||
let combined = prompt_with_stdin_context("Summarize this concisely", "my output\n");
|
||||
|
||||
assert_eq!(
|
||||
combined,
|
||||
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lagged_event_warning_message_is_explicit() {
|
||||
assert_eq!(
|
||||
lagged_event_warning_message(/*skipped*/ 7),
|
||||
"in-process app-server event stream lagged; dropped 7 events".to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_lookup_model_providers_filters_only_last_lookup() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build default config");
|
||||
config.model_provider_id = "test-provider".to_string();
|
||||
|
||||
let last_args = crate::cli::ResumeArgs {
|
||||
session_id: None,
|
||||
last: true,
|
||||
all: false,
|
||||
images: vec![],
|
||||
prompt: None,
|
||||
};
|
||||
let named_args = crate::cli::ResumeArgs {
|
||||
session_id: Some("named-session".to_string()),
|
||||
last: false,
|
||||
all: false,
|
||||
images: vec![],
|
||||
prompt: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
resume_lookup_model_providers(&config, &last_args),
|
||||
Some(vec!["test-provider".to_string()])
|
||||
);
|
||||
assert_eq!(resume_lookup_model_providers(&config, &named_args), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_items_for_thread_returns_matching_turn_items() {
|
||||
let thread = AppServerThread {
|
||||
id: "thread-1".to_string(),
|
||||
forked_from_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
status: codex_app_server_protocol::ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
cli_version: "0.0.0-test".to_string(),
|
||||
source: codex_app_server_protocol::SessionSource::Exec,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: None,
|
||||
turns: vec![
|
||||
codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: vec![AppServerThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
}],
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
codex_app_server_protocol::Turn {
|
||||
id: "turn-2".to_string(),
|
||||
items: vec![AppServerThreadItem::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "ship it".to_string(),
|
||||
}],
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
turn_items_for_thread(&thread, "turn-1"),
|
||||
Some(vec![AppServerThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
}])
|
||||
);
|
||||
assert_eq!(turn_items_for_thread(&thread, "missing-turn"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_backfill_turn_completed_items_skips_ephemeral_threads() {
|
||||
let notification =
|
||||
ServerNotification::TurnCompleted(codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: Vec::new(),
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
});
|
||||
|
||||
assert!(!should_backfill_turn_completed_items(
|
||||
/*thread_ephemeral*/ true,
|
||||
¬ification
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceled_mcp_server_elicitation_response_uses_cancel_action() {
|
||||
let value = canceled_mcp_server_elicitation_response()
|
||||
.expect("mcp elicitation cancel response should serialize");
|
||||
let response: McpServerElicitationRequestResponse =
|
||||
serde_json::from_value(value).expect("cancel response should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
McpServerElicitationRequestResponse {
|
||||
action: McpServerElicitationAction::Cancel,
|
||||
content: None,
|
||||
meta: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_params_include_review_policy_when_review_policy_is_manual_only() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with manual-only review policy");
|
||||
|
||||
let params = thread_start_params_from_config(&config);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::User)
|
||||
);
|
||||
assert_eq!(params.sandbox, None);
|
||||
assert_eq!(
|
||||
params.permission_profile,
|
||||
Some(config.permissions.permission_profile().into())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_params_include_review_policy_when_auto_review_is_enabled() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with guardian review policy");
|
||||
|
||||
let params = thread_start_params_from_config(&config);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_configured_from_thread_response_uses_review_policy_from_response() {
|
||||
let response = ThreadStartResponse {
|
||||
thread: codex_app_server_protocol::Thread {
|
||||
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
|
||||
forked_from_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
status: codex_app_server_protocol::ThreadStatus::Idle,
|
||||
path: Some(PathBuf::from("/tmp/rollout.jsonl")),
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: codex_app_server_protocol::SessionSource::Cli,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: Some("thread".to_string()),
|
||||
turns: vec![],
|
||||
},
|
||||
model: "gpt-5.4".to_string(),
|
||||
model_provider: "openai".to_string(),
|
||||
service_tier: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
instruction_sources: Vec::new(),
|
||||
approval_policy: codex_app_server_protocol::AskForApproval::OnRequest,
|
||||
approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview,
|
||||
sandbox: codex_app_server_protocol::SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: vec![],
|
||||
read_only_access: codex_app_server_protocol::ReadOnlyAccess::FullAccess,
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: false,
|
||||
exclude_slash_tmp: false,
|
||||
},
|
||||
permission_profile: Some(
|
||||
codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy(
|
||||
&codex_protocol::protocol::SandboxPolicy::new_workspace_write_policy(),
|
||||
&test_path_buf("/tmp"),
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
reasoning_effort: None,
|
||||
};
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(event.approvals_reviewer, ApprovalsReviewer::AutoReview);
|
||||
}
|
||||
45
vendor/codex/codex-rs/exec/src/main.rs
vendored
Normal file
45
vendor/codex/codex-rs/exec/src/main.rs
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
//! Entry-point for the `codex-exec` binary.
|
||||
//!
|
||||
//! When this CLI is invoked normally, it parses the standard `codex-exec` CLI
|
||||
//! options and launches the non-interactive Codex agent. However, if it is
|
||||
//! invoked with arg0 as `codex-linux-sandbox`, we instead treat the invocation
|
||||
//! as a request to run the logic for the standalone `codex-linux-sandbox`
|
||||
//! executable (i.e., parse any -s args and then run a *sandboxed* command under
|
||||
//! Landlock + seccomp.
|
||||
//!
|
||||
//! This allows us to ship a completely separate set of functionality as part
|
||||
//! of the `codex-exec` binary.
|
||||
use clap::Parser;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_exec::Cli;
|
||||
use codex_exec::run_main;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
struct TopCli {
|
||||
#[clap(flatten)]
|
||||
config_overrides: CliConfigOverrides,
|
||||
|
||||
#[clap(flatten)]
|
||||
inner: Cli,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
|
||||
let top_cli = TopCli::parse();
|
||||
// Merge root-level overrides into inner CLI struct so downstream logic remains unchanged.
|
||||
let mut inner = top_cli.inner;
|
||||
inner
|
||||
.config_overrides
|
||||
.raw_overrides
|
||||
.splice(0..0, top_cli.config_overrides.raw_overrides);
|
||||
|
||||
run_main(inner, arg0_paths).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
37
vendor/codex/codex-rs/exec/src/main_tests.rs
vendored
Normal file
37
vendor/codex/codex-rs/exec/src/main_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn top_cli_parses_resume_prompt_after_config_flag() {
|
||||
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
|
||||
let cli = TopCli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"--last",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--config",
|
||||
"reasoning_level=xhigh",
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--skip-git-repo-check",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
let Some(codex_exec::Command::Resume(args)) = cli.inner.command else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
let effective_prompt = args.prompt.clone().or_else(|| {
|
||||
if args.last {
|
||||
args.session_id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
|
||||
assert_eq!(cli.config_overrides.raw_overrides.len(), 1);
|
||||
assert_eq!(
|
||||
cli.config_overrides.raw_overrides[0],
|
||||
"reasoning_level=xhigh"
|
||||
);
|
||||
}
|
||||
5
vendor/codex/codex-rs/exec/tests/all.rs
vendored
Normal file
5
vendor/codex/codex-rs/exec/tests/all.rs
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// Single integration test binary that aggregates all test modules.
|
||||
// The submodules live in `tests/suite/`.
|
||||
mod suite;
|
||||
|
||||
mod event_processor_with_json_output;
|
||||
1611
vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs
vendored
Normal file
1611
vendor/codex/codex-rs/exec/tests/event_processor_with_json_output.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
4
vendor/codex/codex-rs/exec/tests/fixtures/apply_patch_freeform_final.txt
vendored
Normal file
4
vendor/codex/codex-rs/exec/tests/fixtures/apply_patch_freeform_final.txt
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
class BaseClass:
|
||||
def method():
|
||||
|
||||
return True
|
||||
10
vendor/codex/codex-rs/exec/tests/fixtures/cli_responses_fixture.sse
vendored
Normal file
10
vendor/codex/codex-rs/exec/tests/fixtures/cli_responses_fixture.sse
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
event: response.created
|
||||
data: {"type":"response.created","response":{"id":"resp1"}}
|
||||
|
||||
event: response.output_item.done
|
||||
data: {"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"fixture hello"}]}}
|
||||
|
||||
event: response.completed
|
||||
data: {"type":"response.completed","response":{"id":"resp1","output":[]}}
|
||||
|
||||
|
||||
72
vendor/codex/codex-rs/exec/tests/suite/add_dir.rs
vendored
Normal file
72
vendor/codex/codex-rs/exec/tests/suite/add_dir.rs
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
/// Verify that the --add-dir flag is accepted and the command runs successfully.
|
||||
/// This test confirms the CLI argument is properly wired up.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
async fn accepts_add_dir_flag() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Task completed"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// Create temporary directories to use with --add-dir
|
||||
let temp_dir1 = tempfile::tempdir()?;
|
||||
let temp_dir2 = tempfile::tempdir()?;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir1.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir2.path())
|
||||
.arg("test with additional directories")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify that multiple --add-dir flags can be specified.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn accepts_multiple_add_dir_flags() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Multiple directories accepted"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
let temp_dir1 = tempfile::tempdir()?;
|
||||
let temp_dir2 = tempfile::tempdir()?;
|
||||
let temp_dir3 = tempfile::tempdir()?;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir1.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir2.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir3.path())
|
||||
.arg("test with three directories")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
150
vendor/codex/codex-rs/exec/tests/suite/apply_patch.rs
vendored
Normal file
150
vendor/codex/codex-rs/exec/tests/suite/apply_patch.rs
vendored
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
#![allow(clippy::expect_used, clippy::unwrap_used, unused_imports)]
|
||||
|
||||
use anyhow::Context;
|
||||
use assert_cmd::prelude::*;
|
||||
use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;
|
||||
use core_test_support::responses::ev_apply_patch_custom_tool_call;
|
||||
use core_test_support::responses::ev_apply_patch_function_call;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// While we may add an `apply-patch` subcommand to the `codex` CLI multitool
|
||||
/// at some point, we must ensure that the smaller `codex-exec` CLI can still
|
||||
/// emulate the `apply_patch` CLI.
|
||||
#[test]
|
||||
fn test_standalone_exec_cli_can_use_apply_patch() -> anyhow::Result<()> {
|
||||
let tmp = tempdir()?;
|
||||
let relative_path = "source.txt";
|
||||
let absolute_path = tmp.path().join(relative_path);
|
||||
fs::write(&absolute_path, "original content\n")?;
|
||||
|
||||
Command::new(codex_utils_cargo_bin::cargo_bin("codex-exec")?)
|
||||
.arg(CODEX_CORE_APPLY_PATCH_ARG1)
|
||||
.arg(
|
||||
r#"*** Begin Patch
|
||||
*** Update File: source.txt
|
||||
@@
|
||||
-original content
|
||||
+modified by apply_patch
|
||||
*** End Patch"#,
|
||||
)
|
||||
.current_dir(tmp.path())
|
||||
.assert()
|
||||
.success()
|
||||
.stdout("Success. Updated the following files:\nM source.txt\n")
|
||||
.stderr(predicates::str::is_empty());
|
||||
assert_eq!(
|
||||
fs::read_to_string(absolute_path)?,
|
||||
"modified by apply_patch\n"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_apply_patch_tool() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let tmp_path = test.cwd_path().to_path_buf();
|
||||
let add_patch = r#"*** Begin Patch
|
||||
*** Add File: test.md
|
||||
+Hello world
|
||||
*** End Patch"#;
|
||||
let update_patch = r#"*** Begin Patch
|
||||
*** Update File: test.md
|
||||
@@
|
||||
-Hello world
|
||||
+Final text
|
||||
*** End Patch"#;
|
||||
let response_streams = vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_0", add_patch),
|
||||
ev_completed("request_0"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_apply_patch_function_call("request_1", update_patch),
|
||||
ev_completed("request_1"),
|
||||
]),
|
||||
sse(vec![ev_completed("request_2")]),
|
||||
];
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, response_streams).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-s")
|
||||
.arg("danger-full-access")
|
||||
.arg("foo")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let final_path = tmp_path.join("test.md");
|
||||
let contents = std::fs::read_to_string(&final_path)
|
||||
.unwrap_or_else(|e| panic!("failed reading {}: {e}", final_path.display()));
|
||||
assert_eq!(contents, "Final text\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_apply_patch_freeform_tool() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let freeform_add_patch = r#"*** Begin Patch
|
||||
*** Add File: app.py
|
||||
+class BaseClass:
|
||||
+ def method():
|
||||
+ return False
|
||||
*** End Patch"#;
|
||||
let freeform_update_patch = r#"*** Begin Patch
|
||||
*** Update File: app.py
|
||||
@@ def method():
|
||||
- return False
|
||||
+
|
||||
+ return True
|
||||
*** End Patch"#;
|
||||
let response_streams = vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_0", freeform_add_patch),
|
||||
ev_completed("request_0"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_1", freeform_update_patch),
|
||||
ev_completed("request_1"),
|
||||
]),
|
||||
sse(vec![ev_completed("request_2")]),
|
||||
];
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, response_streams).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-s")
|
||||
.arg("danger-full-access")
|
||||
.arg("foo")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Verify final file contents
|
||||
let final_path = test.cwd_path().join("app.py");
|
||||
let contents = std::fs::read_to_string(&final_path)
|
||||
.unwrap_or_else(|e| panic!("failed reading {}: {e}", final_path.display()));
|
||||
assert_eq!(
|
||||
contents,
|
||||
include_str!("../fixtures/apply_patch_freeform_final.txt")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
31
vendor/codex/codex-rs/exec/tests/suite/auth_env.rs
vendored
Normal file
31
vendor/codex/codex-rs/exec/tests/suite/auth_env.rs
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::mount_sse_once_match;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use wiremock::matchers::header;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_uses_codex_api_key_env_var() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = start_mock_server().await;
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
header("Authorization", "Bearer dummy"),
|
||||
sse(vec![ev_completed("request_0")]),
|
||||
)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg("echo testing codex api key")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
53
vendor/codex/codex-rs/exec/tests/suite/ephemeral.rs
vendored
Normal file
53
vendor/codex/codex-rs/exec/tests/suite/ephemeral.rs
vendored
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use codex_utils_cargo_bin::find_resource;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
fn session_rollout_count(home_path: &std::path::Path) -> usize {
|
||||
let sessions_dir = home_path.join("sessions");
|
||||
if !sessions_dir.exists() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
WalkDir::new(sessions_dir)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_file())
|
||||
.filter(|entry| entry.file_name().to_string_lossy().ends_with(".jsonl"))
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persists_rollout_file_by_default() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = find_resource!("tests/fixtures/cli_responses_fixture.sse")?;
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("default persistence behavior")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
assert_eq!(session_rollout_count(test.home_path()), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_persist_rollout_file_in_ephemeral_mode() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = find_resource!("tests/fixtures/cli_responses_fixture.sse")?;
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--ephemeral")
|
||||
.arg("ephemeral behavior")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
assert_eq!(session_rollout_count(test.home_path()), 0);
|
||||
Ok(())
|
||||
}
|
||||
38
vendor/codex/codex-rs/exec/tests/suite/mcp_required_exit.rs
vendored
Normal file
38
vendor/codex/codex-rs/exec/tests/suite/mcp_required_exit.rs
vendored
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use predicates::str::contains;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exits_non_zero_when_required_mcp_server_fails_to_initialize() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let config_toml = r#"
|
||||
[mcp_servers.required_broken]
|
||||
command = "codex-definitely-not-a-real-binary"
|
||||
required = true
|
||||
"#;
|
||||
std::fs::write(test.home_path().join("config.toml"), config_toml)?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp_1"),
|
||||
responses::ev_assistant_message("msg_1", "hello"),
|
||||
responses::ev_completed("resp_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--experimental-json")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.code(1)
|
||||
.stderr(contains(
|
||||
"required MCP servers failed to initialize: required_broken",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
12
vendor/codex/codex-rs/exec/tests/suite/mod.rs
vendored
Normal file
12
vendor/codex/codex-rs/exec/tests/suite/mod.rs
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// Aggregates all former standalone integration tests as modules.
|
||||
mod add_dir;
|
||||
mod apply_patch;
|
||||
mod auth_env;
|
||||
mod ephemeral;
|
||||
mod mcp_required_exit;
|
||||
mod originator;
|
||||
mod output_schema;
|
||||
mod prompt_stdin;
|
||||
mod resume;
|
||||
mod sandbox;
|
||||
mod server_error_exit;
|
||||
54
vendor/codex/codex-rs/exec/tests/suite/originator.rs
vendored
Normal file
54
vendor/codex/codex-rs/exec/tests/suite/originator.rs
vendored
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use wiremock::matchers::header;
|
||||
|
||||
/// Verify that when the server reports an error, `codex-exec` exits with a
|
||||
/// non-zero status code so automation can detect failures.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn send_codex_exec_originator() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Hello, world!"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once_match(&server, header("Originator", "codex_exec"), body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove(CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn supports_originator_override() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Hello, world!"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once_match(&server, header("Originator", "codex_exec_override"), body)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env("CODEX_INTERNAL_ORIGINATOR_OVERRIDE", "codex_exec_override")
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
62
vendor/codex/codex-rs/exec/tests/suite/output_schema.rs
vendored
Normal file
62
vendor/codex/codex-rs/exec/tests/suite/output_schema.rs
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use serde_json::Value;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_includes_output_schema_in_request() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let schema_contents = serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"answer": { "type": "string" }
|
||||
},
|
||||
"required": ["answer"],
|
||||
"additionalProperties": false
|
||||
});
|
||||
let schema_path = test.cwd_path().join("schema.json");
|
||||
std::fs::write(&schema_path, serde_json::to_vec_pretty(&schema_contents)?)?;
|
||||
let expected_schema: Value = schema_contents;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
// keep using -C in the test to exercise the flag as well
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("--output-schema")
|
||||
.arg(&schema_path)
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("tell me a joke")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
let payload: Value = request.body_json();
|
||||
let text = payload.get("text").expect("request missing text field");
|
||||
let format = text
|
||||
.get("format")
|
||||
.expect("request missing text.format field");
|
||||
assert_eq!(
|
||||
format,
|
||||
&serde_json::json!({
|
||||
"name": "codex_output_schema",
|
||||
"type": "json_schema",
|
||||
"strict": true,
|
||||
"schema": expected_schema,
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
171
vendor/codex/codex-rs/exec/tests/suite/prompt_stdin.rs
vendored
Normal file
171
vendor/codex/codex-rs/exec/tests/suite/prompt_stdin.rs
vendored
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use predicates::str::contains;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_appends_piped_stdin_to_prompt_argument() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "my output" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("Summarize this concisely")
|
||||
.write_stdin("my output\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["Summarize this concisely\n\n<stdin>\nmy output\n</stdin>".to_string()]
|
||||
}),
|
||||
"request should include a user message with the prompt plus piped stdin context"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_ignores_empty_piped_stdin_when_prompt_argument_is_present() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("Summarize this concisely")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| texts
|
||||
== ["Summarize this concisely".to_string()]),
|
||||
"request should preserve the prompt when stdin is empty"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_dash_prompt_reads_stdin_as_the_prompt() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 -
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("-")
|
||||
.write_stdin("prompt from stdin\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["prompt from stdin\n".to_string()]
|
||||
}),
|
||||
"dash prompt should preserve the existing forced-stdin behavior"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_without_prompt_argument_reads_piped_stdin_as_the_prompt() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.write_stdin("prompt from stdin\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["prompt from stdin\n".to_string()]
|
||||
}),
|
||||
"missing prompt argument should preserve the existing piped-stdin prompt behavior"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_without_prompt_argument_rejects_empty_piped_stdin() {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd>
|
||||
test.cmd()
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.code(1)
|
||||
.stderr(contains("No prompt provided via stdin."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_dash_prompt_rejects_empty_piped_stdin() {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd> -
|
||||
test.cmd()
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.code(1)
|
||||
.stderr(contains("No prompt provided via stdin."));
|
||||
}
|
||||
544
vendor/codex/codex-rs/exec/tests/suite/resume.rs
vendored
Normal file
544
vendor/codex/codex-rs/exec/tests/suite/resume.rs
vendored
Normal file
|
|
@ -0,0 +1,544 @@
|
|||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
use anyhow::Context;
|
||||
use codex_utils_cargo_bin::find_resource;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use std::string::ToString;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
/// Utility: scan the sessions dir for a rollout file that contains `marker`
|
||||
/// in any response_item.message.content entry. Returns the absolute path.
|
||||
fn find_session_file_containing_marker(
|
||||
sessions_dir: &std::path::Path,
|
||||
marker: &str,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
for entry in WalkDir::new(sessions_dir) {
|
||||
let entry = match entry {
|
||||
Ok(e) => e,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if !entry.file_name().to_string_lossy().ends_with(".jsonl") {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let Ok(content) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
// Skip the first meta line and scan remaining JSONL entries.
|
||||
let mut lines = content.lines();
|
||||
if lines.next().is_none() {
|
||||
continue;
|
||||
}
|
||||
for line in lines {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(item): Result<Value, _> = serde_json::from_str(line) else {
|
||||
continue;
|
||||
};
|
||||
if item.get("type").and_then(|t| t.as_str()) == Some("response_item")
|
||||
&& let Some(payload) = item.get("payload")
|
||||
&& payload.get("type").and_then(|t| t.as_str()) == Some("message")
|
||||
&& payload
|
||||
.get("content")
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default()
|
||||
.contains(marker)
|
||||
{
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Extract the conversation UUID from the first SessionMeta line in the rollout file.
|
||||
fn extract_conversation_id(path: &std::path::Path) -> String {
|
||||
let content = std::fs::read_to_string(path).unwrap();
|
||||
let mut lines = content.lines();
|
||||
let meta_line = lines.next().expect("missing meta line");
|
||||
let meta: Value = serde_json::from_str(meta_line).expect("invalid meta json");
|
||||
meta.get("payload")
|
||||
.and_then(|p| p.get("id"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn last_user_image_count(path: &std::path::Path) -> usize {
|
||||
let content = std::fs::read_to_string(path).unwrap_or_default();
|
||||
let mut last_count = 0;
|
||||
for line in content.lines() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(item): Result<Value, _> = serde_json::from_str(line) else {
|
||||
continue;
|
||||
};
|
||||
if item.get("type").and_then(|t| t.as_str()) != Some("response_item") {
|
||||
continue;
|
||||
}
|
||||
let Some(payload) = item.get("payload") else {
|
||||
continue;
|
||||
};
|
||||
if payload.get("type").and_then(|t| t.as_str()) != Some("message") {
|
||||
continue;
|
||||
}
|
||||
if payload.get("role").and_then(|r| r.as_str()) != Some("user") {
|
||||
continue;
|
||||
}
|
||||
let Some(content_items) = payload.get("content").and_then(|v| v.as_array()) else {
|
||||
continue;
|
||||
};
|
||||
last_count = content_items
|
||||
.iter()
|
||||
.filter(|entry| entry.get("type").and_then(|t| t.as_str()) == Some("input_image"))
|
||||
.count();
|
||||
}
|
||||
last_count
|
||||
}
|
||||
|
||||
fn exec_fixture() -> anyhow::Result<std::path::PathBuf> {
|
||||
Ok(find_resource!("tests/fixtures/cli_responses_fixture.sse")?)
|
||||
}
|
||||
|
||||
fn exec_repo_root() -> anyhow::Result<std::path::PathBuf> {
|
||||
Ok(codex_utils_cargo_bin::repo_root()?)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
let repo_root = exec_repo_root()?;
|
||||
|
||||
// 1) First run: create a session with a unique marker in the content.
|
||||
let marker = format!("resume-last-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Find the created session file containing the marker.
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
let path = find_session_file_containing_marker(&sessions_dir, &marker)
|
||||
.expect("no session file found after first run");
|
||||
|
||||
// 2) Second run: resume the most recent file with a new marker.
|
||||
let marker2 = format!("resume-last-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt2)
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Ensure the same file was updated and contains both markers.
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no resumed session file containing marker2");
|
||||
assert_eq!(
|
||||
resumed_path, path,
|
||||
"resume --last should append to existing file"
|
||||
);
|
||||
let content = std::fs::read_to_string(&resumed_path)?;
|
||||
assert!(content.contains(&marker));
|
||||
assert!(content.contains(&marker2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_last_accepts_prompt_after_flag_in_json_mode() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
let repo_root = exec_repo_root()?;
|
||||
|
||||
// 1) First run: create a session with a unique marker in the content.
|
||||
let marker = format!("resume-last-json-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Find the created session file containing the marker.
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
let path = find_session_file_containing_marker(&sessions_dir, &marker)
|
||||
.expect("no session file found after first run");
|
||||
|
||||
// 2) Second run: resume the most recent file and pass the prompt after --last.
|
||||
let marker2 = format!("resume-last-json-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg("--json")
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.arg(&prompt2)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no resumed session file containing marker2");
|
||||
assert_eq!(
|
||||
resumed_path, path,
|
||||
"resume --last should append to existing file"
|
||||
);
|
||||
let content = std::fs::read_to_string(&resumed_path)?;
|
||||
assert!(content.contains(&marker));
|
||||
assert!(content.contains(&marker2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_last_respects_cwd_filter_and_all_flag() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
|
||||
let dir_a = TempDir::new()?;
|
||||
let dir_b = TempDir::new()?;
|
||||
|
||||
let marker_a = format!("resume-cwd-a-{}", Uuid::new_v4());
|
||||
let prompt_a = format!("echo {marker_a}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(dir_a.path())
|
||||
.arg(&prompt_a)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let marker_b = format!("resume-cwd-b-{}", Uuid::new_v4());
|
||||
let prompt_b = format!("echo {marker_b}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(dir_b.path())
|
||||
.arg(&prompt_b)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
find_session_file_containing_marker(&sessions_dir, &marker_a)
|
||||
.expect("no session file found for marker_a");
|
||||
let path_b = find_session_file_containing_marker(&sessions_dir, &marker_b)
|
||||
.expect("no session file found for marker_b");
|
||||
|
||||
// `updated_at` is second-granularity, so ensure the touch lands in a later second
|
||||
// than the initial session creation on fast CI (especially Windows).
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
|
||||
// Make thread B deterministically newest according to rollout metadata.
|
||||
let session_id_b = extract_conversation_id(&path_b);
|
||||
let marker_b_touch = format!("resume-cwd-b-touch-{}", Uuid::new_v4());
|
||||
let prompt_b_touch = format!("echo {marker_b_touch}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(dir_b.path())
|
||||
.arg("resume")
|
||||
.arg(&session_id_b)
|
||||
.arg(&prompt_b_touch)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// `resume --last` sorts by `updated_at`, which is second-granularity. Sleep so
|
||||
// the upcoming `resume --last --all` write lands in a later second and becomes
|
||||
// deterministically newest (instead of tying and falling back to UUID order).
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
|
||||
let marker_b2 = format!("resume-cwd-b-2-{}", Uuid::new_v4());
|
||||
let prompt_b2 = format!("echo {marker_b2}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(dir_a.path())
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.arg("--all")
|
||||
.arg(&prompt_b2)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let resumed_path_all = find_session_file_containing_marker(&sessions_dir, &marker_b2)
|
||||
.expect("no resumed session file containing marker_b2");
|
||||
assert_eq!(
|
||||
resumed_path_all, path_b,
|
||||
"resume --last --all should pick newest session"
|
||||
);
|
||||
|
||||
let marker_a2 = format!("resume-cwd-a-2-{}", Uuid::new_v4());
|
||||
let prompt_a2 = format!("echo {marker_a2}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(dir_a.path())
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.arg(&prompt_a2)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let resumed_path_cwd = find_session_file_containing_marker(&sessions_dir, &marker_a2)
|
||||
.expect("no resumed session file containing marker_a2");
|
||||
// The `--all` resume above appends a new turn to `path_b` while running from `dir_a`, so the
|
||||
// session's latest cwd now matches `dir_a`. A subsequent `resume --last` should therefore pick
|
||||
// the newest matching session (`path_b`).
|
||||
assert_eq!(
|
||||
resumed_path_cwd, path_b,
|
||||
"resume --last should prefer sessions whose latest turn context matches the current cwd"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_accepts_global_flags_after_subcommand() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
|
||||
// Seed a session.
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("echo seed-resume-session")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Resume while passing global flags after the subcommand to ensure clap accepts them.
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.arg("--json")
|
||||
.arg("--model")
|
||||
.arg("gpt-5.2-codex")
|
||||
.arg("--config")
|
||||
.arg("reasoning_level=xhigh")
|
||||
.arg("--dangerously-bypass-approvals-and-sandbox")
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("echo resume-with-global-flags-after-subcommand")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
let repo_root = exec_repo_root()?;
|
||||
|
||||
// 1) First run: create a session
|
||||
let marker = format!("resume-by-id-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
let path = find_session_file_containing_marker(&sessions_dir, &marker)
|
||||
.expect("no session file found after first run");
|
||||
let session_id = extract_conversation_id(&path);
|
||||
assert!(
|
||||
!session_id.is_empty(),
|
||||
"missing conversation id in meta line"
|
||||
);
|
||||
|
||||
// 2) Resume by id
|
||||
let marker2 = format!("resume-by-id-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt2)
|
||||
.arg("resume")
|
||||
.arg(&session_id)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no resumed session file containing marker2");
|
||||
assert_eq!(
|
||||
resumed_path, path,
|
||||
"resume by id should append to existing file"
|
||||
);
|
||||
let content = std::fs::read_to_string(&resumed_path)?;
|
||||
assert!(content.contains(&marker));
|
||||
assert!(content.contains(&marker2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_preserves_cli_configuration_overrides() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
let repo_root = exec_repo_root()?;
|
||||
|
||||
let marker = format!("resume-config-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--model")
|
||||
.arg("gpt-5.1")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
let path = find_session_file_containing_marker(&sessions_dir, &marker)
|
||||
.expect("no session file found after first run");
|
||||
|
||||
let marker2 = format!("resume-config-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
|
||||
let output = test
|
||||
.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--model")
|
||||
.arg("gpt-5.1-high")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt2)
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.output()
|
||||
.context("resume run should succeed")?;
|
||||
|
||||
assert!(output.status.success(), "resume run failed: {output:?}");
|
||||
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(
|
||||
stderr.contains("model: gpt-5.1-high"),
|
||||
"stderr missing model override: {stderr}"
|
||||
);
|
||||
if cfg!(target_os = "windows") {
|
||||
assert!(
|
||||
stderr.contains("sandbox: read-only"),
|
||||
"stderr missing downgraded sandbox note: {stderr}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
stderr.contains("sandbox: workspace-write"),
|
||||
"stderr missing sandbox override: {stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no resumed session file containing marker2");
|
||||
assert_eq!(resumed_path, path, "resume should append to same file");
|
||||
|
||||
let content = std::fs::read_to_string(&resumed_path)?;
|
||||
assert!(content.contains(&marker));
|
||||
assert!(content.contains(&marker2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_resume_accepts_images_after_subcommand() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let fixture = exec_fixture()?;
|
||||
let repo_root = exec_repo_root()?;
|
||||
|
||||
let marker = format!("resume-image-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let image_path = test.cwd_path().join("resume_image.png");
|
||||
let image_path_2 = test.cwd_path().join("resume_image_2.png");
|
||||
let image_bytes: &[u8] = &[
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
|
||||
0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F,
|
||||
0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00,
|
||||
0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
|
||||
0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
|
||||
];
|
||||
std::fs::write(&image_path, image_bytes)?;
|
||||
std::fs::write(&image_path_2, image_bytes)?;
|
||||
|
||||
let marker2 = format!("resume-image-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
test.cmd()
|
||||
.env("CODEX_RS_SSE_FIXTURE", &fixture)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg("resume")
|
||||
.arg("--last")
|
||||
.arg("--image")
|
||||
.arg(&image_path)
|
||||
.arg("--image")
|
||||
.arg(&image_path_2)
|
||||
.arg(&prompt2)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let sessions_dir = test.home_path().join("sessions");
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no session file found after resume with images");
|
||||
let image_count = last_user_image_count(&resumed_path);
|
||||
assert_eq!(
|
||||
image_count, 2,
|
||||
"resume prompt should include both attached images"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
564
vendor/codex/codex-rs/exec/tests/suite/sandbox.rs
vendored
Normal file
564
vendor/codex/codex-rs/exec/tests/suite/sandbox.rs
vendored
Normal file
|
|
@ -0,0 +1,564 @@
|
|||
#![cfg(unix)]
|
||||
use codex_core::spawn::StdioPolicy;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::process::ExitStatus;
|
||||
use tokio::fs::create_dir_all;
|
||||
use tokio::process::Child;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn spawn_command_under_sandbox(
|
||||
command: Vec<String>,
|
||||
command_cwd: AbsolutePathBuf,
|
||||
sandbox_policy: &SandboxPolicy,
|
||||
sandbox_cwd: &AbsolutePathBuf,
|
||||
stdio_policy: StdioPolicy,
|
||||
env: HashMap<String, String>,
|
||||
) -> std::io::Result<Child> {
|
||||
use codex_core::exec::ExecCapturePolicy;
|
||||
use codex_core::exec::ExecParams;
|
||||
use codex_core::exec::build_exec_request;
|
||||
use codex_core::sandboxing::SandboxPermissions;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use std::process::Stdio;
|
||||
|
||||
let codex_linux_sandbox_exe = None;
|
||||
let exec_request = build_exec_request(
|
||||
ExecParams {
|
||||
command,
|
||||
cwd: command_cwd,
|
||||
expiration: 1000.into(),
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
env,
|
||||
network: None,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
windows_sandbox_private_desktop: false,
|
||||
justification: None,
|
||||
arg0: None,
|
||||
},
|
||||
sandbox_policy,
|
||||
&FileSystemSandboxPolicy::from_legacy_sandbox_policy(sandbox_policy, sandbox_cwd),
|
||||
NetworkSandboxPolicy::from(sandbox_policy),
|
||||
sandbox_cwd,
|
||||
&codex_linux_sandbox_exe,
|
||||
/*use_legacy_landlock*/ false,
|
||||
)
|
||||
.map_err(|err| io::Error::other(err.to_string()))?;
|
||||
|
||||
let (program, args) = exec_request
|
||||
.command
|
||||
.split_first()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "command args are empty"))?;
|
||||
|
||||
let mut child = tokio::process::Command::new(program);
|
||||
if let Some(arg0) = exec_request.arg0.as_deref() {
|
||||
child.arg0(arg0);
|
||||
}
|
||||
child.args(args);
|
||||
child.current_dir(exec_request.cwd);
|
||||
child.env_clear();
|
||||
child.envs(exec_request.env);
|
||||
|
||||
match stdio_policy {
|
||||
StdioPolicy::RedirectForShellTool => {
|
||||
child.stdin(Stdio::null());
|
||||
child.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
}
|
||||
StdioPolicy::Inherit => {
|
||||
child
|
||||
.stdin(Stdio::inherit())
|
||||
.stdout(Stdio::inherit())
|
||||
.stderr(Stdio::inherit());
|
||||
}
|
||||
}
|
||||
|
||||
child.kill_on_drop(true).spawn()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn spawn_command_under_sandbox(
|
||||
command: Vec<String>,
|
||||
command_cwd: AbsolutePathBuf,
|
||||
sandbox_policy: &SandboxPolicy,
|
||||
sandbox_cwd: &AbsolutePathBuf,
|
||||
stdio_policy: StdioPolicy,
|
||||
env: HashMap<String, String>,
|
||||
) -> std::io::Result<Child> {
|
||||
use codex_core::spawn_command_under_linux_sandbox;
|
||||
let codex_linux_sandbox_exe = core_test_support::find_codex_linux_sandbox_exe()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?;
|
||||
spawn_command_under_linux_sandbox(
|
||||
codex_linux_sandbox_exe,
|
||||
command,
|
||||
command_cwd,
|
||||
sandbox_policy,
|
||||
sandbox_cwd,
|
||||
/*use_legacy_landlock*/ false,
|
||||
stdio_policy,
|
||||
/*network*/ None,
|
||||
env,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
/// Determines whether Linux sandbox tests can run on this host.
|
||||
///
|
||||
/// These tests require an enforceable filesystem sandbox. We run a tiny command
|
||||
/// under the production Landlock path and skip when enforcement is unavailable
|
||||
/// (for example on kernels or container profiles where Landlock is not
|
||||
/// enforced).
|
||||
async fn linux_sandbox_test_env() -> Option<HashMap<String, String>> {
|
||||
let command_cwd = AbsolutePathBuf::current_dir().ok()?;
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let policy = SandboxPolicy::new_read_only_policy();
|
||||
|
||||
if can_apply_linux_sandbox_policy(&policy, &command_cwd, &sandbox_cwd, HashMap::new()).await {
|
||||
return Some(HashMap::new());
|
||||
}
|
||||
|
||||
eprintln!("Skipping test: Landlock is not enforceable on this host.");
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
/// Returns whether a minimal command can run successfully with the requested
|
||||
/// Linux sandbox policy applied.
|
||||
///
|
||||
/// This is used as a capability probe so sandbox behavior tests only run when
|
||||
/// Landlock enforcement is actually active.
|
||||
async fn can_apply_linux_sandbox_policy(
|
||||
policy: &SandboxPolicy,
|
||||
command_cwd: &AbsolutePathBuf,
|
||||
sandbox_cwd: &AbsolutePathBuf,
|
||||
env: HashMap<String, String>,
|
||||
) -> bool {
|
||||
let spawn_result = spawn_command_under_sandbox(
|
||||
vec!["/usr/bin/true".to_string()],
|
||||
command_cwd.clone(),
|
||||
policy,
|
||||
sandbox_cwd,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
env,
|
||||
)
|
||||
.await;
|
||||
let Ok(mut child) = spawn_result else {
|
||||
return false;
|
||||
};
|
||||
child
|
||||
.wait()
|
||||
.await
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn python_multiprocessing_lock_works_under_sandbox() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
// Skip on Linux hosts where Landlock cannot actually be enforced.
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
let writable_roots = Vec::<AbsolutePathBuf>::new();
|
||||
|
||||
// From https://man7.org/linux/man-pages/man7/sem_overview.7.html
|
||||
//
|
||||
// > On Linux, named semaphores are created in a virtual filesystem,
|
||||
// > normally mounted under /dev/shm.
|
||||
#[cfg(target_os = "linux")]
|
||||
let writable_roots: Vec<AbsolutePathBuf> = vec!["/dev/shm".try_into().unwrap()];
|
||||
|
||||
let policy = SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots,
|
||||
read_only_access: Default::default(),
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: false,
|
||||
exclude_slash_tmp: false,
|
||||
};
|
||||
|
||||
let python_code = r#"import multiprocessing
|
||||
from multiprocessing import Lock, Process
|
||||
|
||||
def f(lock):
|
||||
with lock:
|
||||
print("Lock acquired in child process")
|
||||
|
||||
if __name__ == '__main__':
|
||||
lock = Lock()
|
||||
p = Process(target=f, args=(lock,))
|
||||
p.start()
|
||||
p.join()
|
||||
"#;
|
||||
|
||||
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"python3".to_string(),
|
||||
"-c".to_string(),
|
||||
python_code.to_string(),
|
||||
],
|
||||
command_cwd,
|
||||
&policy,
|
||||
&sandbox_cwd,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should be able to spawn python under sandbox");
|
||||
|
||||
let status = child.wait().await.expect("should wait for child process");
|
||||
assert!(status.success(), "python exited with {status:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn python_getpwuid_works_under_sandbox() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
|
||||
if std::process::Command::new("python3")
|
||||
.arg("--version")
|
||||
.status()
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("python3 not found in PATH, skipping test.");
|
||||
return;
|
||||
}
|
||||
|
||||
let policy = SandboxPolicy::new_read_only_policy();
|
||||
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"python3".to_string(),
|
||||
"-c".to_string(),
|
||||
"import pwd, os; print(pwd.getpwuid(os.getuid()))".to_string(),
|
||||
],
|
||||
command_cwd,
|
||||
&policy,
|
||||
&sandbox_cwd,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should be able to spawn python under sandbox");
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.expect("should be able to wait for child process");
|
||||
assert!(status.success(), "python exited with {status:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_distinguishes_command_and_policy_cwds() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
let temp = tempfile::tempdir().expect("should be able to create temp dir");
|
||||
let sandbox_root = temp.path().join("sandbox");
|
||||
let command_root = temp.path().join("command").abs();
|
||||
create_dir_all(&sandbox_root).await.expect("mkdir");
|
||||
create_dir_all(&command_root).await.expect("mkdir");
|
||||
let canonical_sandbox_root = tokio::fs::canonicalize(&sandbox_root)
|
||||
.await
|
||||
.expect("canonicalize sandbox root")
|
||||
.abs();
|
||||
let canonical_allowed_path = canonical_sandbox_root.join("allowed.txt");
|
||||
|
||||
let disallowed_path = command_root.join("forbidden.txt");
|
||||
|
||||
// Note writable_roots is empty: verify that `canonical_allowed_path` is
|
||||
// writable only because it is under the sandbox policy cwd, not because it
|
||||
// is under a writable root.
|
||||
let policy = SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: vec![],
|
||||
read_only_access: Default::default(),
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: true,
|
||||
exclude_slash_tmp: true,
|
||||
};
|
||||
|
||||
// Attempt to write inside the command cwd, which is outside of the sandbox policy cwd.
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"echo forbidden > forbidden.txt".to_string(),
|
||||
],
|
||||
command_root.clone(),
|
||||
&policy,
|
||||
&canonical_sandbox_root,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command writing to forbidden path");
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.expect("should wait for forbidden command");
|
||||
assert!(
|
||||
!status.success(),
|
||||
"sandbox unexpectedly allowed writing to command cwd: {status:?}"
|
||||
);
|
||||
let forbidden_exists = tokio::fs::try_exists(&disallowed_path)
|
||||
.await
|
||||
.expect("try_exists failed");
|
||||
assert!(
|
||||
!forbidden_exists,
|
||||
"forbidden path should not have been created"
|
||||
);
|
||||
|
||||
// Writing to the sandbox policy cwd after changing directories into it should succeed.
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"/usr/bin/touch".to_string(),
|
||||
canonical_allowed_path.to_string_lossy().into_owned(),
|
||||
],
|
||||
command_root,
|
||||
&policy,
|
||||
&canonical_sandbox_root,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command writing to sandbox root");
|
||||
|
||||
let status = child.wait().await.expect("should wait for allowed command");
|
||||
assert!(
|
||||
status.success(),
|
||||
"sandbox blocked allowed write: {status:?}"
|
||||
);
|
||||
let allowed_exists = tokio::fs::try_exists(&canonical_allowed_path)
|
||||
.await
|
||||
.expect("try_exists allowed failed");
|
||||
assert!(allowed_exists, "allowed path should exist");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_blocks_first_time_dot_codex_creation() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
|
||||
let temp = tempfile::tempdir().expect("should be able to create temp dir");
|
||||
let repo_root = temp.path().join("repo").abs();
|
||||
create_dir_all(&repo_root).await.expect("mkdir repo");
|
||||
let dot_codex = repo_root.join(".codex");
|
||||
let config_toml = dot_codex.join("config.toml");
|
||||
let policy = SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: vec![],
|
||||
read_only_access: Default::default(),
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: true,
|
||||
exclude_slash_tmp: true,
|
||||
};
|
||||
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"mkdir -p .codex && echo 'sandbox_mode = \"danger-full-access\"' > .codex/config.toml"
|
||||
.to_string(),
|
||||
],
|
||||
repo_root.clone(),
|
||||
&policy,
|
||||
&repo_root,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command creating .codex");
|
||||
|
||||
let status = child.wait().await.expect("should wait for .codex command");
|
||||
assert!(
|
||||
!status.success(),
|
||||
"sandbox unexpectedly allowed first-time .codex creation: {status:?}"
|
||||
);
|
||||
let dot_codex_metadata = tokio::fs::symlink_metadata(&dot_codex).await;
|
||||
if let Ok(metadata) = dot_codex_metadata {
|
||||
assert!(
|
||||
!metadata.is_dir(),
|
||||
"{} should not be creatable as a directory",
|
||||
dot_codex.display()
|
||||
);
|
||||
} else if let Err(err) = &dot_codex_metadata {
|
||||
assert_eq!(
|
||||
err.kind(),
|
||||
io::ErrorKind::NotFound,
|
||||
"unexpected metadata error for {}: {err}",
|
||||
dot_codex.display()
|
||||
);
|
||||
}
|
||||
let config_toml_exists = match tokio::fs::try_exists(&config_toml).await {
|
||||
Ok(exists) => exists,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotADirectory => false,
|
||||
Err(err) => panic!("try_exists {} failed: {err}", config_toml.display()),
|
||||
};
|
||||
assert!(
|
||||
!config_toml_exists,
|
||||
"{} should not have been created",
|
||||
config_toml.display()
|
||||
);
|
||||
}
|
||||
|
||||
fn unix_sock_body() {
|
||||
unsafe {
|
||||
let mut fds = [0i32; 2];
|
||||
let r = libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, fds.as_mut_ptr());
|
||||
assert_eq!(
|
||||
r,
|
||||
0,
|
||||
"socketpair(AF_UNIX, SOCK_DGRAM) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
let msg = b"hello_unix";
|
||||
// write() from one end (generic write is allowed)
|
||||
let sent = libc::write(fds[0], msg.as_ptr() as *const libc::c_void, msg.len());
|
||||
assert!(sent >= 0, "write() failed: {}", io::Error::last_os_error());
|
||||
|
||||
// recvfrom() on the other end. We don’t need the address for socketpair,
|
||||
// so we pass null pointers for src address.
|
||||
let mut buf = [0u8; 64];
|
||||
let recvd = libc::recvfrom(
|
||||
fds[1],
|
||||
buf.as_mut_ptr() as *mut libc::c_void,
|
||||
buf.len(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
assert!(
|
||||
recvd >= 0,
|
||||
"recvfrom() failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
let recvd_slice = &buf[..(recvd as usize)];
|
||||
assert_eq!(
|
||||
recvd_slice,
|
||||
&msg[..],
|
||||
"payload mismatch: sent {} bytes, got {} bytes",
|
||||
msg.len(),
|
||||
recvd
|
||||
);
|
||||
|
||||
// Also exercise AF_UNIX stream socketpair quickly to ensure AF_UNIX in general works.
|
||||
let mut sfds = [0i32; 2];
|
||||
let sr = libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sfds.as_mut_ptr());
|
||||
assert_eq!(
|
||||
sr,
|
||||
0,
|
||||
"socketpair(AF_UNIX, SOCK_STREAM) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
let snt2 = libc::write(sfds[0], msg.as_ptr() as *const libc::c_void, msg.len());
|
||||
assert!(
|
||||
snt2 >= 0,
|
||||
"write(stream) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
let mut b2 = [0u8; 64];
|
||||
let rcv2 = libc::recv(sfds[1], b2.as_mut_ptr() as *mut libc::c_void, b2.len(), 0);
|
||||
assert!(
|
||||
rcv2 >= 0,
|
||||
"recv(stream) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
// Clean up
|
||||
let _ = libc::close(sfds[0]);
|
||||
let _ = libc::close(sfds[1]);
|
||||
let _ = libc::close(fds[0]);
|
||||
let _ = libc::close(fds[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn allow_unix_socketpair_recvfrom() {
|
||||
run_code_under_sandbox(
|
||||
"allow_unix_socketpair_recvfrom",
|
||||
&SandboxPolicy::new_read_only_policy(),
|
||||
|| async { unix_sock_body() },
|
||||
)
|
||||
.await
|
||||
.expect("should be able to reexec");
|
||||
}
|
||||
|
||||
const IN_SANDBOX_ENV_VAR: &str = "IN_SANDBOX";
|
||||
|
||||
#[expect(clippy::expect_used)]
|
||||
pub async fn run_code_under_sandbox<F, Fut>(
|
||||
test_selector: &str,
|
||||
policy: &SandboxPolicy,
|
||||
child_body: F,
|
||||
) -> io::Result<Option<ExitStatus>>
|
||||
where
|
||||
F: FnOnce() -> Fut + Send + 'static,
|
||||
Fut: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
if std::env::var(IN_SANDBOX_ENV_VAR).is_err() {
|
||||
let exe = std::env::current_exe()?;
|
||||
let mut cmds = vec![exe.to_string_lossy().into_owned(), "--exact".into()];
|
||||
let mut stdio_policy = StdioPolicy::RedirectForShellTool;
|
||||
// Allow for us to pass forward --nocapture / use the right stdio policy.
|
||||
if std::env::args().any(|a| a == "--nocapture") {
|
||||
cmds.push("--nocapture".into());
|
||||
stdio_policy = StdioPolicy::Inherit;
|
||||
}
|
||||
cmds.push(test_selector.into());
|
||||
|
||||
// Your existing launcher:
|
||||
let command_cwd =
|
||||
AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
cmds,
|
||||
command_cwd,
|
||||
policy,
|
||||
&sandbox_cwd,
|
||||
stdio_policy,
|
||||
HashMap::from([("IN_SANDBOX".into(), "1".into())]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let status = child.wait().await?;
|
||||
Ok(Some(status))
|
||||
} else {
|
||||
// Child branch: run the provided body.
|
||||
child_body().await;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
33
vendor/codex/codex-rs/exec/tests/suite/server_error_exit.rs
vendored
Normal file
33
vendor/codex/codex-rs/exec/tests/suite/server_error_exit.rs
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
/// Verify that when the server reports an error, `codex-exec` exits with a
|
||||
/// non-zero status code so automation can detect failures.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exits_non_zero_when_server_reports_error() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// Mock a simple Responses API SSE stream that immediately reports a
|
||||
// `response.failed` event with an error message.
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![serde_json::json!({
|
||||
"type": "response.failed",
|
||||
"response": {
|
||||
"id": "resp_err_1",
|
||||
"error": {"code": "rate_limit_exceeded", "message": "synthetic server error"}
|
||||
}
|
||||
})]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.arg("--experimental-json")
|
||||
.assert()
|
||||
.code(1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in a new issue