From 232db0613a70301e36981c42e859d670a17f68f3 Mon Sep 17 00:00:00 2001 From: Ruslan Nigmatullin Date: Mon, 6 Apr 2026 20:17:08 -0700 Subject: [PATCH 01/28] app-server: Fix compilation of a test in mcp_resource (#16972) --- codex-rs/app-server/tests/suite/v2/mcp_resource.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/app-server/tests/suite/v2/mcp_resource.rs b/codex-rs/app-server/tests/suite/v2/mcp_resource.rs index db5ddfa9b2..0a38f3b37e 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_resource.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_resource.rs @@ -15,7 +15,7 @@ use codex_app_server_protocol::McpResourceReadResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; -use codex_login::AuthCredentialsStoreMode; +use codex_config::types::AuthCredentialsStoreMode; use core_test_support::responses; use pretty_assertions::assert_eq; use rmcp::handler::server::ServerHandler; From 4bb507d2c4fb978bd6ccc1ad65d467d532fc3b15 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Mon, 6 Apr 2026 20:26:21 -0700 Subject: [PATCH 02/28] Make AGENTS.md discovery FS-aware (#15826) ## Summary - make AGENTS.md discovery and loading fully FS-aware and remove the non-FS discover helper - migrate remote-aware codex-core tests to use TestEnv workspace setup instead of syncing a local workspace copy - add AGENTS.md corner-case coverage, including directory fallbacks and remote-aware integration coverage ## Testing - cargo test -p codex-core project_doc -- --nocapture - cargo test -p codex-core hierarchical_agents -- --nocapture - cargo test -p codex-core agents_md -- --nocapture - cargo test -p codex-tui status -- --nocapture - cargo test -p codex-tui-app-server status -- --nocapture - just fix - just fmt - just bazel-lock-update - just bazel-lock-check - just argument-comment-lint - remote Linux executor tests in progress via scripts/test-remote-env.sh --- codex-rs/Cargo.lock | 1 + codex-rs/core/src/codex.rs | 12 +- codex-rs/core/src/codex_tests.rs | 8 +- codex-rs/core/src/project_doc.rs | 111 +++++++++------ codex-rs/core/src/project_doc_tests.rs | 125 ++++++++++++++++- codex-rs/core/tests/common/test_codex.rs | 118 ++++++++++------ codex-rs/core/tests/common/test_codex_exec.rs | 1 + codex-rs/core/tests/suite/agents_md.rs | 130 ++++++++++++++++++ .../core/tests/suite/hierarchical_agents.rs | 34 +++-- codex-rs/core/tests/suite/mod.rs | 1 + codex-rs/core/tests/suite/remote_env.rs | 11 +- codex-rs/exec-server/src/lib.rs | 1 + codex-rs/exec-server/src/local_file_system.rs | 5 + .../exec-server/src/remote_file_system.rs | 4 + codex-rs/exec-server/src/rpc.rs | 8 ++ .../src/server/file_system_handler.rs | 5 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/chatwidget.rs | 15 ++ codex-rs/tui/src/status/card.rs | 34 ++++- codex-rs/tui/src/status/helpers.rs | 90 ++++++------ codex-rs/tui/src/status/mod.rs | 1 + 21 files changed, 545 insertions(+), 171 deletions(-) create mode 100644 codex-rs/core/tests/suite/agents_md.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d1b1e5eb9c..3578fd8c63 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2794,6 +2794,7 @@ dependencies = [ "codex-cloud-requirements", "codex-config", "codex-core", + "codex-exec-server", "codex-features", "codex-feedback", "codex-file-search", diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 4bf309c902..423c62848a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -536,7 +536,11 @@ impl Codex { config.startup_warnings.push(message); } - let user_instructions = get_user_instructions(&config).await; + let environment = environment_manager + .current() + .await + .map_err(|err| CodexErr::Fatal(format!("failed to create environment: {err}")))?; + let user_instructions = get_user_instructions(&config, environment.as_deref()).await; let exec_policy = if crate::guardian::is_guardian_reviewer_source(&session_source) { // Guardian review should rely on the built-in shell safety checks, @@ -664,12 +668,12 @@ impl Codex { agent_status_tx.clone(), conversation_history, session_source_clone, - environment_manager, skills_manager, plugins_manager, mcp_manager.clone(), skills_watcher, agent_control, + environment, ) .await .map_err(|e| { @@ -1518,12 +1522,12 @@ impl Session { agent_status: watch::Sender, initial_history: InitialHistory, session_source: SessionSource, - environment_manager: Arc, skills_manager: Arc, plugins_manager: Arc, mcp_manager: Arc, skills_watcher: Arc, agent_control: AgentControl, + environment: Option>, ) -> anyhow::Result> { debug!( "Configuring session: model={}; provider={:?}", @@ -1963,7 +1967,7 @@ impl Session { code_mode_service: crate::tools::code_mode::CodeModeService::new( config.js_repl_node_path.clone(), ), - environment: environment_manager.current().await?, + environment, }; services .model_client diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index 88a8902f85..cf7c23be90 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -2612,14 +2612,16 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { agent_status_tx, InitialHistory::New, SessionSource::Exec, - Arc::new(codex_exec_server::EnvironmentManager::new( - /*exec_server_url*/ None, - )), skills_manager, plugins_manager, mcp_manager, Arc::new(SkillsWatcher::noop()), AgentControl::default(), + Some(Arc::new( + codex_exec_server::Environment::create(/*exec_server_url*/ None) + .await + .expect("create environment"), + )), ) .await; diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 1b72f64610..236c25a3c5 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -21,10 +21,12 @@ use crate::config_loader::default_project_root_markers; use crate::config_loader::merge_toml_values; use crate::config_loader::project_root_markers_from_config; use codex_app_server_protocol::ConfigLayerSource; +use codex_exec_server::Environment; +use codex_exec_server::ExecutorFileSystem; use codex_features::Feature; +use codex_utils_absolute_path::AbsolutePathBuf; use dunce::canonicalize as normalize_path; -use std::path::PathBuf; -use tokio::io::AsyncReadExt; +use std::io; use toml::Value as TomlValue; use tracing::error; @@ -76,8 +78,19 @@ fn render_js_repl_instructions(config: &Config) -> Option { /// Combines `Config::instructions` and `AGENTS.md` (if present) into a single /// string of instructions. -pub(crate) async fn get_user_instructions(config: &Config) -> Option { - let project_docs = read_project_docs(config).await; +pub(crate) async fn get_user_instructions( + config: &Config, + environment: Option<&Environment>, +) -> Option { + let fs = environment?.get_filesystem(); + get_user_instructions_with_fs(config, fs.as_ref()).await +} + +pub(crate) async fn get_user_instructions_with_fs( + config: &Config, + fs: &dyn ExecutorFileSystem, +) -> Option { + let project_docs = read_project_docs_with_fs(config, fs).await; let mut output = String::new(); @@ -125,14 +138,25 @@ pub(crate) async fn get_user_instructions(config: &Config) -> Option { /// concatenation of all discovered docs. If no documentation file is found the /// function returns `Ok(None)`. Unexpected I/O failures bubble up as `Err` so /// callers can decide how to handle them. -pub async fn read_project_docs(config: &Config) -> std::io::Result> { +pub async fn read_project_docs( + config: &Config, + environment: &Environment, +) -> io::Result> { + let fs = environment.get_filesystem(); + read_project_docs_with_fs(config, fs.as_ref()).await +} + +async fn read_project_docs_with_fs( + config: &Config, + fs: &dyn ExecutorFileSystem, +) -> io::Result> { let max_total = config.project_doc_max_bytes; if max_total == 0 { return Ok(None); } - let paths = discover_project_doc_paths(config)?; + let paths = discover_project_doc_paths(config, fs).await?; if paths.is_empty() { return Ok(None); } @@ -145,16 +169,22 @@ pub async fn read_project_docs(config: &Config) -> std::io::Result f, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, - Err(e) => return Err(e), - }; + match fs.get_metadata(&p).await { + Ok(metadata) if !metadata.is_file => continue, + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => continue, + Err(err) => return Err(err), + } - let size = file.metadata().await?.len(); - let mut reader = tokio::io::BufReader::new(file).take(remaining); - let mut data: Vec = Vec::new(); - reader.read_to_end(&mut data).await?; + let mut data = match fs.read_file(&p).await { + Ok(data) => data, + Err(err) if err.kind() == io::ErrorKind::NotFound => continue, + Err(err) => return Err(err), + }; + let size = data.len() as u64; + if size > remaining { + data.truncate(remaining as usize); + } if size > remaining { tracing::warn!( @@ -183,10 +213,17 @@ pub async fn read_project_docs(config: &Config) -> std::io::Result std::io::Result> { - let mut dir = config.cwd.to_path_buf(); +pub async fn discover_project_doc_paths( + config: &Config, + fs: &dyn ExecutorFileSystem, +) -> io::Result> { + if config.project_doc_max_bytes == 0 { + return Ok(Vec::new()); + } + + let mut dir = config.cwd.clone(); if let Ok(canon) = normalize_path(&dir) { - dir = canon; + dir = AbsolutePathBuf::try_from(canon)?; } let mut merged = TomlValue::Table(toml::map::Map::new()); @@ -211,14 +248,14 @@ pub fn discover_project_doc_paths(config: &Config) -> std::io::Result true, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, - Err(e) => return Err(e), + Err(err) if err.kind() == io::ErrorKind::NotFound => false, + Err(err) => return Err(err), }; if marker_exists { - project_root = Some(ancestor.to_path_buf()); + project_root = Some(AbsolutePathBuf::try_from(ancestor.to_path_buf())?); break; } } @@ -228,11 +265,11 @@ pub fn discover_project_doc_paths(config: &Config) -> std::io::Result = if let Some(root) = project_root { + let search_dirs: Vec = if let Some(root) = project_root { let mut dirs = Vec::new(); - let mut cursor = dir.as_path(); + let mut cursor = dir.clone(); loop { - dirs.push(cursor.to_path_buf()); + dirs.push(cursor.clone()); if cursor == root { break; } @@ -247,29 +284,25 @@ pub fn discover_project_doc_paths(config: &Config) -> std::io::Result = Vec::new(); + let mut found: Vec = Vec::new(); let candidate_filenames = candidate_filenames(config); for d in search_dirs { for name in &candidate_filenames { - let candidate = d.join(name); - match std::fs::symlink_metadata(&candidate) { - Ok(md) => { - let ft = md.file_type(); - // Allow regular files and symlinks; opening will later fail for dangling links. - if ft.is_file() || ft.is_symlink() { - found.push(candidate); - break; - } + let candidate = d.join(name)?; + match fs.get_metadata(&candidate).await { + Ok(md) if md.is_file => { + found.push(candidate); + break; } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, - Err(e) => return Err(e), + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => continue, + Err(err) => return Err(err), } } } Ok(found) } - fn candidate_filenames<'a>(config: &'a Config) -> Vec<&'a str> { let mut names: Vec<&'a str> = Vec::with_capacity(2 + config.project_doc_fallback_filenames.len()); diff --git a/codex-rs/core/src/project_doc_tests.rs b/codex-rs/core/src/project_doc_tests.rs index 9f4d9c5286..be9cb44b28 100644 --- a/codex-rs/core/src/project_doc_tests.rs +++ b/codex-rs/core/src/project_doc_tests.rs @@ -1,12 +1,23 @@ use super::*; use crate::config::ConfigBuilder; +use codex_exec_server::LOCAL_FS; use codex_features::Feature; +use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::PathBufExt; use core_test_support::TempDirExt; +use pretty_assertions::assert_eq; use std::fs; use std::path::PathBuf; use tempfile::TempDir; +async fn get_user_instructions(config: &Config) -> Option { + super::get_user_instructions_with_fs(config, LOCAL_FS.as_ref()).await +} + +async fn discover_project_doc_paths(config: &Config) -> std::io::Result> { + super::discover_project_doc_paths(config, LOCAL_FS.as_ref()).await +} + /// Helper that returns a `Config` pointing at `root` and using `limit` as /// the maximum number of bytes to embed from AGENTS.md. The caller can /// optionally specify a custom `instructions` string – when `None` the @@ -85,6 +96,16 @@ async fn no_doc_file_returns_none() { assert!(res.is_none(), "Expected None when AGENTS.md is absent"); } +#[tokio::test] +async fn no_environment_returns_none() { + let tmp = tempfile::tempdir().expect("tempdir"); + let config = make_config(&tmp, /*limit*/ 4096, Some("user instructions")).await; + + let res = super::get_user_instructions(&config, /*environment*/ None).await; + + assert_eq!(res, None); +} + /// Small file within the byte-limit is returned unmodified. #[tokio::test] async fn doc_smaller_than_limit_is_returned() { @@ -161,6 +182,18 @@ async fn zero_byte_limit_disables_docs() { ); } +#[tokio::test] +async fn zero_byte_limit_disables_discovery() { + let tmp = tempfile::tempdir().expect("tempdir"); + fs::write(tmp.path().join("AGENTS.md"), "something").unwrap(); + + let discovery = + discover_project_doc_paths(&make_config(&tmp, /*limit*/ 0, /*instructions*/ None).await) + .await + .expect("discover paths"); + assert_eq!(discovery, Vec::::new()); +} + #[tokio::test] async fn js_repl_instructions_are_appended_when_enabled() { let tmp = tempfile::tempdir().expect("tempdir"); @@ -293,11 +326,18 @@ async fn project_root_markers_are_honored_for_agents_discovery() { .await; cfg.cwd = nested.abs(); - let discovery = discover_project_doc_paths(&cfg).expect("discover paths"); - let expected_parent = - dunce::canonicalize(root.path().join("AGENTS.md")).expect("canonical parent doc path"); - let expected_child = - dunce::canonicalize(cfg.cwd.as_path().join("AGENTS.md")).expect("canonical child doc path"); + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); + let expected_parent = AbsolutePathBuf::try_from( + dunce::canonicalize(root.path().join("AGENTS.md")).expect("canonical parent doc path"), + ) + .expect("absolute parent doc path"); + let expected_child = AbsolutePathBuf::try_from( + dunce::canonicalize(cfg.cwd.join("AGENTS.md").expect("absolute child doc path")) + .expect("canonical child doc path"), + ) + .expect("absolute child doc path"); assert_eq!(discovery.len(), 2); assert_eq!(discovery[0], expected_parent); assert_eq!(discovery[1], expected_child); @@ -321,7 +361,9 @@ async fn agents_local_md_preferred() { assert_eq!(res, "local"); - let discovery = discover_project_doc_paths(&cfg).expect("discover paths"); + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); assert_eq!(discovery.len(), 1); assert_eq!( discovery[0].file_name().unwrap().to_string_lossy(), @@ -371,7 +413,9 @@ async fn agents_md_preferred_over_fallbacks() { assert_eq!(res, "primary"); - let discovery = discover_project_doc_paths(&cfg).expect("discover paths"); + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); assert_eq!(discovery.len(), 1); assert!( discovery[0] @@ -382,6 +426,73 @@ async fn agents_md_preferred_over_fallbacks() { ); } +#[tokio::test] +async fn agents_md_directory_is_ignored() { + let tmp = tempfile::tempdir().expect("tempdir"); + fs::create_dir(tmp.path().join("AGENTS.md")).unwrap(); + + let cfg = make_config(&tmp, /*limit*/ 4096, /*instructions*/ None).await; + + let res = get_user_instructions(&cfg).await; + assert_eq!(res, None); + + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); + assert_eq!(discovery, Vec::::new()); +} + +#[cfg(unix)] +#[tokio::test] +async fn agents_md_special_file_is_ignored() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + + let tmp = tempfile::tempdir().expect("tempdir"); + let path = tmp.path().join("AGENTS.md"); + let c_path = CString::new(path.as_os_str().as_bytes()).expect("path without nul"); + // SAFETY: `c_path` is a valid, nul-terminated path and `mkfifo` does not + // retain the pointer after the call. + let rc = unsafe { libc::mkfifo(c_path.as_ptr(), 0o644) }; + assert_eq!(rc, 0); + + let cfg = make_config(&tmp, /*limit*/ 4096, /*instructions*/ None).await; + + let res = get_user_instructions(&cfg).await; + assert_eq!(res, None); + + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); + assert_eq!(discovery, Vec::::new()); +} + +#[tokio::test] +async fn override_directory_falls_back_to_agents_md_file() { + let tmp = tempfile::tempdir().expect("tempdir"); + fs::create_dir(tmp.path().join(LOCAL_PROJECT_DOC_FILENAME)).unwrap(); + fs::write(tmp.path().join(DEFAULT_PROJECT_DOC_FILENAME), "primary").unwrap(); + + let cfg = make_config(&tmp, /*limit*/ 4096, /*instructions*/ None).await; + + let res = get_user_instructions(&cfg) + .await + .expect("AGENTS.md should be used when override is a directory"); + assert_eq!(res, "primary"); + + let discovery = discover_project_doc_paths(&cfg) + .await + .expect("discover paths"); + assert_eq!(discovery.len(), 1); + assert_eq!( + discovery[0] + .file_name() + .expect("file name") + .to_string_lossy(), + DEFAULT_PROJECT_DOC_FILENAME + ); +} + #[tokio::test] async fn skills_are_not_appended_to_project_doc() { let tmp = tempfile::tempdir().expect("tempdir"); diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 10957fd9f0..bffd0cbfd6 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -1,3 +1,4 @@ +use std::future::Future; use std::mem::swap; use std::path::Path; use std::path::PathBuf; @@ -34,12 +35,12 @@ use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; +use futures::future::BoxFuture; use serde_json::Value; use tempfile::TempDir; use wiremock::MockServer; use crate::PathBufExt; -use crate::PathExt; use crate::RemoteEnvConfig; use crate::TempDirExt; use crate::get_remote_test_env; @@ -55,6 +56,8 @@ use wiremock::matchers::path_regex; type ConfigMutator = dyn FnOnce(&mut Config) + Send; type PreBuildHook = dyn FnOnce(&Path) + Send + 'static; +type WorkspaceSetup = dyn FnOnce(AbsolutePathBuf, Arc) -> BoxFuture<'static, Result<()>> + + Send; const TEST_MODEL_WITH_EXPERIMENTAL_TOOLS: &str = "test-gpt-5.1-codex"; const REMOTE_EXEC_SERVER_START_TIMEOUT: Duration = Duration::from_secs(5); const REMOTE_EXEC_SERVER_POLL_INTERVAL: Duration = Duration::from_millis(25); @@ -97,24 +100,28 @@ impl RemoteExecServerProcess { #[derive(Debug)] pub struct TestEnv { environment: codex_exec_server::Environment, - cwd: PathBuf, - _local_cwd_temp_dir: Option, + cwd: AbsolutePathBuf, + local_cwd_temp_dir: Option>, _remote_exec_server_process: Option, } impl TestEnv { pub async fn local() -> Result { - let local_cwd_temp_dir = TempDir::new()?; - let cwd = local_cwd_temp_dir.path().to_path_buf(); + let local_cwd_temp_dir = Arc::new(TempDir::new()?); + let cwd = local_cwd_temp_dir.abs(); let environment = codex_exec_server::Environment::create(/*exec_server_url*/ None).await?; Ok(Self { environment, cwd, - _local_cwd_temp_dir: Some(local_cwd_temp_dir), + local_cwd_temp_dir: Some(local_cwd_temp_dir), _remote_exec_server_process: None, }) } + pub fn cwd(&self) -> &AbsolutePathBuf { + &self.cwd + } + pub fn environment(&self) -> &codex_exec_server::Environment { &self.environment } @@ -122,6 +129,10 @@ impl TestEnv { pub fn exec_server_url(&self) -> Option<&str> { self.environment.exec_server_url() } + + fn local_cwd_temp_dir(&self) -> Option> { + self.local_cwd_temp_dir.clone() + } } pub async fn test_env() -> Result { @@ -134,16 +145,13 @@ pub async fn test_env() -> Result { let cwd = remote_aware_cwd_path(); environment .get_filesystem() - .create_directory( - &absolute_path(&cwd)?, - CreateDirectoryOptions { recursive: true }, - ) + .create_directory(&cwd, CreateDirectoryOptions { recursive: true }) .await?; - remote_process.process.register_cleanup_path(&cwd); + remote_process.process.register_cleanup_path(cwd.as_path()); Ok(TestEnv { environment, cwd, - _local_cwd_temp_dir: None, + local_cwd_temp_dir: None, _remote_exec_server_process: Some(remote_process.process), }) } @@ -201,11 +209,12 @@ echo $!" }) } -fn remote_aware_cwd_path() -> PathBuf { +fn remote_aware_cwd_path() -> AbsolutePathBuf { PathBuf::from(format!( "/tmp/codex-core-test-cwd-{}", remote_exec_server_instance_id() )) + .abs() } fn wait_for_remote_listen_url(container_name: &str, stdout_path: &str) -> Result { @@ -299,10 +308,6 @@ fn docker_command_capture_stdout(args: [&str; N]) -> Result Result { - Ok(path.abs()) -} - /// A collection of different ways the model can output an apply_patch call #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ApplyPatchModelOutput { @@ -326,6 +331,7 @@ pub struct TestCodexBuilder { config_mutators: Vec>, auth: CodexAuth, pre_build_hooks: Vec>, + workspace_setups: Vec>, home: Option>, user_shell_override: Option, } @@ -359,6 +365,16 @@ impl TestCodexBuilder { self } + pub fn with_workspace_setup(mut self, setup: F) -> Self + where + F: FnOnce(AbsolutePathBuf, Arc) -> Fut + Send + 'static, + Fut: Future> + Send + 'static, + { + self.workspace_setups + .push(Box::new(move |cwd, fs| Box::pin(setup(cwd, fs)))); + self + } + pub fn with_home(mut self, home: Arc) -> Self { self.home = Some(home); self @@ -382,25 +398,24 @@ impl TestCodexBuilder { Some(home) => home, None => Arc::new(TempDir::new()?), }; - Box::pin(self.build_with_home(server, home, /*resume_from*/ None)).await + let base_url = format!("{}/v1", server.uri()); + let test_env = TestEnv::local().await?; + Box::pin(self.build_with_home_and_base_url(base_url, home, /*resume_from*/ None, test_env)) + .await } pub async fn build_remote_aware( &mut self, server: &wiremock::MockServer, ) -> anyhow::Result { - let test_env = test_env().await?; let home = match self.home.clone() { Some(home) => home, None => Arc::new(TempDir::new()?), }; let base_url = format!("{}/v1", server.uri()); - let cwd = test_env.cwd.to_path_buf(); - self.config_mutators.push(Box::new(move |config| { - config.cwd = cwd.abs(); - })); - let (config, cwd) = self.prepare_config(base_url, &home).await?; - Box::pin(self.build_from_config(config, cwd, home, /*resume_from*/ None, test_env)).await + let test_env = test_env().await?; + Box::pin(self.build_with_home_and_base_url(base_url, home, /*resume_from*/ None, test_env)) + .await } pub async fn build_with_streaming_server( @@ -412,10 +427,12 @@ impl TestCodexBuilder { Some(home) => home, None => Arc::new(TempDir::new()?), }; + let test_env = TestEnv::local().await?; Box::pin(self.build_with_home_and_base_url( format!("{base_url}/v1"), home, /*resume_from*/ None, + test_env, )) .await } @@ -435,7 +452,9 @@ impl TestCodexBuilder { config.model_provider.supports_websockets = true; config.experimental_realtime_ws_model = Some("realtime-test-model".to_string()); })); - Box::pin(self.build_with_home_and_base_url(base_url, home, /*resume_from*/ None)).await + let test_env = TestEnv::local().await?; + Box::pin(self.build_with_home_and_base_url(base_url, home, /*resume_from*/ None, test_env)) + .await } pub async fn resume( @@ -443,19 +462,10 @@ impl TestCodexBuilder { server: &wiremock::MockServer, home: Arc, rollout_path: PathBuf, - ) -> anyhow::Result { - Box::pin(self.build_with_home(server, home, Some(rollout_path))).await - } - - async fn build_with_home( - &mut self, - server: &wiremock::MockServer, - home: Arc, - resume_from: Option, ) -> anyhow::Result { let base_url = format!("{}/v1", server.uri()); - let (config, cwd) = self.prepare_config(base_url, &home).await?; - Box::pin(self.build_from_config(config, cwd, home, resume_from, TestEnv::local().await?)) + let test_env = TestEnv::local().await?; + Box::pin(self.build_with_home_and_base_url(base_url, home, Some(rollout_path), test_env)) .await } @@ -464,10 +474,30 @@ impl TestCodexBuilder { base_url: String, home: Arc, resume_from: Option, + test_env: TestEnv, ) -> anyhow::Result { - let (config, cwd) = self.prepare_config(base_url, &home).await?; - Box::pin(self.build_from_config(config, cwd, home, resume_from, TestEnv::local().await?)) - .await + let (config, fallback_cwd) = self + .prepare_config(base_url, &home, test_env.cwd().clone()) + .await?; + let environment_manager = Arc::new(codex_exec_server::EnvironmentManager::new( + test_env.exec_server_url().map(str::to_owned), + )); + let file_system = test_env.environment().get_filesystem(); + let mut workspace_setups = vec![]; + swap(&mut self.workspace_setups, &mut workspace_setups); + for setup in workspace_setups { + setup(config.cwd.clone(), Arc::clone(&file_system)).await?; + } + let cwd = test_env.local_cwd_temp_dir().unwrap_or(fallback_cwd); + Box::pin(self.build_from_config( + config, + cwd, + home, + resume_from, + test_env, + environment_manager, + )) + .await } async fn build_from_config( @@ -477,11 +507,9 @@ impl TestCodexBuilder { home: Arc, resume_from: Option, test_env: TestEnv, + environment_manager: Arc, ) -> anyhow::Result { let auth = self.auth.clone(); - let environment_manager = Arc::new(codex_exec_server::EnvironmentManager::new( - test_env.exec_server_url().map(str::to_owned), - )); let thread_manager = if config.model_catalog.is_some() { ThreadManager::new( &config, @@ -553,6 +581,7 @@ impl TestCodexBuilder { &mut self, base_url: String, home: &TempDir, + cwd_override: AbsolutePathBuf, ) -> anyhow::Result<(Config, Arc)> { let model_provider = ModelProviderInfo { base_url: Some(base_url), @@ -563,7 +592,7 @@ impl TestCodexBuilder { }; let cwd = Arc::new(TempDir::new()?); let mut config = load_default_config_for_test(home).await; - config.cwd = cwd.abs(); + config.cwd = cwd_override; config.model_provider = model_provider; for hook in self.pre_build_hooks.drain(..) { hook(home.path()); @@ -897,6 +926,7 @@ pub fn test_codex() -> TestCodexBuilder { config_mutators: vec![], auth: CodexAuth::from_api_key("dummy"), pre_build_hooks: vec![], + workspace_setups: vec![], home: None, user_shell_override: None, } diff --git a/codex-rs/core/tests/common/test_codex_exec.rs b/codex-rs/core/tests/common/test_codex_exec.rs index 5fe47018a6..ad32bcb025 100644 --- a/codex-rs/core/tests/common/test_codex_exec.rs +++ b/codex-rs/core/tests/common/test_codex_exec.rs @@ -17,6 +17,7 @@ impl TestCodexExecBuilder { ); cmd.current_dir(self.cwd.path()) .env("CODEX_HOME", self.home.path()) + .env("CODEX_SQLITE_HOME", self.home.path()) .env(CODEX_API_KEY_ENV_VAR, "dummy"); cmd } diff --git a/codex-rs/core/tests/suite/agents_md.rs b/codex-rs/core/tests/suite/agents_md.rs new file mode 100644 index 0000000000..7fbcc0703c --- /dev/null +++ b/codex-rs/core/tests/suite/agents_md.rs @@ -0,0 +1,130 @@ +use anyhow::Result; +use codex_exec_server::CreateDirectoryOptions; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::TestCodexBuilder; +use core_test_support::test_codex::test_codex; + +async fn agents_instructions(mut builder: TestCodexBuilder) -> Result { + let server = start_mock_server().await; + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let test = builder.build_remote_aware(&server).await?; + test.submit_turn("hello").await?; + + let request = resp_mock.single_request(); + request + .message_input_texts("user") + .into_iter() + .find(|text| text.starts_with("# AGENTS.md instructions for ")) + .ok_or_else(|| anyhow::anyhow!("instructions message not found")) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn agents_override_is_preferred_over_agents_md() -> Result<()> { + let instructions = + agents_instructions(test_codex().with_workspace_setup(|cwd, fs| async move { + let agents_md = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); + let override_md = cwd + .join("AGENTS.override.md") + .expect("absolute AGENTS.override.md path"); + fs.write_file(&agents_md, b"base doc".to_vec()).await?; + fs.write_file(&override_md, b"override doc".to_vec()) + .await?; + Ok::<(), anyhow::Error>(()) + })) + .await?; + + assert!( + instructions.contains("override doc"), + "expected AGENTS.override.md contents: {instructions}" + ); + assert!( + !instructions.contains("base doc"), + "expected AGENTS.md to be ignored when override exists: {instructions}" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn configured_fallback_is_used_when_agents_candidate_is_directory() -> Result<()> { + let instructions = agents_instructions( + test_codex() + .with_config(|config| { + config.project_doc_fallback_filenames = vec!["WORKFLOW.md".to_string()]; + }) + .with_workspace_setup(|cwd, fs| async move { + let agents_dir = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); + let fallback = cwd.join("WORKFLOW.md").expect("absolute WORKFLOW.md path"); + fs.create_directory(&agents_dir, CreateDirectoryOptions { recursive: true }) + .await?; + fs.write_file(&fallback, b"fallback doc".to_vec()).await?; + Ok::<(), anyhow::Error>(()) + }), + ) + .await?; + + assert!( + instructions.contains("fallback doc"), + "expected fallback doc contents: {instructions}" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn agents_docs_are_concatenated_from_project_root_to_cwd() -> Result<()> { + let instructions = agents_instructions( + test_codex() + .with_config(|config| { + config.cwd = config + .cwd + .join("nested/workspace") + .expect("absolute nested workspace path"); + }) + .with_workspace_setup(|cwd, fs| async move { + let nested = cwd.clone(); + let root = nested + .parent() + .and_then(|parent| parent.parent()) + .expect("nested workspace should have a project root ancestor"); + let root_agents = root + .join("AGENTS.md") + .expect("absolute root AGENTS.md path"); + let git_marker = root.join(".git").expect("absolute .git path"); + let nested_agents = nested + .join("AGENTS.md") + .expect("absolute nested AGENTS.md path"); + + fs.create_directory(&nested, CreateDirectoryOptions { recursive: true }) + .await?; + fs.write_file(&root_agents, b"root doc".to_vec()).await?; + fs.write_file(&git_marker, b"gitdir: /tmp/mock-git-dir\n".to_vec()) + .await?; + fs.write_file(&nested_agents, b"child doc".to_vec()).await?; + Ok::<(), anyhow::Error>(()) + }), + ) + .await?; + + let root_pos = instructions + .find("root doc") + .expect("expected root doc in AGENTS instructions"); + let child_pos = instructions + .find("child doc") + .expect("expected child doc in AGENTS instructions"); + assert!( + root_pos < child_pos, + "expected root doc before child doc: {instructions}" + ); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/hierarchical_agents.rs b/codex-rs/core/tests/suite/hierarchical_agents.rs index 8a3fadfbb0..bddc1a5276 100644 --- a/codex-rs/core/tests/suite/hierarchical_agents.rs +++ b/codex-rs/core/tests/suite/hierarchical_agents.rs @@ -18,21 +18,22 @@ async fn hierarchical_agents_appends_to_project_doc_in_user_instructions() { ) .await; - let mut builder = test_codex().with_config(|config| { - config - .features - .enable(Feature::ChildAgentsMd) - .expect("test config should allow feature update"); - std::fs::write( + let mut builder = test_codex() + .with_config(|config| { config - .cwd - .join("AGENTS.md") - .expect("absolute AGENTS.md path"), - "be nice", - ) - .expect("write AGENTS.md"); - }); - let test = builder.build(&server).await.expect("build test codex"); + .features + .enable(Feature::ChildAgentsMd) + .expect("test config should allow feature update"); + }) + .with_workspace_setup(|cwd, fs| async move { + let agents_md = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); + fs.write_file(&agents_md, b"be nice".to_vec()).await?; + Ok::<(), anyhow::Error>(()) + }); + let test = builder + .build_remote_aware(&server) + .await + .expect("build test codex"); test.submit_turn("hello").await.expect("submit turn"); @@ -73,7 +74,10 @@ async fn hierarchical_agents_emits_when_no_project_doc() { .enable(Feature::ChildAgentsMd) .expect("test config should allow feature update"); }); - let test = builder.build(&server).await.expect("build test codex"); + let test = builder + .build_remote_aware(&server) + .await + .expect("build test codex"); test.submit_turn("hello").await.expect("submit turn"); diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 4d58537e02..78dcf748a3 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -74,6 +74,7 @@ pub static CODEX_ALIASES_TEMP_DIR: Option = { mod abort_tasks; mod agent_jobs; mod agent_websocket; +mod agents_md; mod apply_patch_cli; #[cfg(not(target_os = "windows"))] mod approvals; diff --git a/codex-rs/core/tests/suite/remote_env.rs b/codex-rs/core/tests/suite/remote_env.rs index 0dd7718d3a..4cd9568a58 100644 --- a/codex-rs/core/tests/suite/remote_env.rs +++ b/codex-rs/core/tests/suite/remote_env.rs @@ -1,6 +1,6 @@ use anyhow::Result; use codex_exec_server::RemoveOptions; -use codex_utils_absolute_path::AbsolutePathBuf; +use core_test_support::PathBufExt; use core_test_support::get_remote_test_env; use core_test_support::test_codex::test_env; use pretty_assertions::assert_eq; @@ -17,8 +17,7 @@ async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> { let test_env = test_env().await?; let file_system = test_env.environment().get_filesystem(); - let file_path = remote_test_file_path(); - let file_path_abs = absolute_path(file_path.clone())?; + let file_path_abs = remote_test_file_path().abs(); let payload = b"remote-test-env-ok".to_vec(); file_system @@ -39,12 +38,6 @@ async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> { Ok(()) } - -fn absolute_path(path: PathBuf) -> Result { - AbsolutePathBuf::try_from(path.clone()) - .map_err(|err| anyhow::anyhow!("invalid absolute path {}: {err}", path.display())) -} - fn remote_test_file_path() -> PathBuf { let nanos = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(duration) => duration.as_nanos(), diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs index ab27ab2397..88378da9ee 100644 --- a/codex-rs/exec-server/src/lib.rs +++ b/codex-rs/exec-server/src/lib.rs @@ -41,6 +41,7 @@ pub use file_system::FileMetadata; pub use file_system::FileSystemResult; pub use file_system::ReadDirectoryEntry; pub use file_system::RemoveOptions; +pub use local_file_system::LOCAL_FS; pub use process::ExecBackend; pub use process::ExecProcess; pub use process::StartedExecProcess; diff --git a/codex-rs/exec-server/src/local_file_system.rs b/codex-rs/exec-server/src/local_file_system.rs index fba7efa306..69ab9d64b0 100644 --- a/codex-rs/exec-server/src/local_file_system.rs +++ b/codex-rs/exec-server/src/local_file_system.rs @@ -3,6 +3,8 @@ use codex_utils_absolute_path::AbsolutePathBuf; use std::path::Component; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; +use std::sync::LazyLock; use std::time::SystemTime; use std::time::UNIX_EPOCH; use tokio::io; @@ -17,6 +19,9 @@ use crate::RemoveOptions; const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024; +pub static LOCAL_FS: LazyLock> = + LazyLock::new(|| -> Arc { Arc::new(LocalFileSystem) }); + #[derive(Clone, Default)] pub(crate) struct LocalFileSystem; diff --git a/codex-rs/exec-server/src/remote_file_system.rs b/codex-rs/exec-server/src/remote_file_system.rs index 27e4fee911..7da10b0e50 100644 --- a/codex-rs/exec-server/src/remote_file_system.rs +++ b/codex-rs/exec-server/src/remote_file_system.rs @@ -23,6 +23,7 @@ use crate::ReadDirectoryEntry; use crate::RemoveOptions; const INVALID_REQUEST_ERROR_CODE: i64 = -32600; +const NOT_FOUND_ERROR_CODE: i64 = -32004; #[derive(Clone)] pub(crate) struct RemoteFileSystem { @@ -151,6 +152,9 @@ impl ExecutorFileSystem for RemoteFileSystem { fn map_remote_error(error: ExecServerError) -> io::Error { match error { + ExecServerError::Server { code, message } if code == NOT_FOUND_ERROR_CODE => { + io::Error::new(io::ErrorKind::NotFound, message) + } ExecServerError::Server { code, message } if code == INVALID_REQUEST_ERROR_CODE => { io::Error::new(io::ErrorKind::InvalidInput, message) } diff --git a/codex-rs/exec-server/src/rpc.rs b/codex-rs/exec-server/src/rpc.rs index f2d725e69c..bf7cb27a5a 100644 --- a/codex-rs/exec-server/src/rpc.rs +++ b/codex-rs/exec-server/src/rpc.rs @@ -356,6 +356,14 @@ pub(crate) fn invalid_params(message: String) -> JSONRPCErrorError { } } +pub(crate) fn not_found(message: String) -> JSONRPCErrorError { + JSONRPCErrorError { + code: -32004, + data: None, + message, + } +} + pub(crate) fn internal_error(message: String) -> JSONRPCErrorError { JSONRPCErrorError { code: -32603, diff --git a/codex-rs/exec-server/src/server/file_system_handler.rs b/codex-rs/exec-server/src/server/file_system_handler.rs index 2e4e1592d1..2f6c679dcc 100644 --- a/codex-rs/exec-server/src/server/file_system_handler.rs +++ b/codex-rs/exec-server/src/server/file_system_handler.rs @@ -26,6 +26,7 @@ use crate::RemoveOptions; use crate::local_file_system::LocalFileSystem; use crate::rpc::internal_error; use crate::rpc::invalid_request; +use crate::rpc::not_found; #[derive(Clone, Default)] pub(crate) struct FileSystemHandler { @@ -153,7 +154,9 @@ impl FileSystemHandler { } fn map_fs_error(err: io::Error) -> JSONRPCErrorError { - if err.kind() == io::ErrorKind::InvalidInput { + if err.kind() == io::ErrorKind::NotFound { + not_found(err.to_string()) + } else if err.kind() == io::ErrorKind::InvalidInput { invalid_request(err.to_string()) } else { internal_error(err.to_string()) diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 8c68de0da6..713a5b38ae 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -33,6 +33,7 @@ codex-chatgpt = { workspace = true } codex-cloud-requirements = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } +codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-feedback = { workspace = true } codex-file-search = { workspace = true } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 786911f158..f942308aa7 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -7303,6 +7303,8 @@ impl ChatWidget { .values() .cloned() .collect(); + let config = self.config.clone(); + let frame_requester = self.frame_requester.clone(); let (cell, handle) = crate::status::new_status_output_with_rate_limits_handle( &self.config, self.status_account_display.as_ref(), @@ -7317,8 +7319,21 @@ impl ChatWidget { self.model_display_name(), collaboration_mode, reasoning_effort_override, + "".to_string(), refreshing_rate_limits, ); + let agents_summary_handle = handle.clone(); + tokio::spawn(async move { + let agents_summary = match crate::status::discover_agents_summary(&config).await { + Ok(summary) => summary, + Err(err) => { + tracing::warn!(error = %err, "failed to discover project docs for /status"); + "".to_string() + } + }; + agents_summary_handle.finish_agents_summary_discovery(agents_summary); + frame_requester.schedule_frame(); + }); if let Some(request_id) = request_id { self.refreshing_status_outputs.push((request_id, handle)); } diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 781f4ae311..a737262139 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -28,7 +28,6 @@ use super::format::line_display_width; use super::format::push_label; use super::format::truncate_line_to_width; use super::helpers::compose_account_display; -use super::helpers::compose_agents_summary; use super::helpers::compose_model_display; use super::helpers::format_directory_display; use super::helpers::format_tokens_compact; @@ -68,10 +67,20 @@ struct StatusRateLimitState { #[derive(Debug, Clone)] pub(crate) struct StatusHistoryHandle { + agents_summary: Arc>, rate_limit_state: Arc>, } impl StatusHistoryHandle { + pub(crate) fn finish_agents_summary_discovery(&self, agents_summary: String) { + #[expect(clippy::expect_used)] + let mut current = self + .agents_summary + .write() + .expect("status history agents summary state poisoned"); + *current = agents_summary; + } + pub(crate) fn finish_rate_limit_refresh( &self, rate_limits: &[RateLimitSnapshotDisplay], @@ -98,7 +107,7 @@ struct StatusHistoryCell { model_details: Vec, directory: PathBuf, permissions: String, - agents_summary: String, + agents_summary: Arc>, collaboration_mode: Option, model_provider: Option, account: Option, @@ -177,6 +186,7 @@ pub(crate) fn new_status_output_with_rate_limits( model_name, collaboration_mode, reasoning_effort_override, + "".to_string(), refreshing_rate_limits, ) .0 @@ -197,6 +207,7 @@ pub(crate) fn new_status_output_with_rate_limits_handle( model_name: &str, collaboration_mode: Option<&str>, reasoning_effort_override: Option>, + agents_summary: String, refreshing_rate_limits: bool, ) -> (CompositeHistoryCell, StatusHistoryHandle) { let command = PlainHistoryCell::new(vec!["/status".magenta().into()]); @@ -214,6 +225,7 @@ pub(crate) fn new_status_output_with_rate_limits_handle( model_name, collaboration_mode, reasoning_effort_override, + agents_summary, refreshing_rate_limits, ); @@ -239,6 +251,7 @@ impl StatusHistoryCell { model_name: &str, collaboration_mode: Option<&str>, reasoning_effort_override: Option>, + agents_summary: String, refreshing_rate_limits: bool, ) -> (Self, StatusHistoryHandle) { let mut config_entries = vec![ @@ -302,7 +315,6 @@ impl StatusHistoryCell { } else { format!("Custom ({sandbox}, {approval})") }; - let agents_summary = compose_agents_summary(config); let model_provider = format_model_provider(config); let account = compose_account_display(account_display); let session_id = session_id.as_ref().map(std::string::ToString::to_string); @@ -333,6 +345,7 @@ impl StatusHistoryCell { rate_limits, refreshing_rate_limits, })); + let agents_summary = Arc::new(RwLock::new(agents_summary)); ( Self { @@ -340,7 +353,6 @@ impl StatusHistoryCell { model_details, directory: config.cwd.to_path_buf(), permissions, - agents_summary, collaboration_mode: collaboration_mode.map(ToString::to_string), model_provider, account, @@ -348,9 +360,13 @@ impl StatusHistoryCell { session_id, forked_from, token_usage, + agents_summary: agents_summary.clone(), rate_limit_state: rate_limit_state.clone(), }, - StatusHistoryHandle { rate_limit_state }, + StatusHistoryHandle { + agents_summary, + rate_limit_state, + }, ) } @@ -564,6 +580,12 @@ impl HistoryCell for StatusHistoryCell { .rate_limit_state .read() .expect("status history rate-limit state poisoned"); + #[expect(clippy::expect_used)] + let agents_summary = self + .agents_summary + .read() + .expect("status history agents summary state poisoned") + .clone(); if self.model_provider.is_some() { push_label(&mut labels, &mut seen, "Model provider"); @@ -625,7 +647,7 @@ impl HistoryCell for StatusHistoryCell { } lines.push(formatter.line("Directory", vec![Span::from(directory_value)])); lines.push(formatter.line("Permissions", vec![Span::from(self.permissions.clone())])); - lines.push(formatter.line("Agents.md", vec![Span::from(self.agents_summary.clone())])); + lines.push(formatter.line("Agents.md", vec![Span::from(agents_summary)])); if let Some(account_value) = account_value { lines.push(formatter.line("Account", vec![Span::from(account_value)])); diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 7813094c35..9f4c8f793b 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -5,7 +5,10 @@ use chrono::DateTime; use chrono::Local; use codex_core::config::Config; use codex_core::project_doc::discover_project_doc_paths; +use codex_exec_server::LOCAL_FS; use codex_protocol::account::PlanType; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::io; use std::path::Path; use unicode_width::UnicodeWidthStr; @@ -33,51 +36,52 @@ pub(crate) fn compose_model_display( (model_name.to_string(), details) } -pub(crate) fn compose_agents_summary(config: &Config) -> String { - match discover_project_doc_paths(config) { - Ok(paths) => { - let mut rels: Vec = Vec::new(); - for p in paths { - let file_name = p - .file_name() - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_else(|| "".to_string()); - let display = if let Some(parent) = p.parent() { - if parent == config.cwd.as_path() { - file_name.clone() - } else { - let mut cur = config.cwd.as_path(); - let mut ups = 0usize; - let mut reached = false; - while let Some(c) = cur.parent() { - if cur == parent { - reached = true; - break; - } - cur = c; - ups += 1; - } - if reached { - let up = format!("..{}", std::path::MAIN_SEPARATOR); - format!("{}{}", up.repeat(ups), file_name) - } else if let Ok(stripped) = p.strip_prefix(&config.cwd) { - normalize_agents_display_path(stripped) - } else { - normalize_agents_display_path(&p) - } - } - } else { - normalize_agents_display_path(&p) - }; - rels.push(display); - } - if rels.is_empty() { - "".to_string() +pub(crate) async fn discover_agents_summary(config: &Config) -> io::Result { + let paths = discover_project_doc_paths(config, LOCAL_FS.as_ref()).await?; + Ok(compose_agents_summary(config, &paths)) +} + +pub(crate) fn compose_agents_summary(config: &Config, paths: &[AbsolutePathBuf]) -> String { + let mut rels: Vec = Vec::new(); + for p in paths { + let file_name = p + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| "".to_string()); + let display = if let Some(parent) = p.parent() { + if parent.as_path() == config.cwd.as_path() { + file_name.clone() } else { - rels.join(", ") + let mut cur = config.cwd.as_path(); + let mut ups = 0usize; + let mut reached = false; + while let Some(c) = cur.parent() { + if cur == parent.as_path() { + reached = true; + break; + } + cur = c; + ups += 1; + } + if reached { + let up = format!("..{}", std::path::MAIN_SEPARATOR); + format!("{}{}", up.repeat(ups), file_name) + } else if let Ok(stripped) = p.strip_prefix(&config.cwd) { + normalize_agents_display_path(stripped) + } else { + normalize_agents_display_path(p) + } } - } - Err(_) => "".to_string(), + } else { + normalize_agents_display_path(p) + }; + rels.push(display); + } + + if rels.is_empty() { + "".to_string() + } else { + rels.join(", ") } } diff --git a/codex-rs/tui/src/status/mod.rs b/codex-rs/tui/src/status/mod.rs index e09955a6a6..1781104efd 100644 --- a/codex-rs/tui/src/status/mod.rs +++ b/codex-rs/tui/src/status/mod.rs @@ -19,6 +19,7 @@ pub(crate) use card::new_status_output; #[cfg(test)] pub(crate) use card::new_status_output_with_rate_limits; pub(crate) use card::new_status_output_with_rate_limits_handle; +pub(crate) use helpers::discover_agents_summary; pub(crate) use helpers::format_directory_display; pub(crate) use helpers::format_tokens_compact; pub(crate) use helpers::plan_type_display_name; From 24c598e8a9efdd7b9de2dd8c935f7204c1c7c414 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 6 Apr 2026 21:10:19 -0700 Subject: [PATCH 03/28] Honor null thread instructions (#16964) - Treat explicit null thread instructions as a blank-slate override while preserving omitted-field fallback behavior. - Preserve null through rollout resume/fork and keep explicit empty strings distinct. - Add app-server v2 start/fork coverage for the tri-state instruction params. --- .../schema/typescript/v2/ThreadForkParams.ts | 2 +- .../typescript/v2/ThreadResumeParams.ts | 2 +- .../schema/typescript/v2/ThreadStartParams.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 77 ++++++++- .../app-server/src/codex_message_processor.rs | 11 +- .../app-server/tests/suite/v2/thread_fork.rs | 149 ++++++++++++++++++ .../app-server/tests/suite/v2/turn_start.rs | 97 ++++++++++++ codex-rs/codex-api/src/common.rs | 6 +- codex-rs/codex-api/tests/clients.rs | 4 +- codex-rs/core/src/client.rs | 13 +- codex-rs/core/src/client_common.rs | 17 +- codex-rs/core/src/client_common_tests.rs | 8 +- codex-rs/core/src/codex.rs | 54 ++++--- codex-rs/core/src/codex_tests.rs | 28 ++-- codex-rs/core/src/compact_remote.rs | 15 +- codex-rs/core/src/config/mod.rs | 13 +- codex-rs/core/src/config_loader/tests.rs | 4 +- codex-rs/core/src/guardian/review_session.rs | 2 +- codex-rs/core/src/memories/phase1.rs | 4 +- codex-rs/core/src/session_startup_prewarm.rs | 4 +- codex-rs/core/src/tasks/review.rs | 2 +- .../core/src/tools/handlers/agent_jobs.rs | 2 +- .../src/tools/handlers/multi_agents/spawn.rs | 6 +- .../src/tools/handlers/multi_agents_common.rs | 5 +- .../src/tools/handlers/multi_agents_tests.rs | 8 +- .../tools/handlers/multi_agents_v2/spawn.rs | 6 +- codex-rs/core/tests/suite/client.rs | 43 ++++- .../core/tests/suite/client_websockets.rs | 4 +- codex-rs/core/tests/suite/compact_remote.rs | 2 +- codex-rs/core/tests/suite/personality.rs | 2 +- .../core/tests/suite/rollout_list_find.rs | 2 +- .../suite/stream_error_allows_next_turn.rs | 2 +- codex-rs/mcp-server/src/codex_tool_config.rs | 4 +- codex-rs/protocol/src/lib.rs | 1 + codex-rs/protocol/src/protocol.rs | 12 +- codex-rs/protocol/src/serde_helpers.rs | 23 +++ codex-rs/rollout/src/recorder.rs | 4 +- codex-rs/rollout/src/recorder_tests.rs | 4 +- codex-rs/rollout/src/tests.rs | 7 +- 39 files changed, 550 insertions(+), 101 deletions(-) create mode 100644 codex-rs/protocol/src/serde_helpers.rs diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts index a7ba311803..952da565a6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -27,7 +27,7 @@ model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null | null, developerInstructions?: string | null | null, ephemeral?: boolean, /** * If true, persist additional rollout EventMsg variants required to * reconstruct a richer thread history on subsequent resume/fork/read. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts index 770344de8e..fcde0ae502 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts @@ -36,7 +36,7 @@ model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, /** +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null | null, developerInstructions?: string | null | null, personality?: Personality | null, /** * If true, persist additional rollout EventMsg variants required to * reconstruct a richer thread history on subsequent resume/fork/read. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts index 61f501ad60..c7b27823f6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts @@ -12,7 +12,7 @@ export type ThreadStartParams = {model?: string | null, modelProvider?: string | * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, /** +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null | null, developerInstructions?: string | null | null, personality?: Personality | null, ephemeral?: boolean | null, /** * If true, opt into emitting raw Responses API items on the event stream. * This is for internal use only (e.g. Codex Cloud). */ diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 61b7db45e2..3562d9cda6 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2603,10 +2603,22 @@ pub struct ThreadStartParams { pub config: Option>, #[ts(optional = nullable)] pub service_name: Option, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub base_instructions: Option, + pub base_instructions: Option>, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub developer_instructions: Option, + pub developer_instructions: Option>, #[ts(optional = nullable)] pub personality: Option, #[ts(optional = nullable)] @@ -2721,10 +2733,22 @@ pub struct ThreadResumeParams { pub sandbox: Option, #[ts(optional = nullable)] pub config: Option>, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub base_instructions: Option, + pub base_instructions: Option>, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub developer_instructions: Option, + pub developer_instructions: Option>, #[ts(optional = nullable)] pub personality: Option, /// If true, persist additional rollout EventMsg variants required to @@ -2798,10 +2822,22 @@ pub struct ThreadForkParams { pub sandbox: Option, #[ts(optional = nullable)] pub config: Option>, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub base_instructions: Option, + pub base_instructions: Option>, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] #[ts(optional = nullable)] - pub developer_instructions: Option, + pub developer_instructions: Option>, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub ephemeral: bool, /// If true, persist additional rollout EventMsg variants required to @@ -8325,6 +8361,35 @@ mod tests { assert_eq!(serialized_without_override.get("serviceTier"), None); } + #[test] + fn thread_start_params_preserve_explicit_null_instructions() { + let params: ThreadStartParams = serde_json::from_value(json!({ + "baseInstructions": null, + "developerInstructions": null, + })) + .expect("params should deserialize"); + assert_eq!(params.base_instructions, Some(None)); + assert_eq!(params.developer_instructions, Some(None)); + + let serialized = serde_json::to_value(¶ms).expect("params should serialize"); + assert_eq!( + serialized.get("baseInstructions"), + Some(&serde_json::Value::Null) + ); + assert_eq!( + serialized.get("developerInstructions"), + Some(&serde_json::Value::Null) + ); + + let serialized_without_override = + serde_json::to_value(ThreadStartParams::default()).expect("params should serialize"); + assert_eq!(serialized_without_override.get("baseInstructions"), None); + assert_eq!( + serialized_without_override.get("developerInstructions"), + None + ); + } + #[test] fn turn_start_params_preserve_explicit_null_service_tier() { let params: TurnStartParams = serde_json::from_value(json!({ diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 920fcbeceb..91641898d1 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -2473,8 +2473,8 @@ impl CodexMessageProcessor { approval_policy: Option, approvals_reviewer: Option, sandbox: Option, - base_instructions: Option, - developer_instructions: Option, + base_instructions: Option>, + developer_instructions: Option>, personality: Option, ) -> ConfigOverrides { ConfigOverrides { @@ -4363,6 +4363,13 @@ impl CodexMessageProcessor { developer_instructions, /*personality*/ None, ); + if typesafe_overrides.base_instructions.is_none() + && let Ok(history) = RolloutRecorder::get_rollout_history(&rollout_path).await + && let Some(base_instructions) = history.get_base_instructions() + { + typesafe_overrides.base_instructions = + Some(base_instructions.map(|base_instructions| base_instructions.text)); + } typesafe_overrides.ephemeral = ephemeral.then_some(true); // Derive a Config using the same logic as new conversation, honoring overrides if provided. let cloud_requirements = self.current_cloud_requirements(); diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index 9907fc4b1d..b4e80d7816 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -26,6 +26,8 @@ use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput; use codex_config::types::AuthCredentialsStoreMode; use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; +use core_test_support::responses; +use core_test_support::skip_if_no_network; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; @@ -183,6 +185,153 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { Ok(()) } +#[tokio::test] +async fn thread_fork_honors_explicit_null_thread_instructions() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let body = responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "Done"), + responses::ev_completed("resp-1"), + ]); + let response_mock = + responses::mount_sse_sequence(&server, vec![body.clone(), body.clone(), body]).await; + + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let conversation_id = create_fake_rollout( + codex_home.path(), + "2025-01-05T12-00-00", + "2025-01-05T12:00:00Z", + "Saved user message", + Some("mock_provider"), + /*git_info*/ None, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let disabled_instruction_config = json!({ + "include_permissions_instructions": false, + "include_apps_instructions": false, + "include_environment_context": false, + "features.apps": false, + "features.plugins": false, + "features.codex_hooks": false, + "skills.bundled.enabled": false, + }); + + let fork_params = [ + ( + json!({ + "threadId": conversation_id.clone(), + "config": disabled_instruction_config.clone(), + }), + /*expect_instructions*/ true, + ), + ( + json!({ + "threadId": conversation_id.clone(), + "config": disabled_instruction_config.clone(), + "baseInstructions": null, + "developerInstructions": null, + }), + /*expect_instructions*/ false, + ), + ]; + + let mut forked_thread_ids = Vec::new(); + for (params, _expect_instructions) in fork_params { + let fork_id = mcp.send_raw_request("thread/fork", Some(params)).await?; + let fork_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(fork_id)), + ) + .await??; + let ThreadForkResponse { thread, .. } = to_response::(fork_resp)?; + forked_thread_ids.push(thread.id.clone()); + + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![UserInput::Text { + text: "continue".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + } + + let refork_id = mcp + .send_raw_request( + "thread/fork", + Some(json!({ + "threadId": forked_thread_ids[1].clone(), + "config": disabled_instruction_config.clone(), + })), + ) + .await?; + let refork_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(refork_id)), + ) + .await??; + let ThreadForkResponse { thread, .. } = to_response::(refork_resp)?; + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![UserInput::Text { + text: "continue again".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let requests = response_mock.requests(); + assert_eq!(requests.len(), 3); + for (request, expect_instructions) in requests.into_iter().zip([true, false, false]) { + let payload = request.body_json(); + assert_eq!( + payload.get("instructions").is_some(), + expect_instructions, + "unexpected instructions field in payload: {payload:?}" + ); + let developer_texts = request.message_input_texts("developer"); + assert!( + developer_texts.iter().all(|text| !text.is_empty()), + "did not expect empty developer instruction messages: {developer_texts:?}" + ); + } + + Ok(()) +} + #[tokio::test] async fn thread_fork_tracks_thread_initialized_analytics() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 59591dd0d1..e8f3e1df2c 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -152,6 +152,103 @@ async fn turn_start_sends_originator_header() -> Result<()> { Ok(()) } +#[tokio::test] +async fn turn_start_honors_explicit_null_thread_instructions() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let body = responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "Done"), + responses::ev_completed("resp-1"), + ]); + let response_mock = responses::mount_sse_sequence(&server, vec![body.clone(), body]).await; + + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri(), "never", &BTreeMap::new())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let disabled_instruction_config = json!({ + "include_permissions_instructions": false, + "include_apps_instructions": false, + "include_environment_context": false, + "features.apps": false, + "features.plugins": false, + "features.codex_hooks": false, + "skills.bundled.enabled": false, + }); + + let thread_start_params = [ + ( + json!({ + "model": "mock-model", + "config": disabled_instruction_config.clone(), + }), + /*expect_instructions*/ true, + ), + ( + json!({ + "model": "mock-model", + "config": disabled_instruction_config.clone(), + "baseInstructions": null, + "developerInstructions": null, + }), + /*expect_instructions*/ false, + ), + ]; + + for (params, _expect_instructions) in thread_start_params { + let thread_req = mcp.send_raw_request("thread/start", Some(params)).await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![V2UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + } + + let requests = response_mock.requests(); + assert_eq!(requests.len(), 2); + for (request, expect_instructions) in requests.into_iter().zip([true, false]) { + let payload = request.body_json(); + assert_eq!( + payload.get("instructions").is_some(), + expect_instructions, + "unexpected instructions field in payload: {payload:?}" + ); + let developer_texts = request.message_input_texts("developer"); + assert!( + developer_texts.iter().all(|text| !text.is_empty()), + "did not expect empty developer instruction messages: {developer_texts:?}" + ); + } + + Ok(()) +} + #[tokio::test] async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> { let responses = vec![create_final_assistant_message_sse_response("Done")?]; diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index 39fb976e67..a2a2c1d478 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -153,7 +153,8 @@ impl From for OpenAiVerbosity { #[derive(Debug, Serialize, Clone, PartialEq)] pub struct ResponsesApiRequest { pub model: String, - pub instructions: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub instructions: Option, pub input: Vec, pub tools: Vec, pub tool_choice: String, @@ -196,7 +197,8 @@ impl From<&ResponsesApiRequest> for ResponseCreateWsRequest { #[derive(Debug, Serialize)] pub struct ResponseCreateWsRequest { pub model: String, - pub instructions: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub instructions: Option, #[serde(skip_serializing_if = "Option::is_none")] pub previous_response_id: Option, pub input: Vec, diff --git a/codex-rs/codex-api/tests/clients.rs b/codex-rs/codex-api/tests/clients.rs index ba0f416788..2f3bc17e2c 100644 --- a/codex-rs/codex-api/tests/clients.rs +++ b/codex-rs/codex-api/tests/clients.rs @@ -266,7 +266,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> { let request = ResponsesApiRequest { model: "gpt-test".into(), - instructions: "Say hi".into(), + instructions: Some("Say hi".into()), input: Vec::new(), tools: Vec::new(), tool_choice: "auto".into(), @@ -302,7 +302,7 @@ async fn azure_default_store_attaches_ids_and_headers() -> Result<()> { let request = ResponsesApiRequest { model: "gpt-test".into(), - instructions: "Say hi".into(), + instructions: Some("Say hi".into()), input: vec![ResponseItem::Message { id: Some("msg_1".into()), role: "user".into(), diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index d77e36870a..b77dda2b75 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -399,7 +399,11 @@ impl ModelClient { ApiCompactClient::new(transport, client_setup.api_provider, client_setup.api_auth) .with_telemetry(Some(request_telemetry)); - let instructions = prompt.base_instructions.text.clone(); + let instructions = prompt + .base_instructions + .as_ref() + .map(|base_instructions| base_instructions.text.clone()) + .unwrap_or_default(); let input = prompt.get_formatted_input(); let tools = create_tools_json_for_responses_api(&prompt.tools)?; let reasoning = Self::build_reasoning(model_info, effort, summary); @@ -755,7 +759,10 @@ impl ModelClientSession { summary: ReasoningSummaryConfig, service_tier: Option, ) -> Result { - let instructions = &prompt.base_instructions.text; + let instructions = prompt + .base_instructions + .as_ref() + .map(|base_instructions| base_instructions.text.clone()); let input = prompt.get_formatted_input(); let tools = create_tools_json_for_responses_api(&prompt.tools)?; let default_reasoning_effort = model_info.default_reasoning_level; @@ -794,7 +801,7 @@ impl ModelClientSession { let prompt_cache_key = Some(self.client.state.conversation_id.to_string()); let request = ResponsesApiRequest { model: model_info.slug.clone(), - instructions: instructions.clone(), + instructions, input, tools, tool_choice: "auto".to_string(), diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index cb50ccac39..828839ae77 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -23,7 +23,7 @@ pub const REVIEW_EXIT_INTERRUPTED_TMPL: &str = include_str!("../templates/review/exit_interrupted.xml"); /// API request payload for a single model turn -#[derive(Default, Debug, Clone)] +#[derive(Debug, Clone)] pub struct Prompt { /// Conversation context input items. pub input: Vec, @@ -35,7 +35,7 @@ pub struct Prompt { /// Whether parallel tool calls are permitted for this prompt. pub(crate) parallel_tool_calls: bool, - pub base_instructions: BaseInstructions, + pub base_instructions: Option, /// Optionally specify the personality of the model. pub personality: Option, @@ -44,6 +44,19 @@ pub struct Prompt { pub output_schema: Option, } +impl Default for Prompt { + fn default() -> Self { + Self { + input: Vec::new(), + tools: Vec::new(), + parallel_tool_calls: false, + base_instructions: Some(BaseInstructions::default()), + personality: None, + output_schema: None, + } + } +} + impl Prompt { pub(crate) fn get_formatted_input(&self) -> Vec { let mut input = self.input.clone(); diff --git a/codex-rs/core/src/client_common_tests.rs b/codex-rs/core/src/client_common_tests.rs index 16a37796ad..968703046e 100644 --- a/codex-rs/core/src/client_common_tests.rs +++ b/codex-rs/core/src/client_common_tests.rs @@ -14,7 +14,7 @@ fn serializes_text_verbosity_when_set() { let tools: Vec = vec![]; let req = ResponsesApiRequest { model: "gpt-5.1".to_string(), - instructions: "i".to_string(), + instructions: Some("i".to_string()), input, tools, tool_choice: "auto".to_string(), @@ -57,7 +57,7 @@ fn serializes_text_schema_with_strict_format() { let req = ResponsesApiRequest { model: "gpt-5.1".to_string(), - instructions: "i".to_string(), + instructions: Some("i".to_string()), input, tools, tool_choice: "auto".to_string(), @@ -94,7 +94,7 @@ fn omits_text_when_not_set() { let tools: Vec = vec![]; let req = ResponsesApiRequest { model: "gpt-5.1".to_string(), - instructions: "i".to_string(), + instructions: Some("i".to_string()), input, tools, tool_choice: "auto".to_string(), @@ -116,7 +116,7 @@ fn omits_text_when_not_set() { fn serializes_flex_service_tier_when_set() { let req = ResponsesApiRequest { model: "gpt-5.1".to_string(), - instructions: "i".to_string(), + instructions: Some("i".to_string()), input: vec![], tools: vec![], tool_choice: "auto".to_string(), diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 423c62848a..237b77e38d 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -581,11 +581,15 @@ impl Codex { let model_info = models_manager .get_model_info(model.as_str(), &config.to_models_manager_config()) .await; - let base_instructions = config - .base_instructions - .clone() - .or_else(|| conversation_history.get_base_instructions().map(|s| s.text)) - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)); + let base_instructions = match config.base_instructions.clone() { + Some(base_instructions) => base_instructions, + None => conversation_history + .get_base_instructions() + .map(|base_instructions| { + base_instructions.map(|base_instructions| base_instructions.text) + }) + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), + }; // Respect thread-start tools. When missing (resumed/forked threads), read from the db // first, then fall back to rollout-file tools. @@ -1106,7 +1110,7 @@ pub(crate) struct SessionConfiguration { personality: Option, /// Base instructions for the session. - base_instructions: String, + base_instructions: Option, /// Compact prompt override. compact_prompt: Option, @@ -1545,9 +1549,10 @@ impl Session { conversation_id, forked_from_id, session_source, - BaseInstructions { - text: session_configuration.base_instructions.clone(), - }, + session_configuration + .base_instructions + .clone() + .map(|text| BaseInstructions { text }), session_configuration.dynamic_tools.clone(), if session_configuration.persist_extended_history { EventPersistenceMode::Extended @@ -2109,8 +2114,9 @@ impl Session { )); } } - sess.schedule_startup_prewarm(session_configuration.base_instructions.clone()) - .await; + if let Some(base_instructions) = session_configuration.base_instructions.clone() { + sess.schedule_startup_prewarm(base_instructions).await; + } let session_start_source = match &initial_history { InitialHistory::Resumed(_) => codex_hooks::SessionStartSource::Resume, InitialHistory::New | InitialHistory::Forked(_) => { @@ -2212,11 +2218,13 @@ impl Session { state.history.estimate_token_count(turn_context) } - pub(crate) async fn get_base_instructions(&self) -> BaseInstructions { + pub(crate) async fn get_base_instructions(&self) -> Option { let state = self.state.lock().await; - BaseInstructions { - text: state.session_configuration.base_instructions.clone(), - } + state + .session_configuration + .base_instructions + .clone() + .map(|text| BaseInstructions { text }) } // Merges connector IDs into the session-level explicit connector selection. @@ -3620,7 +3628,11 @@ impl Session { state.reference_context_item(), state.previous_turn_settings(), state.session_configuration.collaboration_mode.clone(), - state.session_configuration.base_instructions.clone(), + state + .session_configuration + .base_instructions + .clone() + .unwrap_or_default(), state.session_configuration.session_source.clone(), ) }; @@ -3861,7 +3873,13 @@ impl Session { pub(crate) async fn recompute_token_usage(&self, turn_context: &TurnContext) { let history = self.clone_history().await; - let base_instructions = self.get_base_instructions().await; + let empty_base_instructions = BaseInstructions { + text: String::new(), + }; + let base_instructions = self + .get_base_instructions() + .await + .unwrap_or(empty_base_instructions); let Some(estimated_total_tokens) = history.estimate_token_count_with_base_instructions(&base_instructions) else { @@ -6555,7 +6573,7 @@ pub(crate) fn build_prompt( input: Vec, router: &ToolRouter, turn_context: &TurnContext, - base_instructions: BaseInstructions, + base_instructions: Option, ) -> Prompt { let deferred_dynamic_tools = turn_context .dynamic_tools diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index cf7c23be90..b0437edbfe 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -591,11 +591,15 @@ async fn get_base_instructions_no_user_content() { { let mut state = session.state.lock().await; - state.session_configuration.base_instructions = model_info.base_instructions.clone(); + state.session_configuration.base_instructions = + Some(model_info.base_instructions.clone()); } let base_instructions = session.get_base_instructions().await; - assert_eq!(base_instructions.text, model_info.base_instructions); + assert_eq!( + base_instructions.expect("base instructions").text, + model_info.base_instructions + ); } } @@ -1091,7 +1095,7 @@ async fn recompute_token_usage_uses_session_base_instructions() { let override_instructions = "SESSION_OVERRIDE_INSTRUCTIONS_ONLY".repeat(120); { let mut state = session.state.lock().await; - state.session_configuration.base_instructions = override_instructions.clone(); + state.session_configuration.base_instructions = Some(override_instructions.clone()); } let item = user_message("hello"); @@ -1855,7 +1859,7 @@ async fn set_rate_limits_retains_previous_credits() { base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -1957,7 +1961,7 @@ async fn set_rate_limits_updates_plan_type_when_present() { base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -2222,7 +2226,7 @@ async fn attach_rollout_recorder(session: &Arc) -> PathBuf { ThreadId::default(), /*forked_from_id*/ None, SessionSource::Exec, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), @@ -2306,7 +2310,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -2572,7 +2576,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -2675,7 +2679,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -3515,7 +3519,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( base_instructions: config .base_instructions .clone() - .unwrap_or_else(|| model_info.get_model_instructions(config.personality)), + .unwrap_or_else(|| Some(model_info.get_model_instructions(config.personality))), compact_prompt: config.compact_prompt.clone(), approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, @@ -4264,7 +4268,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_baseline ThreadId::default(), /*forked_from_id*/ None, SessionSource::Exec, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), @@ -4361,7 +4365,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_full_rei ThreadId::default(), /*forked_from_id*/ None, SessionSource::Exec, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 5bc7944d28..640ca3c1f8 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -76,10 +76,16 @@ async fn run_remote_compact_task_inner_impl( .await; let mut history = sess.clone_history().await; let base_instructions = sess.get_base_instructions().await; + let token_count_base_instructions = + base_instructions + .clone() + .unwrap_or_else(|| BaseInstructions { + text: String::new(), + }); let deleted_items = trim_function_call_history_to_fit_context_window( &mut history, turn_context.as_ref(), - &base_instructions, + &token_count_base_instructions, ); if deleted_items > 0 { info!( @@ -127,8 +133,13 @@ async fn run_remote_compact_task_inner_impl( ) .or_else(|err| async { let total_usage_breakdown = sess.get_total_token_usage_breakdown().await; + let base_instruction_text = prompt + .base_instructions + .as_ref() + .map(|base_instructions| base_instructions.text.as_str()) + .unwrap_or(""); let compact_request_log_data = - build_compact_request_log_data(&prompt.input, &prompt.base_instructions.text); + build_compact_request_log_data(&prompt.input, base_instruction_text); log_remote_compact_failure( turn_context, &compact_request_log_data, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3c2d80464e..20d3dd2f1b 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -243,7 +243,7 @@ pub struct Config { pub user_instructions: Option, /// Base instructions override. - pub base_instructions: Option, + pub base_instructions: Option>, /// Developer instructions override injected as a separate message. pub developer_instructions: Option, @@ -687,7 +687,7 @@ impl Config { model_context_window: self.model_context_window, model_auto_compact_token_limit: self.model_auto_compact_token_limit, tool_output_token_limit: self.tool_output_token_limit, - base_instructions: self.base_instructions.clone(), + base_instructions: self.base_instructions.clone().flatten(), personality_enabled: self.features.enabled(Feature::Personality), model_supports_reasoning_summaries: self.model_supports_reasoning_summaries, model_catalog: self.model_catalog.clone(), @@ -1200,8 +1200,8 @@ pub struct ConfigOverrides { pub js_repl_node_path: Option, pub js_repl_node_module_dirs: Option>, pub zsh_path: Option, - pub base_instructions: Option, - pub developer_instructions: Option, + pub base_instructions: Option>, + pub developer_instructions: Option>, pub personality: Option, pub compact_prompt: Option, pub include_apply_patch_tool: Option, @@ -1760,8 +1760,9 @@ impl Config { .or(cfg.model_instructions_file.as_ref()); let file_base_instructions = Self::try_read_non_empty_file(model_instructions_path, "model instructions file")?; - let base_instructions = base_instructions.or(file_base_instructions); - let developer_instructions = developer_instructions.or(cfg.developer_instructions); + let base_instructions = base_instructions.or_else(|| file_base_instructions.map(Some)); + let developer_instructions = + developer_instructions.unwrap_or_else(|| cfg.developer_instructions.clone()); let include_permissions_instructions = config_profile .include_permissions_instructions .or(cfg.include_permissions_instructions) diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 7978f37ec8..629730cbf2 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -905,7 +905,7 @@ model_instructions_file = "child.txt" .await?; assert_eq!( - config.base_instructions.as_deref(), + config.base_instructions.as_ref().and_then(Option::as_deref), Some("child instructions") ); @@ -941,7 +941,7 @@ async fn cli_override_model_instructions_file_sets_base_instructions() -> std::i .await?; assert_eq!( - config.base_instructions.as_deref(), + config.base_instructions.as_ref().and_then(Option::as_deref), Some("cli override instructions") ); diff --git a/codex-rs/core/src/guardian/review_session.rs b/codex-rs/core/src/guardian/review_session.rs index bc24974c82..368b812e56 100644 --- a/codex-rs/core/src/guardian/review_session.rs +++ b/codex-rs/core/src/guardian/review_session.rs @@ -137,7 +137,7 @@ impl GuardianReviewSessionReuseKey { model_reasoning_summary: spawn_config.model_reasoning_summary, permissions: spawn_config.permissions.clone(), developer_instructions: spawn_config.developer_instructions.clone(), - base_instructions: spawn_config.base_instructions.clone(), + base_instructions: spawn_config.base_instructions.clone().flatten(), user_instructions: spawn_config.user_instructions.clone(), compact_prompt: spawn_config.compact_prompt.clone(), cwd: spawn_config.cwd.to_path_buf(), diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs index 37cb0e9f48..0b8cdcdad5 100644 --- a/codex-rs/core/src/memories/phase1.rs +++ b/codex-rs/core/src/memories/phase1.rs @@ -336,9 +336,9 @@ mod job { }], tools: Vec::new(), parallel_tool_calls: false, - base_instructions: BaseInstructions { + base_instructions: Some(BaseInstructions { text: phase_one::PROMPT.to_string(), - }, + }), personality: None, output_schema: Some(output_schema()), }; diff --git a/codex-rs/core/src/session_startup_prewarm.rs b/codex-rs/core/src/session_startup_prewarm.rs index 397ffc949c..708401aedd 100644 --- a/codex-rs/core/src/session_startup_prewarm.rs +++ b/codex-rs/core/src/session_startup_prewarm.rs @@ -217,9 +217,9 @@ async fn schedule_startup_prewarm_inner( Vec::new(), startup_router.as_ref(), startup_turn_context.as_ref(), - BaseInstructions { + Some(BaseInstructions { text: base_instructions, - }, + }), ); let startup_turn_metadata_header = startup_turn_context .turn_metadata_state diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index a1cc071108..834cf20b4b 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -112,7 +112,7 @@ async fn start_review_conversation( let _ = sub_agent_config.features.disable(Feature::Collab); // Set explicit review rubric for the sub-agent - sub_agent_config.base_instructions = Some(crate::REVIEW_PROMPT.to_string()); + sub_agent_config.base_instructions = Some(Some(crate::REVIEW_PROMPT.to_string())); sub_agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); let model = config diff --git a/codex-rs/core/src/tools/handlers/agent_jobs.rs b/codex-rs/core/src/tools/handlers/agent_jobs.rs index fe30f3d750..837b654edc 100644 --- a/codex-rs/core/src/tools/handlers/agent_jobs.rs +++ b/codex-rs/core/src/tools/handlers/agent_jobs.rs @@ -535,7 +535,7 @@ async fn build_runner_options( let max_concurrency = normalize_concurrency(requested_concurrency, turn.config.agent_max_threads); let base_instructions = session.get_base_instructions().await; - let spawn_config = build_agent_spawn_config(&base_instructions, turn.as_ref())?; + let spawn_config = build_agent_spawn_config(base_instructions.as_ref(), turn.as_ref())?; Ok(JobRunnerOptions { max_concurrency, spawn_config, diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs index 8e4bfb5b59..a2482ea6a9 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -59,8 +59,10 @@ impl ToolHandler for Handler { .into(), ) .await; - let mut config = - build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; + let mut config = build_agent_spawn_config( + session.get_base_instructions().await.as_ref(), + turn.as_ref(), + )?; apply_requested_spawn_agent_model_overrides( &session, turn.as_ref(), diff --git a/codex-rs/core/src/tools/handlers/multi_agents_common.rs b/codex-rs/core/src/tools/handlers/multi_agents_common.rs index 2078c229b9..4205c4bb43 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_common.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_common.rs @@ -201,11 +201,12 @@ pub(crate) fn parse_collab_input( /// skipping this helper and cloning stale config state directly can send the child agent out with /// the wrong provider or runtime policy. pub(crate) fn build_agent_spawn_config( - base_instructions: &BaseInstructions, + base_instructions: Option<&BaseInstructions>, turn: &TurnContext, ) -> Result { let mut config = build_agent_shared_config(turn)?; - config.base_instructions = Some(base_instructions.text.clone()); + config.base_instructions = + Some(base_instructions.map(|base_instructions| base_instructions.text.clone())); Ok(config) } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index eab43f899c..03f4b0780b 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -3209,9 +3209,9 @@ async fn build_agent_spawn_config_uses_turn_context_values() { .set(AskForApproval::OnRequest) .expect("approval policy set"); - let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config"); + let config = build_agent_spawn_config(Some(&base_instructions), &turn).expect("spawn config"); let mut expected = (*turn.config).clone(); - expected.base_instructions = Some(base_instructions.text); + expected.base_instructions = Some(Some(base_instructions.text)); expected.model = Some(turn.model_info.slug.clone()); expected.model_provider = turn.provider.clone(); expected.model_reasoning_effort = turn.reasoning_effort; @@ -3247,7 +3247,7 @@ async fn build_agent_spawn_config_preserves_base_user_instructions() { text: "base".to_string(), }; - let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config"); + let config = build_agent_spawn_config(Some(&base_instructions), &turn).expect("spawn config"); assert_eq!(config.user_instructions, base_config.user_instructions); } @@ -3256,7 +3256,7 @@ async fn build_agent_spawn_config_preserves_base_user_instructions() { async fn build_agent_resume_config_clears_base_instructions() { let (_session, mut turn) = make_session_and_context().await; let mut base_config = (*turn.config).clone(); - base_config.base_instructions = Some("caller-base".to_string()); + base_config.base_instructions = Some(Some("caller-base".to_string())); turn.config = Arc::new(base_config); turn.approval_policy .set(AskForApproval::OnRequest) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index 77c48af9e6..a1cdb121d1 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -68,8 +68,10 @@ impl ToolHandler for Handler { .into(), ) .await; - let mut config = - build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; + let mut config = build_agent_spawn_config( + session.get_base_instructions().await.as_ref(), + turn.as_ref(), + )?; apply_requested_spawn_agent_model_overrides( &session, turn.as_ref(), diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 8e719460e5..cb97e4a3b3 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -921,7 +921,7 @@ async fn includes_base_instructions_override_in_request() { let mut builder = test_codex() .with_auth(CodexAuth::from_api_key("Test API Key")) .with_config(|config| { - config.base_instructions = Some("test instructions".to_string()); + config.base_instructions = Some(Some("test instructions".to_string())); }); let codex = builder .build(&server) @@ -953,6 +953,47 @@ async fn includes_base_instructions_override_in_request() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn omits_explicit_null_base_instructions_from_request() { + skip_if_no_network!(); + // Mock server + let server = MockServer::start().await; + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let mut builder = test_codex() + .with_auth(CodexAuth::from_api_key("Test API Key")) + .with_config(|config| { + config.base_instructions = Some(None); + }); + let codex = builder + .build(&server) + .await + .expect("create new conversation") + .codex; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request = resp_mock.single_request(); + let request_body = request.body_json(); + + assert_eq!(request_body.get("instructions"), None); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn chatgpt_auth_sends_correct_request() { skip_if_no_network!(); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index d348d4a022..0a1195a11b 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -1654,9 +1654,9 @@ fn prompt_with_input(input: Vec) -> Prompt { fn prompt_with_input_and_instructions(input: Vec, instructions: &str) -> Prompt { let mut prompt = prompt_with_input(input); - prompt.base_instructions = BaseInstructions { + prompt.base_instructions = Some(BaseInstructions { text: instructions.to_string(), - }; + }); prompt } diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 0069c5fb86..dd99e0f391 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -869,7 +869,7 @@ async fn remote_compact_trim_estimate_uses_session_base_instructions() -> Result let override_base_instructions = override_base_instructions.clone(); move |config| { config.model_context_window = Some(override_context_window); - config.base_instructions = Some(override_base_instructions); + config.base_instructions = Some(Some(override_base_instructions)); } }), ) diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 172738ffd1..8a0cbdcb63 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -66,7 +66,7 @@ async fn base_instructions_override_disables_personality_template() { .enable(Feature::Personality) .expect("test config should allow feature update"); config.personality = Some(Personality::Friendly); - config.base_instructions = Some("override instructions".to_string()); + config.base_instructions = Some(Some("override instructions".to_string())); let model_info = codex_core::test_support::construct_model_info_offline("gpt-5.2-codex", &config); diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index 7445a4ba05..93edd1621a 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -173,7 +173,7 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()> thread_id, /*forked_from_id*/ None, SessionSource::Exec, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs b/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs index 19d9d27cf7..c5aa57ce74 100644 --- a/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs +++ b/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs @@ -84,7 +84,7 @@ async fn continue_after_stream_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.base_instructions = Some("You are a helpful assistant".to_string()); + config.base_instructions = Some(Some("You are a helpful assistant".to_string())); config.model_provider = provider; }) .build(&server) diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index f83fd4fd5a..341f0ac4b2 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -179,8 +179,8 @@ impl CodexToolCallParam { codex_self_exe: arg0_paths.codex_self_exe.clone(), codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, + base_instructions: base_instructions.map(Some), + developer_instructions: developer_instructions.map(Some), compact_prompt, ..Default::default() }; diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index de580de6f3..e78bfe6e45 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -23,4 +23,5 @@ pub mod plan_tool; pub mod protocol; pub mod request_permissions; pub mod request_user_input; +mod serde_helpers; pub mod user_input; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 7116878b47..05926a9544 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -48,6 +48,8 @@ use crate::plan_tool::UpdatePlanArgs; use crate::request_permissions::RequestPermissionsEvent; use crate::request_permissions::RequestPermissionsResponse; use crate::request_user_input::RequestUserInputResponse; +use crate::serde_helpers::deserialize_double_option; +use crate::serde_helpers::serialize_double_option; use crate::user_input::UserInput; use codex_git_utils::GitSha; use codex_utils_absolute_path::AbsolutePathBuf; @@ -2332,7 +2334,7 @@ impl InitialHistory { } } - pub fn get_base_instructions(&self) -> Option { + pub fn get_base_instructions(&self) -> Option> { // TODO: SessionMeta should (in theory) always be first in the history, so we can probably only check the first item? match self { InitialHistory::New => None, @@ -2540,7 +2542,13 @@ pub struct SessionMeta { /// base_instructions for the session. This *should* always be present when creating a new session, /// but may be missing for older sessions. If not present, fall back to rendering the base_instructions /// from ModelsManager. - pub base_instructions: Option, + #[serde( + default, + deserialize_with = "deserialize_double_option", + serialize_with = "serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + pub base_instructions: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub dynamic_tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/codex-rs/protocol/src/serde_helpers.rs b/codex-rs/protocol/src/serde_helpers.rs new file mode 100644 index 0000000000..0e35ebdba7 --- /dev/null +++ b/codex-rs/protocol/src/serde_helpers.rs @@ -0,0 +1,23 @@ +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::Serializer; + +pub fn deserialize_double_option<'de, T, D>(deserializer: D) -> Result>, D::Error> +where + T: Deserialize<'de>, + D: Deserializer<'de>, +{ + serde_with::rust::double_option::deserialize(deserializer) +} + +pub fn serialize_double_option( + value: &Option>, + serializer: S, +) -> Result +where + T: Serialize, + S: Serializer, +{ + serde_with::rust::double_option::serialize(value, serializer) +} diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index f39c38af60..aa7b485b0c 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -81,7 +81,7 @@ pub enum RolloutRecorderParams { conversation_id: ThreadId, forked_from_id: Option, source: SessionSource, - base_instructions: BaseInstructions, + base_instructions: Option, dynamic_tools: Vec, event_persistence_mode: EventPersistenceMode, }, @@ -110,7 +110,7 @@ impl RolloutRecorderParams { conversation_id: ThreadId, forked_from_id: Option, source: SessionSource, - base_instructions: BaseInstructions, + base_instructions: Option, dynamic_tools: Vec, event_persistence_mode: EventPersistenceMode, ) -> Self { diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 163c8a1ee8..6ee55672e7 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -73,7 +73,7 @@ async fn recorder_materializes_only_after_explicit_persist() -> std::io::Result< thread_id, /*forked_from_id*/ None, SessionSource::Exec, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), @@ -166,7 +166,7 @@ async fn metadata_irrelevant_events_touch_state_db_updated_at() -> std::io::Resu thread_id, /*forked_from_id*/ None, SessionSource::Cli, - BaseInstructions::default(), + Some(BaseInstructions::default()), Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/rollout/src/tests.rs b/codex-rs/rollout/src/tests.rs index e647a54cd4..aeda089a25 100644 --- a/codex-rs/rollout/src/tests.rs +++ b/codex-rs/rollout/src/tests.rs @@ -977,7 +977,7 @@ async fn test_get_thread_contents() { } #[tokio::test] -async fn test_base_instructions_missing_in_meta_defaults_to_null() { +async fn test_base_instructions_missing_in_meta_stays_missing() { let temp = TempDir::new().unwrap(); let home = temp.path(); @@ -1011,10 +1011,7 @@ async fn test_base_instructions_missing_in_meta_defaults_to_null() { .await .expect("session meta head"); let first = head.first().expect("first head entry"); - assert_eq!( - first.get("base_instructions"), - Some(&serde_json::Value::Null) - ); + assert_eq!(first.get("base_instructions"), None); } #[tokio::test] From 90320fc51a760841d84acd1566f12bab57ddd092 Mon Sep 17 00:00:00 2001 From: Won Park Date: Mon, 6 Apr 2026 23:49:47 -0700 Subject: [PATCH 04/28] collapse dev message into one (#16988) collapse image-gen dev message into one --- codex-rs/core/src/codex_tests.rs | 11 +++-------- codex-rs/core/src/stream_events_utils.rs | 9 ++------- 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index b0437edbfe..0bfb0c3033 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -4089,18 +4089,13 @@ async fn handle_output_item_done_records_image_save_history_message() { let image_output_dir = image_output_path .parent() .expect("generated image path should have a parent"); - let save_message: ResponseItem = DeveloperInstructions::new(format!( - "Generated images are saved to {} as {} by default.", + let image_message: ResponseItem = DeveloperInstructions::new(format!( + "Generated images are saved to {} as {} by default.\nIf you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.", image_output_dir.display(), image_output_path.display(), )) .into(); - let copy_message: ResponseItem = DeveloperInstructions::new( - "If you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it." - .to_string(), - ) - .into(); - assert_eq!(history.raw_items(), &[save_message, copy_message, item]); + assert_eq!(history.raw_items(), &[image_message, item]); assert_eq!( std::fs::read(&expected_saved_path).expect("saved file"), b"foo" diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index 75eb1a8c22..ac4334d683 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -379,17 +379,12 @@ pub(crate) async fn handle_non_tool_response_item( .parent() .unwrap_or(turn_context.config.codex_home.as_path()); let message: ResponseItem = DeveloperInstructions::new(format!( - "Generated images are saved to {} as {} by default.", + "Generated images are saved to {} as {} by default.\nIf you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.", image_output_dir.display(), image_output_path.display(), )) .into(); - let copy_message: ResponseItem = DeveloperInstructions::new( - "If you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it." - .to_string(), - ) - .into(); - sess.record_conversation_items(turn_context, &[message, copy_message]) + sess.record_conversation_items(turn_context, &[message]) .await; } Err(err) => { From 741e2fdeb87e1d1ed2e70c73b33d70865d89a288 Mon Sep 17 00:00:00 2001 From: starr-openai Date: Tue, 7 Apr 2026 02:17:31 -0700 Subject: [PATCH 05/28] [codex] ez - rename env=>request in codex-rs/core/src/unified_exec/process_manager.rs (#16724) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- .../core/src/unified_exec/process_manager.rs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index affb72b69f..bc4ffe0d35 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -582,12 +582,12 @@ impl UnifiedExecProcessManager { pub(crate) async fn open_session_with_exec_env( &self, process_id: i32, - env: &ExecRequest, + request: &ExecRequest, tty: bool, mut spawn_lifecycle: SpawnLifecycleHandle, environment: &codex_exec_server::Environment, ) -> Result { - let (program, args) = env + let (program, args) = request .command .split_first() .ok_or(UnifiedExecError::MissingCommandLine)?; @@ -604,24 +604,24 @@ impl UnifiedExecProcessManager { .get_exec_backend() .start(codex_exec_server::ExecParams { process_id: exec_server_process_id(process_id).into(), - argv: env.command.clone(), - cwd: env.cwd.clone(), - env: env.env.clone(), + argv: request.command.clone(), + cwd: request.cwd.clone(), + env: request.env.clone(), tty, - arg0: env.arg0.clone(), + arg0: request.arg0.clone(), }) .await .map_err(|err| UnifiedExecError::create_process(err.to_string()))?; - return UnifiedExecProcess::from_remote_started(started, env.sandbox).await; + return UnifiedExecProcess::from_remote_started(started, request.sandbox).await; } let spawn_result = if tty { codex_utils_pty::pty::spawn_process_with_inherited_fds( program, args, - env.cwd.as_path(), - &env.env, - &env.arg0, + request.cwd.as_path(), + &request.env, + &request.arg0, codex_utils_pty::TerminalSize::default(), &inherited_fds, ) @@ -630,9 +630,9 @@ impl UnifiedExecProcessManager { codex_utils_pty::pipe::spawn_process_no_stdin_with_inherited_fds( program, args, - env.cwd.as_path(), - &env.env, - &env.arg0, + request.cwd.as_path(), + &request.env, + &request.arg0, &inherited_fds, ) .await @@ -640,7 +640,7 @@ impl UnifiedExecProcessManager { let spawned = spawn_result.map_err(|err| UnifiedExecError::create_process(err.to_string()))?; spawn_lifecycle.after_spawn(); - UnifiedExecProcess::from_spawned(spawned, env.sandbox, spawn_lifecycle).await + UnifiedExecProcess::from_spawned(spawned, request.sandbox, spawn_lifecycle).await } pub(super) async fn open_session_with_sandbox( From 51f75e2f567e2e25e057533fd5efcef57694f819 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 11:34:08 +0200 Subject: [PATCH 06/28] feat: empty role ok (#16999) --- codex-rs/core/src/agent/role.rs | 6 ++++++ codex-rs/core/src/agent/role_tests.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index 6570baa45a..83c2b1843b 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -64,6 +64,12 @@ async fn apply_role_to_config_inner( return Ok(()); }; let role_layer_toml = load_role_layer_toml(config, config_file, is_built_in, role_name).await?; + if role_layer_toml + .as_table() + .is_some_and(toml::map::Map::is_empty) + { + return Ok(()); + } let (preserve_current_profile, preserve_current_provider) = preservation_policy(config, &role_layer_toml); diff --git a/codex-rs/core/src/agent/role_tests.rs b/codex-rs/core/src/agent/role_tests.rs index 5b3941ebda..d68376ddd6 100644 --- a/codex-rs/core/src/agent/role_tests.rs +++ b/codex-rs/core/src/agent/role_tests.rs @@ -87,6 +87,22 @@ async fn apply_explorer_role_sets_model_and_adds_session_flags_layer() { assert_eq!(session_flags_layer_count(&config), before_layers + 1); } +#[tokio::test] +async fn apply_empty_explorer_role_preserves_current_model_and_reasoning_effort() { + let (_home, mut config) = test_config_with_cli_overrides(Vec::new()).await; + let before_layers = session_flags_layer_count(&config); + config.model = Some("gpt-5.4-mini".to_string()); + config.model_reasoning_effort = Some(ReasoningEffort::High); + + apply_role_to_config(&mut config, Some("explorer")) + .await + .expect("explorer role should apply"); + + assert_eq!(config.model.as_deref(), Some("gpt-5.4-mini")); + assert_eq!(config.model_reasoning_effort, Some(ReasoningEffort::High)); + assert_eq!(session_flags_layer_count(&config), before_layers); +} + #[tokio::test] async fn apply_role_returns_unavailable_for_missing_user_role_file() { let (_home, mut config) = test_config_with_cli_overrides(Vec::new()).await; From e2bb45bb249994312b4fa9c2e4e4836c574a3d07 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 11:42:19 +0200 Subject: [PATCH 07/28] chore: debug flag to hide some parameters (#17002) --- codex-rs/core/config.schema.json | 6 +++ codex-rs/features/src/lib.rs | 8 ++++ codex-rs/tools/src/agent_tool.rs | 37 +++++++++++++++---- codex-rs/tools/src/agent_tool_tests.rs | 2 + codex-rs/tools/src/tool_config.rs | 3 ++ codex-rs/tools/src/tool_registry_plan.rs | 2 + .../tools/src/tool_registry_plan_tests.rs | 1 + 7 files changed, 51 insertions(+), 8 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 8da02dc803..e4e7ff85b7 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -362,6 +362,9 @@ "connectors": { "type": "boolean" }, + "debug_hide_spawn_agent_metadata": { + "type": "boolean" + }, "default_mode_request_user_input": { "type": "boolean" }, @@ -2072,6 +2075,9 @@ "connectors": { "type": "boolean" }, + "debug_hide_spawn_agent_metadata": { + "type": "boolean" + }, "default_mode_request_user_input": { "type": "boolean" }, diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index f49e0edc05..23c23c9916 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -138,6 +138,8 @@ pub enum Feature { Collab, /// Enable task-path-based multi-agent routing. MultiAgentV2, + /// Hide spawn_agent agent/model override fields from the model-visible tool schema. + DebugHideSpawnAgentMetadata, /// Enable CSV-backed agent job tools. SpawnCsv, /// Enable apps. @@ -706,6 +708,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::DebugHideSpawnAgentMetadata, + key: "debug_hide_spawn_agent_metadata", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::SpawnCsv, key: "enable_fanout", diff --git a/codex-rs/tools/src/agent_tool.rs b/codex-rs/tools/src/agent_tool.rs index 017cc6e5ee..5180a31dff 100644 --- a/codex-rs/tools/src/agent_tool.rs +++ b/codex-rs/tools/src/agent_tool.rs @@ -10,6 +10,7 @@ use std::collections::BTreeMap; pub struct SpawnAgentToolOptions<'a> { pub available_models: &'a [ModelPreset], pub agent_type_description: String, + pub hide_agent_type_model_reasoning: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -20,15 +21,19 @@ pub struct WaitAgentTimeoutOptions { } pub fn create_spawn_agent_tool_v1(options: SpawnAgentToolOptions<'_>) -> ToolSpec { - let available_models_description = spawn_agent_models_description(options.available_models); + let available_models_description = (!options.hide_agent_type_model_reasoning) + .then(|| spawn_agent_models_description(options.available_models)); let return_value_description = "Returns the spawned agent id plus the user-facing nickname when available."; - let properties = spawn_agent_common_properties_v1(&options.agent_type_description); + let mut properties = spawn_agent_common_properties_v1(&options.agent_type_description); + if options.hide_agent_type_model_reasoning { + hide_spawn_agent_metadata_options(&mut properties); + } ToolSpec::Function(ResponsesApiTool { name: "spawn_agent".to_string(), description: spawn_agent_tool_description( - &available_models_description, + available_models_description.as_deref(), return_value_description, ), strict: false, @@ -43,9 +48,13 @@ pub fn create_spawn_agent_tool_v1(options: SpawnAgentToolOptions<'_>) -> ToolSpe } pub fn create_spawn_agent_tool_v2(options: SpawnAgentToolOptions<'_>) -> ToolSpec { - let available_models_description = spawn_agent_models_description(options.available_models); + let available_models_description = (!options.hide_agent_type_model_reasoning) + .then(|| spawn_agent_models_description(options.available_models)); let return_value_description = "Returns the canonical task name for the spawned agent, plus the user-facing nickname when available."; let mut properties = spawn_agent_common_properties_v2(&options.agent_type_description); + if options.hide_agent_type_model_reasoning { + hide_spawn_agent_metadata_options(&mut properties); + } properties.insert( "task_name".to_string(), JsonSchema::String { @@ -59,7 +68,7 @@ pub fn create_spawn_agent_tool_v2(options: SpawnAgentToolOptions<'_>) -> ToolSpe ToolSpec::Function(ResponsesApiTool { name: "spawn_agent".to_string(), description: spawn_agent_tool_description( - &available_models_description, + available_models_description.as_deref(), return_value_description, ), strict: false, @@ -637,18 +646,30 @@ fn spawn_agent_common_properties_v2(agent_type_description: &str) -> BTreeMap) { + properties.remove("agent_type"); + properties.remove("model"); + properties.remove("reasoning_effort"); +} + fn spawn_agent_tool_description( - available_models_description: &str, + available_models_description: Option<&str>, return_value_description: &str, ) -> String { + let agent_role_guidance = available_models_description + .map(|description| { + format!( + "Agent-role guidance below only helps choose which agent to use after spawning is already authorized; it never authorizes spawning by itself.\n{description}" + ) + }) + .unwrap_or_default(); format!( r#" Only use `spawn_agent` if and only if the user explicitly asks for sub-agents, delegation, or parallel agent work. Requests for depth, thoroughness, research, investigation, or detailed codebase analysis do not count as permission to spawn. - Agent-role guidance below only helps choose which agent to use after spawning is already authorized; it never authorizes spawning by itself. + {agent_role_guidance} Spawn a sub-agent for a well-scoped task. {return_value_description} This spawn_agent tool provides you access to smaller but more efficient sub-agents. A mini model can solve many tasks faster than the main model. You should follow the rules and guidelines below to use this tool. -{available_models_description} ### When to delegate vs. do the subtask yourself - First, quickly analyze the overall user task and form a succinct high-level plan. Identify which tasks are immediate blockers on the critical path, and which tasks are sidecar tasks that are needed but can run in parallel without blocking the next local step. As part of that plan, explicitly decide what immediate task you should do locally right now. Do this planning step before delegating to agents so you do not hand off the immediate blocking task to a submodel and then waste time waiting on it. - Use the smaller subagent when a subtask is easy enough for it to handle and can run in parallel with your local work. Prefer delegating concrete, bounded sidecar tasks that materially advance the main task without blocking your immediate next local step. diff --git a/codex-rs/tools/src/agent_tool_tests.rs b/codex-rs/tools/src/agent_tool_tests.rs index cd68fbd13a..550181d290 100644 --- a/codex-rs/tools/src/agent_tool_tests.rs +++ b/codex-rs/tools/src/agent_tool_tests.rs @@ -34,6 +34,7 @@ fn spawn_agent_tool_v2_requires_task_name_and_lists_visible_models() { model_preset("hidden", /*show_in_picker*/ false), ], agent_type_description: "role help".to_string(), + hide_agent_type_model_reasoning: false, }); let ToolSpec::Function(ResponsesApiTool { @@ -81,6 +82,7 @@ fn spawn_agent_tool_v1_keeps_legacy_fork_context_field() { let tool = create_spawn_agent_tool_v1(SpawnAgentToolOptions { available_models: &[], agent_type_description: "role help".to_string(), + hide_agent_type_model_reasoning: false, }); let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = tool else { diff --git a/codex-rs/tools/src/tool_config.rs b/codex-rs/tools/src/tool_config.rs index 6e9e0d1f57..3143976a5c 100644 --- a/codex-rs/tools/src/tool_config.rs +++ b/codex-rs/tools/src/tool_config.rs @@ -104,6 +104,7 @@ pub struct ToolsConfig { pub can_request_original_image_detail: bool, pub collab_tools: bool, pub multi_agent_v2: bool, + pub hide_spawn_agent_metadata: bool, pub request_user_input: bool, pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, @@ -141,6 +142,7 @@ impl ToolsConfig { include_js_repl && features.enabled(Feature::JsReplToolsOnly); let include_collab_tools = features.enabled(Feature::Collab); let include_multi_agent_v2 = features.enabled(Feature::MultiAgentV2); + let hide_spawn_agent_metadata = features.enabled(Feature::DebugHideSpawnAgentMetadata); let include_agent_jobs = features.enabled(Feature::SpawnCsv); let include_request_user_input = !matches!(session_source, SessionSource::SubAgent(_)); let include_default_mode_request_user_input = @@ -219,6 +221,7 @@ impl ToolsConfig { can_request_original_image_detail: include_original_image_detail, collab_tools: include_collab_tools, multi_agent_v2: include_multi_agent_v2, + hide_spawn_agent_metadata, request_user_input: include_request_user_input, default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs index 8985e2ee87..d63174c4c9 100644 --- a/codex-rs/tools/src/tool_registry_plan.rs +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -355,6 +355,7 @@ pub fn build_tool_registry_plan( create_spawn_agent_tool_v2(SpawnAgentToolOptions { available_models: &config.available_models, agent_type_description, + hide_agent_type_model_reasoning: config.hide_spawn_agent_metadata, }), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, @@ -397,6 +398,7 @@ pub fn build_tool_registry_plan( create_spawn_agent_tool_v1(SpawnAgentToolOptions { available_models: &config.available_models, agent_type_description, + hide_agent_type_model_reasoning: config.hide_spawn_agent_metadata, }), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index c73302d1be..36cbf42d43 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -1856,6 +1856,7 @@ fn spawn_agent_tool_options(config: &ToolsConfig) -> SpawnAgentToolOptions<'_> { SpawnAgentToolOptions { available_models: &config.available_models, agent_type_description: agent_type_description(config, DEFAULT_AGENT_TYPE_DESCRIPTION), + hide_agent_type_model_reasoning: config.hide_spawn_agent_metadata, } } From 2a8c3a2a527d1b3cb51365a72552bfa3aff32040 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 11:56:01 +0200 Subject: [PATCH 08/28] feat: drop agent ID from v2 (#17005) --- codex-rs/core/src/tools/handlers/multi_agents_tests.rs | 4 ++-- codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs | 2 -- codex-rs/tools/src/agent_tool.rs | 6 +----- codex-rs/tools/src/agent_tool_tests.rs | 2 +- codex-rs/tools/src/tool_registry_plan_tests.rs | 5 +---- 5 files changed, 5 insertions(+), 14 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 03f4b0780b..1e2fad9f09 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -1554,7 +1554,7 @@ async fn multi_agent_v2_interrupted_turn_does_not_notify_parent() { } #[tokio::test] -async fn multi_agent_v2_spawn_includes_agent_id_key_when_named() { +async fn multi_agent_v2_spawn_omits_agent_id_when_named() { let (mut session, mut turn) = make_session_and_context().await; let manager = thread_manager(); let root = manager @@ -1586,7 +1586,7 @@ async fn multi_agent_v2_spawn_includes_agent_id_key_when_named() { let result: serde_json::Value = serde_json::from_str(&content).expect("spawn_agent result should be json"); - assert_eq!(result["agent_id"], serde_json::Value::Null); + assert!(result.get("agent_id").is_none()); assert_eq!(result["task_name"], "/root/test_process"); assert!(result.get("nickname").is_some()); assert_eq!(success, Some(true)); diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index a1cdb121d1..e30b9b5806 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -209,7 +209,6 @@ impl ToolHandler for Handler { })?; Ok(SpawnAgentResult { - agent_id: None, task_name, nickname, }) @@ -269,7 +268,6 @@ impl SpawnAgentArgs { #[derive(Debug, Serialize)] pub(crate) struct SpawnAgentResult { - agent_id: Option, task_name: String, nickname: Option, } diff --git a/codex-rs/tools/src/agent_tool.rs b/codex-rs/tools/src/agent_tool.rs index 5180a31dff..317813eb71 100644 --- a/codex-rs/tools/src/agent_tool.rs +++ b/codex-rs/tools/src/agent_tool.rs @@ -375,10 +375,6 @@ fn spawn_agent_output_schema_v2() -> Value { json!({ "type": "object", "properties": { - "agent_id": { - "type": ["string", "null"], - "description": "Legacy thread identifier for the spawned agent." - }, "task_name": { "type": "string", "description": "Canonical task name for the spawned agent." @@ -388,7 +384,7 @@ fn spawn_agent_output_schema_v2() -> Value { "description": "User-facing nickname for the spawned agent when available." } }, - "required": ["agent_id", "task_name", "nickname"], + "required": ["task_name", "nickname"], "additionalProperties": false }) } diff --git a/codex-rs/tools/src/agent_tool_tests.rs b/codex-rs/tools/src/agent_tool_tests.rs index 550181d290..77ed3ded03 100644 --- a/codex-rs/tools/src/agent_tool_tests.rs +++ b/codex-rs/tools/src/agent_tool_tests.rs @@ -73,7 +73,7 @@ fn spawn_agent_tool_v2_requires_task_name_and_lists_visible_models() { ); assert_eq!( output_schema.expect("spawn_agent output schema")["required"], - json!(["agent_id", "task_name", "nickname"]) + json!(["task_name", "nickname"]) ); } diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index 36cbf42d43..3a6c52fb8a 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -243,10 +243,7 @@ fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() { let output_schema = output_schema .as_ref() .expect("spawn_agent should define output schema"); - assert_eq!( - output_schema["required"], - json!(["agent_id", "task_name", "nickname"]) - ); + assert_eq!(output_schema["required"], json!(["task_name", "nickname"])); let send_message = find_tool(&tools, "send_message"); let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &send_message.spec else { From 68e16baabe79a1f48c7d93c9a3d6e234a9b2c9b7 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 12:26:36 +0200 Subject: [PATCH 09/28] chore: send_message and followup_task do not return anything (#17008) --- .../src/tools/handlers/multi_agents_tests.rs | 6 ++-- .../handlers/multi_agents_v2/followup_task.rs | 4 +-- .../handlers/multi_agents_v2/message_tool.rs | 35 +++---------------- .../handlers/multi_agents_v2/send_message.rs | 4 +-- codex-rs/tools/src/agent_tool.rs | 4 +-- codex-rs/tools/src/agent_tool_tests.rs | 14 +++----- .../tools/src/tool_registry_plan_tests.rs | 16 +++++++-- 7 files changed, 33 insertions(+), 50 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 1e2fad9f09..923f7a6b7f 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -757,7 +757,7 @@ async fn multi_agent_v2_followup_task_rejects_root_target_from_child() { agent_role: None, }); - let err = FollowupTaskHandlerV2 + let Err(err) = FollowupTaskHandlerV2 .handle(invocation( Arc::new(session), Arc::new(turn), @@ -769,7 +769,9 @@ async fn multi_agent_v2_followup_task_rejects_root_target_from_child() { })), )) .await - .expect_err("followup_task should reject the root target"); + else { + panic!("followup_task should reject the root target"); + }; assert_eq!( err, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs index 312e17a316..e618f5da2b 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/followup_task.rs @@ -1,13 +1,13 @@ use super::message_tool::FollowupTaskArgs; use super::message_tool::MessageDeliveryMode; -use super::message_tool::MessageToolResult; use super::message_tool::handle_message_string_tool; use super::*; +use crate::tools::context::FunctionToolOutput; pub(crate) struct Handler; impl ToolHandler for Handler { - type Output = MessageToolResult; + type Output = FunctionToolOutput; fn kind(&self) -> ToolKind { ToolKind::Function diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs index 3123e93f4c..c9c2fda51e 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs @@ -4,6 +4,7 @@ //! resulting `InterAgentCommunication` should wake the target immediately. use super::*; +use crate::tools::context::FunctionToolOutput; use codex_protocol::protocol::InterAgentCommunication; #[derive(Clone, Copy, PartialEq, Eq)] @@ -46,30 +47,6 @@ pub(crate) struct FollowupTaskArgs { pub(crate) interrupt: bool, } -#[derive(Debug, Serialize)] -/// Tool result shared by the MultiAgentV2 message-delivery tools. -pub(crate) struct MessageToolResult { - submission_id: String, -} - -impl ToolOutput for MessageToolResult { - fn log_preview(&self) -> String { - tool_output_json_text(self, "multi_agent_message") - } - - fn success_for_logging(&self) -> bool { - true - } - - fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem { - tool_output_response_item(call_id, payload, self, Some(true), "multi_agent_message") - } - - fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue { - tool_output_code_mode_result(self, "multi_agent_message") - } -} - fn message_content(message: String) -> Result { if message.trim().is_empty() { return Err(FunctionCallError::RespondToModel( @@ -86,7 +63,7 @@ pub(crate) async fn handle_message_string_tool( target: String, message: String, interrupt: bool, -) -> Result { +) -> Result { handle_message_submission( invocation, mode, @@ -103,15 +80,13 @@ async fn handle_message_submission( target: String, prompt: String, interrupt: bool, -) -> Result { +) -> Result { let ToolInvocation { session, turn, - payload, call_id, .. } = invocation; - let _ = payload; let receiver_thread_id = resolve_agent_target(&session, &turn, &target).await?; let receiver_agent = session .services @@ -186,7 +161,7 @@ async fn handle_message_submission( .into(), ) .await; - let submission_id = result?; + result?; - Ok(MessageToolResult { submission_id }) + Ok(FunctionToolOutput::from_text(String::new(), Some(true))) } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs index a490d1100d..0d142623a9 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/send_message.rs @@ -1,13 +1,13 @@ use super::message_tool::MessageDeliveryMode; -use super::message_tool::MessageToolResult; use super::message_tool::SendMessageArgs; use super::message_tool::handle_message_string_tool; use super::*; +use crate::tools::context::FunctionToolOutput; pub(crate) struct Handler; impl ToolHandler for Handler { - type Output = MessageToolResult; + type Output = FunctionToolOutput; fn kind(&self) -> ToolKind { ToolKind::Function diff --git a/codex-rs/tools/src/agent_tool.rs b/codex-rs/tools/src/agent_tool.rs index 317813eb71..4a767dbc07 100644 --- a/codex-rs/tools/src/agent_tool.rs +++ b/codex-rs/tools/src/agent_tool.rs @@ -155,7 +155,7 @@ pub fn create_send_message_tool() -> ToolSpec { required: Some(vec!["target".to_string(), "message".to_string()]), additional_properties: Some(false.into()), }, - output_schema: Some(send_input_output_schema()), + output_schema: None, }) } @@ -197,7 +197,7 @@ pub fn create_followup_task_tool() -> ToolSpec { required: Some(vec!["target".to_string(), "message".to_string()]), additional_properties: Some(false.into()), }, - output_schema: Some(send_input_output_schema()), + output_schema: None, }) } diff --git a/codex-rs/tools/src/agent_tool_tests.rs b/codex-rs/tools/src/agent_tool_tests.rs index 77ed3ded03..fc1de7bc76 100644 --- a/codex-rs/tools/src/agent_tool_tests.rs +++ b/codex-rs/tools/src/agent_tool_tests.rs @@ -97,7 +97,7 @@ fn spawn_agent_tool_v1_keeps_legacy_fork_context_field() { } #[test] -fn send_message_tool_requires_message_and_uses_submission_output() { +fn send_message_tool_requires_message_and_has_no_output_schema() { let ToolSpec::Function(ResponsesApiTool { parameters, output_schema, @@ -122,14 +122,11 @@ fn send_message_tool_requires_message_and_uses_submission_output() { required, Some(vec!["target".to_string(), "message".to_string()]) ); - assert_eq!( - output_schema.expect("send_message output schema")["required"], - json!(["submission_id"]) - ); + assert_eq!(output_schema, None); } #[test] -fn followup_task_tool_requires_message_and_uses_submission_output() { +fn followup_task_tool_requires_message_and_has_no_output_schema() { let ToolSpec::Function(ResponsesApiTool { parameters, output_schema, @@ -154,10 +151,7 @@ fn followup_task_tool_requires_message_and_uses_submission_output() { required, Some(vec!["target".to_string(), "message".to_string()]) ); - assert_eq!( - output_schema.expect("followup_task output schema")["required"], - json!(["submission_id"]) - ); + assert_eq!(output_schema, None); } #[test] diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index 3a6c52fb8a..9e5fac1fcc 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -246,9 +246,15 @@ fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() { assert_eq!(output_schema["required"], json!(["task_name", "nickname"])); let send_message = find_tool(&tools, "send_message"); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &send_message.spec else { + let ToolSpec::Function(ResponsesApiTool { + parameters, + output_schema, + .. + }) = &send_message.spec + else { panic!("send_message should be a function tool"); }; + assert_eq!(output_schema, &None); let JsonSchema::Object { properties, required, @@ -267,9 +273,15 @@ fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() { ); let followup_task = find_tool(&tools, "followup_task"); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &followup_task.spec else { + let ToolSpec::Function(ResponsesApiTool { + parameters, + output_schema, + .. + }) = &followup_task.spec + else { panic!("followup_task should be a function tool"); }; + assert_eq!(output_schema, &None); let JsonSchema::Object { properties, required, From 99f167e6bfa1fd34257a83b5db2ce19b56792ddb Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 12:31:13 +0200 Subject: [PATCH 10/28] chore: hide nickname for debug flag (#17007) --- .../tools/handlers/multi_agents_v2/spawn.rs | 29 ++++++++++++++----- codex-rs/tools/src/agent_tool.rs | 26 +++++++++++++++-- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index e30b9b5806..0d460b1a04 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -5,6 +5,7 @@ use crate::agent::control::render_input_preview; use crate::agent::next_thread_spawn_depth; use crate::agent::role::DEFAULT_ROLE_NAME; use crate::agent::role::apply_role_to_config; +use codex_features::Feature; use codex_protocol::AgentPath; use codex_protocol::models::DeveloperInstructions; use codex_protocol::protocol::InterAgentCommunication; @@ -208,10 +209,18 @@ impl ToolHandler for Handler { ) })?; - Ok(SpawnAgentResult { - task_name, - nickname, - }) + let hide_agent_metadata = turn + .config + .features + .enabled(Feature::DebugHideSpawnAgentMetadata); + if hide_agent_metadata { + Ok(SpawnAgentResult::HiddenMetadata { task_name }) + } else { + Ok(SpawnAgentResult::WithNickname { + task_name, + nickname, + }) + } } } @@ -267,9 +276,15 @@ impl SpawnAgentArgs { } #[derive(Debug, Serialize)] -pub(crate) struct SpawnAgentResult { - task_name: String, - nickname: Option, +#[serde(untagged)] +pub(crate) enum SpawnAgentResult { + WithNickname { + task_name: String, + nickname: Option, + }, + HiddenMetadata { + task_name: String, + }, } impl ToolOutput for SpawnAgentResult { diff --git a/codex-rs/tools/src/agent_tool.rs b/codex-rs/tools/src/agent_tool.rs index 4a767dbc07..1a1eeb19dc 100644 --- a/codex-rs/tools/src/agent_tool.rs +++ b/codex-rs/tools/src/agent_tool.rs @@ -50,7 +50,11 @@ pub fn create_spawn_agent_tool_v1(options: SpawnAgentToolOptions<'_>) -> ToolSpe pub fn create_spawn_agent_tool_v2(options: SpawnAgentToolOptions<'_>) -> ToolSpec { let available_models_description = (!options.hide_agent_type_model_reasoning) .then(|| spawn_agent_models_description(options.available_models)); - let return_value_description = "Returns the canonical task name for the spawned agent, plus the user-facing nickname when available."; + let return_value_description = if options.hide_agent_type_model_reasoning { + "Returns the canonical task name for the spawned agent." + } else { + "Returns the canonical task name for the spawned agent, plus the user-facing nickname when available." + }; let mut properties = spawn_agent_common_properties_v2(&options.agent_type_description); if options.hide_agent_type_model_reasoning { hide_spawn_agent_metadata_options(&mut properties); @@ -78,7 +82,9 @@ pub fn create_spawn_agent_tool_v2(options: SpawnAgentToolOptions<'_>) -> ToolSpe required: Some(vec!["task_name".to_string(), "message".to_string()]), additional_properties: Some(false.into()), }, - output_schema: Some(spawn_agent_output_schema_v2()), + output_schema: Some(spawn_agent_output_schema_v2( + options.hide_agent_type_model_reasoning, + )), }) } @@ -371,7 +377,21 @@ fn spawn_agent_output_schema_v1() -> Value { }) } -fn spawn_agent_output_schema_v2() -> Value { +fn spawn_agent_output_schema_v2(hide_agent_metadata: bool) -> Value { + if hide_agent_metadata { + return json!({ + "type": "object", + "properties": { + "task_name": { + "type": "string", + "description": "Canonical task name for the spawned agent." + } + }, + "required": ["task_name"], + "additionalProperties": false + }); + } + json!({ "type": "object", "properties": { From 89f1a44afab5fa1f2cee9b12f7d9bec444e2d8b0 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 13:47:37 +0200 Subject: [PATCH 11/28] feat: /feedback cascade (#16442) Example here: https://openai.sentry.io/issues/7380240430/?project=4510195390611458&query=019d498f-bec4-7ba2-96d2-612b1e4507df&referrer=issue-stream --- .../app-server/src/codex_message_processor.rs | 129 ++++++++++++++---- codex-rs/core/src/agent/control.rs | 9 ++ codex-rs/core/src/agent/control_tests.rs | 126 +++++++++++++++++ codex-rs/core/src/thread_manager.rs | 49 +++++++ 4 files changed, 285 insertions(+), 28 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 91641898d1..6b917d6990 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -7672,42 +7672,101 @@ impl CodexMessageProcessor { } let snapshot = self.feedback.snapshot(conversation_id); let thread_id = snapshot.thread_id.clone(); - let sqlite_feedback_logs = if include_logs { + let (feedback_thread_ids, sqlite_feedback_logs, state_db_ctx) = if include_logs { if let Some(log_db) = self.log_db.as_ref() { log_db.flush().await; } let state_db_ctx = get_state_db(&self.config).await; - match (state_db_ctx.as_ref(), conversation_id) { - (Some(state_db_ctx), Some(conversation_id)) => { - let thread_id_text = conversation_id.to_string(); - match state_db_ctx.query_feedback_logs(&thread_id_text).await { - Ok(logs) if logs.is_empty() => None, - Ok(logs) => Some(logs), - Err(err) => { - warn!( - "failed to query feedback logs from sqlite for thread_id={thread_id_text}: {err}" - ); - None + let feedback_thread_ids = match conversation_id { + Some(conversation_id) => match self + .thread_manager + .list_agent_subtree_thread_ids(conversation_id) + .await + { + Ok(thread_ids) => thread_ids, + Err(err) => { + warn!( + "failed to list feedback subtree for thread_id={conversation_id}: {err}" + ); + let mut thread_ids = vec![conversation_id]; + if let Some(state_db_ctx) = state_db_ctx.as_ref() { + for status in [ + codex_state::DirectionalThreadSpawnEdgeStatus::Open, + codex_state::DirectionalThreadSpawnEdgeStatus::Closed, + ] { + match state_db_ctx + .list_thread_spawn_descendants_with_status( + conversation_id, + status, + ) + .await + { + Ok(descendant_ids) => thread_ids.extend(descendant_ids), + Err(err) => warn!( + "failed to list persisted feedback subtree for thread_id={conversation_id}: {err}" + ), + } + } } + thread_ids + } + }, + None => Vec::new(), + }; + let sqlite_feedback_logs = if let Some(state_db_ctx) = state_db_ctx.as_ref() + && !feedback_thread_ids.is_empty() + { + let thread_id_texts = feedback_thread_ids + .iter() + .map(ToString::to_string) + .collect::>(); + let thread_id_refs = thread_id_texts + .iter() + .map(String::as_str) + .collect::>(); + match state_db_ctx + .query_feedback_logs_for_threads(&thread_id_refs) + .await + { + Ok(logs) if logs.is_empty() => None, + Ok(logs) => Some(logs), + Err(err) => { + let thread_ids = thread_id_texts.join(", "); + warn!( + "failed to query feedback logs from sqlite for thread_ids=[{thread_ids}]: {err}" + ); + None } } - _ => None, - } + } else { + None + }; + (feedback_thread_ids, sqlite_feedback_logs, state_db_ctx) } else { - None + (Vec::new(), None, None) }; - let validated_rollout_path = if include_logs { - match conversation_id { - Some(conv_id) => self.resolve_rollout_path(conv_id).await, - None => None, + let mut attachment_paths = Vec::new(); + let mut seen_attachment_paths = HashSet::new(); + if include_logs { + for feedback_thread_id in &feedback_thread_ids { + let Some(rollout_path) = self + .resolve_rollout_path(*feedback_thread_id, state_db_ctx.as_ref()) + .await + else { + continue; + }; + if seen_attachment_paths.insert(rollout_path.clone()) { + attachment_paths.push(rollout_path); + } } - } else { - None - }; - let mut attachment_paths = validated_rollout_path.into_iter().collect::>(); + } if let Some(extra_log_files) = extra_log_files { - attachment_paths.extend(extra_log_files); + for extra_log_file in extra_log_files { + if seen_attachment_paths.insert(extra_log_file.clone()) { + attachment_paths.push(extra_log_file); + } + } } let session_source = self.thread_manager.session_source(); @@ -7826,11 +7885,25 @@ impl CodexMessageProcessor { }); } - async fn resolve_rollout_path(&self, conversation_id: ThreadId) -> Option { - match self.thread_manager.get_thread(conversation_id).await { - Ok(conv) => conv.rollout_path(), - Err(_) => None, + async fn resolve_rollout_path( + &self, + conversation_id: ThreadId, + state_db_ctx: Option<&StateDbHandle>, + ) -> Option { + if let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await + && let Some(rollout_path) = conversation.rollout_path() + { + return Some(rollout_path); } + + let state_db_ctx = state_db_ctx?; + state_db_ctx + .find_rollout_path_by_id(conversation_id, /*archived_only*/ None) + .await + .unwrap_or_else(|err| { + warn!("failed to resolve rollout path for thread_id={conversation_id}: {err}"); + None + }) } } diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 255c6bc2c3..529615a7a5 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -730,6 +730,15 @@ impl AgentControl { self.state.agent_metadata_for_thread(agent_id) } + pub(crate) async fn list_live_agent_subtree_thread_ids( + &self, + agent_id: ThreadId, + ) -> CodexResult> { + let mut thread_ids = vec![agent_id]; + thread_ids.extend(self.live_thread_spawn_descendants(agent_id).await?); + Ok(thread_ids) + } + pub(crate) async fn get_agent_config_snapshot( &self, agent_id: ThreadId, diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index a64a11bf98..54693228fa 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -1687,6 +1687,132 @@ async fn resume_agent_from_rollout_reads_archived_rollout_path() { .expect("resumed child shutdown should succeed"); } +#[tokio::test] +async fn list_agent_subtree_thread_ids_includes_anonymous_and_closed_descendants() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, _parent_thread) = harness.start_thread().await; + let worker_path = AgentPath::root().join("worker").expect("worker path"); + let reviewer_path = AgentPath::root().join("reviewer").expect("reviewer path"); + + let worker_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello worker"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_path: Some(worker_path.clone()), + agent_nickname: None, + agent_role: Some("worker".to_string()), + })), + ) + .await + .expect("worker spawn should succeed"); + let worker_child_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello worker child"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: worker_thread_id, + depth: 2, + agent_path: Some( + worker_path + .join("child") + .expect("worker child path should be valid"), + ), + agent_nickname: None, + agent_role: Some("worker".to_string()), + })), + ) + .await + .expect("worker child spawn should succeed"); + let no_path_child_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello anonymous child"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: worker_thread_id, + depth: 2, + agent_path: None, + agent_nickname: None, + agent_role: Some("worker".to_string()), + })), + ) + .await + .expect("no-path child spawn should succeed"); + let no_path_grandchild_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello anonymous grandchild"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: no_path_child_thread_id, + depth: 3, + agent_path: None, + agent_nickname: None, + agent_role: Some("worker".to_string()), + })), + ) + .await + .expect("no-path grandchild spawn should succeed"); + let _reviewer_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello reviewer"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_path: Some(reviewer_path), + agent_nickname: None, + agent_role: Some("reviewer".to_string()), + })), + ) + .await + .expect("reviewer spawn should succeed"); + + let _ = harness + .control + .shutdown_live_agent(no_path_grandchild_thread_id) + .await + .expect("no-path grandchild shutdown should succeed"); + + let mut worker_subtree_thread_ids = harness + .manager + .list_agent_subtree_thread_ids(worker_thread_id) + .await + .expect("worker subtree thread ids should load"); + worker_subtree_thread_ids.sort_by_key(ToString::to_string); + let mut expected_worker_subtree_thread_ids = vec![ + worker_thread_id, + worker_child_thread_id, + no_path_child_thread_id, + no_path_grandchild_thread_id, + ]; + expected_worker_subtree_thread_ids.sort_by_key(ToString::to_string); + assert_eq!( + worker_subtree_thread_ids, + expected_worker_subtree_thread_ids + ); + + let mut no_path_child_subtree_thread_ids = harness + .manager + .list_agent_subtree_thread_ids(no_path_child_thread_id) + .await + .expect("no-path subtree thread ids should load"); + no_path_child_subtree_thread_ids.sort_by_key(ToString::to_string); + let mut expected_no_path_child_subtree_thread_ids = + vec![no_path_child_thread_id, no_path_grandchild_thread_id]; + expected_no_path_child_subtree_thread_ids.sort_by_key(ToString::to_string); + assert_eq!( + no_path_child_subtree_thread_ids, + expected_no_path_child_subtree_thread_ids + ); +} + #[tokio::test] async fn shutdown_agent_tree_closes_live_descendants() { let harness = AgentControlHarness::new().await; diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 6d93a1a329..2dd4ad5532 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -43,9 +43,11 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::W3cTraceContext; +use codex_state::DirectionalThreadSpawnEdgeStatus; use futures::StreamExt; use futures::stream::FuturesUnordered; use std::collections::HashMap; +use std::collections::HashSet; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -401,6 +403,53 @@ impl ThreadManager { self.state.get_thread(thread_id).await } + /// List `thread_id` plus all known descendants in its spawn subtree. + pub async fn list_agent_subtree_thread_ids( + &self, + thread_id: ThreadId, + ) -> CodexResult> { + let thread = self.state.get_thread(thread_id).await?; + + let mut subtree_thread_ids = Vec::new(); + let mut seen_thread_ids = HashSet::new(); + subtree_thread_ids.push(thread_id); + seen_thread_ids.insert(thread_id); + + if let Some(state_db_ctx) = thread.state_db() { + for status in [ + DirectionalThreadSpawnEdgeStatus::Open, + DirectionalThreadSpawnEdgeStatus::Closed, + ] { + for descendant_id in state_db_ctx + .list_thread_spawn_descendants_with_status(thread_id, status) + .await + .map_err(|err| { + CodexErr::Fatal(format!("failed to load thread-spawn descendants: {err}")) + })? + { + if seen_thread_ids.insert(descendant_id) { + subtree_thread_ids.push(descendant_id); + } + } + } + } + + for descendant_id in thread + .codex + .session + .services + .agent_control + .list_live_agent_subtree_thread_ids(thread_id) + .await? + { + if seen_thread_ids.insert(descendant_id) { + subtree_thread_ids.push(descendant_id); + } + } + + Ok(subtree_thread_ids) + } + pub async fn start_thread(&self, config: Config) -> CodexResult { // Box delegated thread-spawn futures so these convenience wrappers do // not inline the full spawn path into every caller's async state. From 413c1e1fdf60d3fe418e101eb53d20fee33ae0e6 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 7 Apr 2026 08:03:35 -0700 Subject: [PATCH 12/28] [codex] reduce module visibility (#16978) ## Summary - reduce public module visibility across Rust crates, preferring private or crate-private modules with explicit crate-root public exports - update external call sites and tests to use the intended public crate APIs instead of reaching through module trees - add the module visibility guideline to AGENTS.md ## Validation - `cargo check --workspace --all-targets --message-format=short` passed before the final fix/format pass - `just fix` completed successfully - `just fmt` completed successfully - `git diff --check` passed --- AGENTS.md | 1 + .../app-server/src/codex_message_processor.rs | 14 ++-- .../plugin_mcp_oauth.rs | 8 +- codex-rs/backend-client/src/client.rs | 5 +- codex-rs/backend-client/src/lib.rs | 2 +- codex-rs/backend-client/src/types.rs | 1 - codex-rs/cli/src/lib.rs | 15 +++- codex-rs/cli/src/main.rs | 22 ++--- codex-rs/cli/src/mcp_cmd.rs | 18 ++--- codex-rs/cli/src/wsl_paths.rs | 2 +- codex-rs/cloud-requirements/src/lib.rs | 2 +- codex-rs/cloud-tasks/src/lib.rs | 16 ++-- codex-rs/cloud-tasks/src/scrollable_diff.rs | 4 +- codex-rs/codex-api/src/endpoint/mod.rs | 27 +++++-- .../endpoint/realtime_websocket/methods.rs | 2 +- .../src/endpoint/realtime_websocket/mod.rs | 6 +- .../endpoint/realtime_websocket/protocol.rs | 1 - codex-rs/codex-api/src/endpoint/responses.rs | 4 +- .../src/endpoint/responses_websocket.rs | 4 +- codex-rs/codex-api/src/lib.rs | 54 ++++++++----- codex-rs/codex-api/src/requests/mod.rs | 5 +- codex-rs/codex-api/src/sse/mod.rs | 5 +- codex-rs/codex-api/tests/clients.rs | 4 +- .../codex-api/tests/models_integration.rs | 4 +- .../codex-api/tests/realtime_websocket_e2e.rs | 4 +- codex-rs/codex-api/tests/sse_end_to_end.rs | 4 +- .../src/models/mod.rs | 24 +++--- codex-rs/codex-mcp/src/lib.rs | 42 +++++++++- codex-rs/codex-mcp/src/mcp/mod.rs | 17 +++- .../codex-mcp/src/mcp_connection_manager.rs | 4 +- .../config/src/requirements_exec_policy.rs | 8 +- codex-rs/core/src/agent/registry.rs | 2 +- codex-rs/core/src/apps/render.rs | 2 +- codex-rs/core/src/client.rs | 12 +-- codex-rs/core/src/client_common.rs | 2 +- codex-rs/core/src/client_common_tests.rs | 4 +- codex-rs/core/src/client_tests.rs | 2 +- codex-rs/core/src/codex.rs | 32 +++----- codex-rs/core/src/codex_tests.rs | 4 +- codex-rs/core/src/config/mod.rs | 4 +- codex-rs/core/src/connectors.rs | 16 ++-- codex-rs/core/src/connectors_tests.rs | 4 +- codex-rs/core/src/exec.rs | 2 +- codex-rs/core/src/external_agent_config.rs | 2 +- codex-rs/core/src/instructions/mod.rs | 1 - codex-rs/core/src/lib.rs | 81 ++++++++++++------- codex-rs/core/src/mcp.rs | 8 +- codex-rs/core/src/mcp_skill_dependencies.rs | 8 +- codex-rs/core/src/mcp_tool_call.rs | 2 +- codex-rs/core/src/otel_init.rs | 8 +- codex-rs/core/src/plugins/injection.rs | 4 +- codex-rs/core/src/plugins/startup_sync.rs | 6 +- codex-rs/core/src/realtime_conversation.rs | 6 +- codex-rs/core/src/rollout.rs | 33 +++++--- codex-rs/core/src/session_startup_prewarm.rs | 4 +- codex-rs/core/src/state/service.rs | 2 +- codex-rs/core/src/state_db_bridge.rs | 13 --- codex-rs/core/src/tasks/mod.rs | 8 +- codex-rs/core/src/tasks/mod_tests.rs | 6 +- codex-rs/core/src/tools/handlers/mod.rs | 2 +- .../core/src/tools/handlers/multi_agents.rs | 2 +- .../core/src/tools/handlers/tool_search.rs | 2 +- .../core/src/tools/handlers/tool_suggest.rs | 2 +- .../core/src/tools/handlers/unified_exec.rs | 2 +- codex-rs/core/src/tools/mod.rs | 22 ++--- codex-rs/core/src/tools/router.rs | 2 +- codex-rs/core/src/tools/runtimes/mod.rs | 6 +- codex-rs/core/src/tools/spec.rs | 4 +- codex-rs/core/src/tools/spec_tests.rs | 2 +- codex-rs/core/src/turn_timing.rs | 4 +- codex-rs/core/src/windows_sandbox.rs | 4 +- .../core/tests/suite/client_websockets.rs | 4 +- codex-rs/core/tests/suite/pending_input.rs | 15 +++- codex-rs/exec/src/lib.rs | 42 +++++++++- .../tests/event_processor_with_json_output.rs | 72 ++++++++--------- codex-rs/exec/tests/suite/sandbox.rs | 2 +- codex-rs/execpolicy/src/amend.rs | 1 - codex-rs/execpolicy/src/lib.rs | 17 ++-- codex-rs/execpolicy/src/main.rs | 2 +- codex-rs/execpolicy/src/parser.rs | 1 - codex-rs/execpolicy/tests/basic.rs | 6 +- codex-rs/feedback/src/lib.rs | 9 ++- codex-rs/hooks/src/lib.rs | 2 +- codex-rs/login/src/api_bridge.rs | 2 +- codex-rs/login/src/lib.rs | 1 + codex-rs/model-provider-info/src/lib.rs | 2 +- codex-rs/models-manager/src/lib.rs | 4 +- codex-rs/models-manager/src/manager.rs | 2 +- codex-rs/otel/src/events/session_telemetry.rs | 36 ++++----- codex-rs/otel/src/lib.rs | 14 ++-- codex-rs/otel/src/metrics/mod.rs | 6 +- codex-rs/otel/tests/harness/mod.rs | 6 +- codex-rs/otel/tests/suite/manager_metrics.rs | 2 +- .../otel/tests/suite/otlp_http_loopback.rs | 12 +-- codex-rs/otel/tests/suite/runtime_summary.rs | 6 +- codex-rs/otel/tests/suite/send.rs | 2 +- codex-rs/otel/tests/suite/snapshot.rs | 6 +- codex-rs/otel/tests/suite/timing.rs | 2 +- codex-rs/otel/tests/suite/validation.rs | 8 +- codex-rs/protocol/src/models.rs | 2 +- codex-rs/response-debug-context/src/lib.rs | 4 +- codex-rs/rollout/src/lib.rs | 26 ++++-- codex-rs/rollout/src/metadata.rs | 2 +- .../shell-command/src/command_safety/mod.rs | 2 +- codex-rs/shell-command/src/lib.rs | 2 +- codex-rs/shell-escalation/src/lib.rs | 4 +- codex-rs/shell-escalation/src/unix/mod.rs | 15 ++-- codex-rs/tui/src/app.rs | 10 +-- codex-rs/tui/src/app_server_session.rs | 10 ++- codex-rs/tui/src/bottom_pane/feedback_view.rs | 6 +- codex-rs/tui/src/bottom_pane/mod.rs | 4 +- codex-rs/tui/src/chatwidget.rs | 2 +- codex-rs/tui/src/chatwidget/skills.rs | 2 +- .../chatwidget/tests/popups_and_settings.rs | 24 +++--- codex-rs/tui/src/history_cell.rs | 10 +-- codex-rs/tui/src/lib.rs | 18 +++-- codex-rs/tui/src/mention_codec.rs | 4 +- codex-rs/tui/src/onboarding/mod.rs | 3 +- codex-rs/tui/src/public_widgets/mod.rs | 2 +- codex-rs/tui/src/render/mod.rs | 6 +- codex-rs/tui/src/status/helpers.rs | 2 +- codex-rs/tui/tests/suite/vt100_history.rs | 8 +- codex-rs/tui/tests/suite/vt100_live_commit.rs | 6 +- codex-rs/utils/cli/src/lib.rs | 3 +- codex-rs/utils/image/src/lib.rs | 5 +- codex-rs/utils/path-utils/src/lib.rs | 4 +- codex-rs/utils/pty/src/win/mod.rs | 2 +- .../src/elevated/command_runner_win.rs | 32 ++++---- codex-rs/windows-sandbox-rs/src/lib.rs | 26 +++++- 129 files changed, 695 insertions(+), 496 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c8d989fe9d..297fb0fe15 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ In the codex-rs folder where the rust code lives: - Newly added traits should include doc comments that explain their role and how implementations are expected to use them. - When writing tests, prefer comparing the equality of entire objects over fields one by one. - When making a change that adds or changes an API, ensure that the documentation in the `docs/` folder is up to date if applicable. +- Prefer private modules and explicitly exported public crate API. - If you change `ConfigToml` or nested config types, run `just write-config-schema` to update `codex-rs/core/config.schema.json`. - If you change Rust dependencies (`Cargo.toml` or `Cargo.lock`), run `just bazel-lock-update` from the repo root to refresh `MODULE.bazel.lock`, and include that lockfile update in the same change. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 6b917d6990..9282720828 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -248,12 +248,12 @@ use codex_login::default_client::set_default_client_residency_requirement; use codex_login::login_with_api_key; use codex_login::request_device_code; use codex_login::run_login_server; -use codex_mcp::mcp::McpSnapshotDetail; -use codex_mcp::mcp::auth::discover_supported_scopes; -use codex_mcp::mcp::auth::resolve_oauth_scopes; -use codex_mcp::mcp::collect_mcp_snapshot_with_detail; -use codex_mcp::mcp::effective_mcp_servers; -use codex_mcp::mcp::qualified_mcp_tool_name_prefix; +use codex_mcp::McpSnapshotDetail; +use codex_mcp::collect_mcp_snapshot_with_detail; +use codex_mcp::discover_supported_scopes; +use codex_mcp::effective_mcp_servers; +use codex_mcp::qualified_mcp_tool_name_prefix; +use codex_mcp::resolve_oauth_scopes; use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationMode; @@ -5175,7 +5175,7 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ListMcpServerStatusParams, config: Config, - mcp_config: codex_mcp::mcp::McpConfig, + mcp_config: codex_mcp::McpConfig, auth: Option, ) { let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) { diff --git a/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs b/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs index 58f4a5e8dd..b027aef453 100644 --- a/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs +++ b/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs @@ -5,10 +5,10 @@ use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; use codex_app_server_protocol::ServerNotification; use codex_config::types::McpServerConfig; use codex_core::config::Config; -use codex_mcp::mcp::auth::McpOAuthLoginSupport; -use codex_mcp::mcp::auth::oauth_login_support; -use codex_mcp::mcp::auth::resolve_oauth_scopes; -use codex_mcp::mcp::auth::should_retry_without_scopes; +use codex_mcp::McpOAuthLoginSupport; +use codex_mcp::oauth_login_support; +use codex_mcp::resolve_oauth_scopes; +use codex_mcp::should_retry_without_scopes; use codex_rmcp_client::perform_oauth_login_silent; use tracing::warn; diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index 3d5beb9d15..6049c1697b 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -503,6 +503,7 @@ impl Client { #[cfg(test)] mod tests { use super::*; + use codex_backend_openapi_models::models::AdditionalRateLimitDetails; use pretty_assertions::assert_eq; #[test] @@ -536,7 +537,7 @@ mod tests { }))), ..Default::default() }))), - additional_rate_limits: Some(Some(vec![crate::types::AdditionalRateLimitDetails { + additional_rate_limits: Some(Some(vec![AdditionalRateLimitDetails { limit_name: "codex_other".to_string(), metered_feature: "codex_other".to_string(), rate_limit: Some(Some(Box::new(crate::types::RateLimitStatusDetails { @@ -596,7 +597,7 @@ mod tests { let payload = RateLimitStatusPayload { plan_type: crate::types::PlanType::Plus, rate_limit: None, - additional_rate_limits: Some(Some(vec![crate::types::AdditionalRateLimitDetails { + additional_rate_limits: Some(Some(vec![AdditionalRateLimitDetails { limit_name: "codex_other".to_string(), metered_feature: "codex_other".to_string(), rate_limit: None, diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs index a3b2f37608..397c2a2cd4 100644 --- a/codex-rs/backend-client/src/lib.rs +++ b/codex-rs/backend-client/src/lib.rs @@ -1,5 +1,5 @@ mod client; -pub mod types; +pub(crate) mod types; pub use client::Client; pub use client::RequestError; diff --git a/codex-rs/backend-client/src/types.rs b/codex-rs/backend-client/src/types.rs index 4ef0fb8462..22e0984cda 100644 --- a/codex-rs/backend-client/src/types.rs +++ b/codex-rs/backend-client/src/types.rs @@ -1,4 +1,3 @@ -pub use codex_backend_openapi_models::models::AdditionalRateLimitDetails; pub use codex_backend_openapi_models::models::ConfigFileResponse; pub use codex_backend_openapi_models::models::CreditStatusDetails; pub use codex_backend_openapi_models::models::PaginatedListTaskListItem; diff --git a/codex-rs/cli/src/lib.rs b/codex-rs/cli/src/lib.rs index b6174efa3a..848391293c 100644 --- a/codex-rs/cli/src/lib.rs +++ b/codex-rs/cli/src/lib.rs @@ -1,10 +1,21 @@ -pub mod debug_sandbox; +pub(crate) mod debug_sandbox; mod exit_status; -pub mod login; +pub(crate) mod login; use clap::Parser; use codex_utils_cli::CliConfigOverrides; +pub use debug_sandbox::run_command_under_landlock; +pub use debug_sandbox::run_command_under_seatbelt; +pub use debug_sandbox::run_command_under_windows; +pub use login::read_api_key_from_stdin; +pub use login::run_login_status; +pub use login::run_login_with_api_key; +pub use login::run_login_with_chatgpt; +pub use login::run_login_with_device_code; +pub use login::run_login_with_device_code_fallback_to_browser; +pub use login::run_logout; + #[derive(Debug, Parser)] pub struct SeatbeltCommand { /// Convenience alias for low-friction sandboxed automatic execution (network-disabled sandbox that can write to cwd and TMPDIR) diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 3007048a2f..0477162718 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -10,12 +10,12 @@ use codex_chatgpt::apply_command::run_apply_command; use codex_cli::LandlockCommand; use codex_cli::SeatbeltCommand; use codex_cli::WindowsCommand; -use codex_cli::login::read_api_key_from_stdin; -use codex_cli::login::run_login_status; -use codex_cli::login::run_login_with_api_key; -use codex_cli::login::run_login_with_chatgpt; -use codex_cli::login::run_login_with_device_code; -use codex_cli::login::run_logout; +use codex_cli::read_api_key_from_stdin; +use codex_cli::run_login_status; +use codex_cli::run_login_with_api_key; +use codex_cli::run_login_with_chatgpt; +use codex_cli::run_login_with_device_code; +use codex_cli::run_logout; use codex_cloud_tasks::Cli as CloudTasksCli; use codex_exec::Cli as ExecCli; use codex_exec::Command as ExecCommand; @@ -27,7 +27,7 @@ use codex_state::state_db_path; use codex_tui::AppExitInfo; use codex_tui::Cli as TuiCli; use codex_tui::ExitReason; -use codex_tui::update_action::UpdateAction; +use codex_tui::UpdateAction; use codex_utils_cli::CliConfigOverrides; use owo_colors::OwoColorize; use std::io::IsTerminal; @@ -883,7 +883,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut seatbelt_cli.config_overrides, root_config_overrides.clone(), ); - codex_cli::debug_sandbox::run_command_under_seatbelt( + codex_cli::run_command_under_seatbelt( seatbelt_cli, arg0_paths.codex_linux_sandbox_exe.clone(), ) @@ -899,7 +899,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut landlock_cli.config_overrides, root_config_overrides.clone(), ); - codex_cli::debug_sandbox::run_command_under_landlock( + codex_cli::run_command_under_landlock( landlock_cli, arg0_paths.codex_linux_sandbox_exe.clone(), ) @@ -915,7 +915,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut windows_cli.config_overrides, root_config_overrides.clone(), ); - codex_cli::debug_sandbox::run_command_under_windows( + codex_cli::run_command_under_windows( windows_cli, arg0_paths.codex_linux_sandbox_exe.clone(), ) @@ -1173,7 +1173,7 @@ async fn run_debug_prompt_input_command( }); } - let prompt_input = codex_core::prompt_debug::build_prompt_input(config, input).await?; + let prompt_input = codex_core::build_prompt_input(config, input).await?; println!("{}", serde_json::to_string_pretty(&prompt_input)?); Ok(()) diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 027a88a7c5..f544ca82b7 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -8,24 +8,24 @@ use anyhow::bail; use clap::ArgGroup; use codex_config::types::McpServerConfig; use codex_config::types::McpServerTransportConfig; +use codex_core::McpManager; use codex_core::config::Config; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::find_codex_home; use codex_core::config::load_global_mcp_servers; -use codex_core::mcp::McpManager; use codex_core::plugins::PluginsManager; -use codex_mcp::mcp::auth::McpOAuthLoginSupport; -use codex_mcp::mcp::auth::ResolvedMcpOAuthScopes; -use codex_mcp::mcp::auth::compute_auth_statuses; -use codex_mcp::mcp::auth::discover_supported_scopes; -use codex_mcp::mcp::auth::oauth_login_support; -use codex_mcp::mcp::auth::resolve_oauth_scopes; -use codex_mcp::mcp::auth::should_retry_without_scopes; +use codex_mcp::McpOAuthLoginSupport; +use codex_mcp::ResolvedMcpOAuthScopes; +use codex_mcp::compute_auth_statuses; +use codex_mcp::discover_supported_scopes; +use codex_mcp::oauth_login_support; +use codex_mcp::resolve_oauth_scopes; +use codex_mcp::should_retry_without_scopes; use codex_protocol::protocol::McpAuthStatus; use codex_rmcp_client::delete_oauth_tokens; use codex_rmcp_client::perform_oauth_login; use codex_utils_cli::CliConfigOverrides; -use codex_utils_cli::format_env_display::format_env_display; +use codex_utils_cli::format_env_display; /// Subcommands: /// - `list` — list configured servers (with `--json`) diff --git a/codex-rs/cli/src/wsl_paths.rs b/codex-rs/cli/src/wsl_paths.rs index 28366579e5..b90dc1e283 100644 --- a/codex-rs/cli/src/wsl_paths.rs +++ b/codex-rs/cli/src/wsl_paths.rs @@ -1,7 +1,7 @@ use std::ffi::OsStr; /// Returns true if the current process is running under WSL. -pub use codex_utils_path::env::is_wsl; +pub use codex_utils_path::is_wsl; /// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`). /// Returns `None` if the input does not look like a Windows drive path. diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 04463a7dd4..ad4ebed12f 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -806,7 +806,7 @@ fn status_code_tag(status_code: Option) -> String { } fn emit_metric(metric_name: &str, tags: Vec<(&str, String)>) { - if let Some(metrics) = codex_otel::metrics::global() { + if let Some(metrics) = codex_otel::global() { let tag_refs = tags .iter() .map(|(key, value)| (*key, value.as_str())) diff --git a/codex-rs/cloud-tasks/src/lib.rs b/codex-rs/cloud-tasks/src/lib.rs index f96ac62ed9..7006d52b92 100644 --- a/codex-rs/cloud-tasks/src/lib.rs +++ b/codex-rs/cloud-tasks/src/lib.rs @@ -1,10 +1,10 @@ mod app; mod cli; -pub mod env_detect; +pub(crate) mod env_detect; mod new_task; -pub mod scrollable_diff; +pub(crate) mod scrollable_diff; mod ui; -pub mod util; +pub(crate) mod util; pub use cli::Cli; use anyhow::anyhow; @@ -1596,7 +1596,7 @@ pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> an let total = ov.attempt_display_total(); let current = ov.selected_attempt + 1; app.status = format!("Viewing attempt {current} of {total}"); - ov.sd.to_top(); + ov.sd.scroll_to_top(); needs_redraw = true; } }; @@ -1672,7 +1672,7 @@ pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> an let has_diff = ov.current_attempt().is_some_and(app::AttemptView::has_diff) || ov.base_can_apply; if has_text && has_diff { ov.set_view(app::DetailView::Prompt); - ov.sd.to_top(); + ov.sd.scroll_to_top(); needs_redraw = true; } } @@ -1683,7 +1683,7 @@ pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> an let has_diff = ov.current_attempt().is_some_and(app::AttemptView::has_diff) || ov.base_can_apply; if has_text && has_diff { ov.set_view(app::DetailView::Diff); - ov.sd.to_top(); + ov.sd.scroll_to_top(); needs_redraw = true; } } @@ -1714,8 +1714,8 @@ pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> an if let Some(ov) = &mut app.diff_overlay { let step = ov.sd.state.viewport_h.saturating_sub(1) as i16; ov.sd.page_by(-step); } needs_redraw = true; } - KeyCode::Home => { if let Some(ov) = &mut app.diff_overlay { ov.sd.to_top(); } needs_redraw = true; } - KeyCode::End => { if let Some(ov) = &mut app.diff_overlay { ov.sd.to_bottom(); } needs_redraw = true; } + KeyCode::Home => { if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_to_top(); } needs_redraw = true; } + KeyCode::End => { if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_to_bottom(); } needs_redraw = true; } _ => {} } } else if app.env_modal.is_some() { diff --git a/codex-rs/cloud-tasks/src/scrollable_diff.rs b/codex-rs/cloud-tasks/src/scrollable_diff.rs index 97dfb24895..59dd076b36 100644 --- a/codex-rs/cloud-tasks/src/scrollable_diff.rs +++ b/codex-rs/cloud-tasks/src/scrollable_diff.rs @@ -86,11 +86,11 @@ impl ScrollableDiff { self.scroll_by(delta); } - pub fn to_top(&mut self) { + pub fn scroll_to_top(&mut self) { self.state.scroll = 0; } - pub fn to_bottom(&mut self) { + pub fn scroll_to_bottom(&mut self) { self.state.scroll = self.max_scroll(); } diff --git a/codex-rs/codex-api/src/endpoint/mod.rs b/codex-rs/codex-api/src/endpoint/mod.rs index 6a748e533d..a6c2603f70 100644 --- a/codex-rs/codex-api/src/endpoint/mod.rs +++ b/codex-rs/codex-api/src/endpoint/mod.rs @@ -1,7 +1,22 @@ -pub mod compact; -pub mod memories; -pub mod models; -pub mod realtime_websocket; -pub mod responses; -pub mod responses_websocket; +pub(crate) mod compact; +pub(crate) mod memories; +pub(crate) mod models; +pub(crate) mod realtime_websocket; +pub(crate) mod responses; +pub(crate) mod responses_websocket; mod session; + +pub use compact::CompactClient; +pub use memories::MemoriesClient; +pub use models::ModelsClient; +pub use realtime_websocket::RealtimeEventParser; +pub use realtime_websocket::RealtimeSessionConfig; +pub use realtime_websocket::RealtimeSessionMode; +pub use realtime_websocket::RealtimeWebsocketClient; +pub use realtime_websocket::RealtimeWebsocketConnection; +pub use realtime_websocket::RealtimeWebsocketEvents; +pub use realtime_websocket::RealtimeWebsocketWriter; +pub use responses::ResponsesClient; +pub use responses::ResponsesOptions; +pub use responses_websocket::ResponsesWebsocketClient; +pub use responses_websocket::ResponsesWebsocketConnection; diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs index eed0e470a4..544c7ad7a5 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs @@ -625,9 +625,9 @@ fn normalize_realtime_path(url: &mut Url) { #[cfg(test)] mod tests { use super::*; - use crate::endpoint::realtime_websocket::protocol::RealtimeHandoffRequested; use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptDelta; use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry; + use codex_protocol::protocol::RealtimeHandoffRequested; use codex_protocol::protocol::RealtimeInputAudioSpeechStarted; use codex_protocol::protocol::RealtimeResponseCancelled; use http::HeaderValue; diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs index d13585034a..867ebdff65 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs @@ -1,14 +1,12 @@ -pub mod methods; +pub(crate) mod methods; mod methods_common; mod methods_v1; mod methods_v2; -pub mod protocol; +pub(crate) mod protocol; mod protocol_common; mod protocol_v1; mod protocol_v2; -pub use codex_protocol::protocol::RealtimeAudioFrame; -pub use codex_protocol::protocol::RealtimeEvent; pub use methods::RealtimeWebsocketClient; pub use methods::RealtimeWebsocketConnection; pub use methods::RealtimeWebsocketEvents; diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs index 2c629249fa..4941740556 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs @@ -2,7 +2,6 @@ use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1; use crate::endpoint::realtime_websocket::protocol_v2::parse_realtime_event_v2; pub use codex_protocol::protocol::RealtimeAudioFrame; pub use codex_protocol::protocol::RealtimeEvent; -pub use codex_protocol::protocol::RealtimeHandoffRequested; pub use codex_protocol::protocol::RealtimeTranscriptDelta; pub use codex_protocol::protocol::RealtimeTranscriptEntry; use serde::Serialize; diff --git a/codex-rs/codex-api/src/endpoint/responses.rs b/codex-rs/codex-api/src/endpoint/responses.rs index 57a44d2e27..8e0e7384fd 100644 --- a/codex-rs/codex-api/src/endpoint/responses.rs +++ b/codex-rs/codex-api/src/endpoint/responses.rs @@ -4,11 +4,11 @@ use crate::common::ResponsesApiRequest; use crate::endpoint::session::EndpointSession; use crate::error::ApiError; use crate::provider::Provider; +use crate::requests::Compression; +use crate::requests::attach_item_ids; use crate::requests::headers::build_conversation_headers; use crate::requests::headers::insert_header; use crate::requests::headers::subagent_header; -use crate::requests::responses::Compression; -use crate::requests::responses::attach_item_ids; use crate::sse::spawn_response_stream; use crate::telemetry::SseTelemetry; use codex_client::HttpTransport; diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index d3b578db69..a60d188bda 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -6,8 +6,8 @@ use crate::common::ResponsesWsRequest; use crate::error::ApiError; use crate::provider::Provider; use crate::rate_limits::parse_rate_limit_event; -use crate::sse::responses::ResponsesStreamEvent; -use crate::sse::responses::process_responses_event; +use crate::sse::ResponsesStreamEvent; +use crate::sse::process_responses_event; use crate::telemetry::WebsocketTelemetry; use codex_client::TransportError; use codex_client::maybe_build_rustls_client_config_with_custom_ca; diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index c7bb607059..01a5637356 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -1,48 +1,58 @@ -pub mod api_bridge; -pub mod auth; -pub mod common; -pub mod endpoint; -pub mod error; -pub mod provider; -pub mod rate_limits; -pub mod requests; -pub mod sse; -pub mod telemetry; +pub(crate) mod api_bridge; +pub(crate) mod auth; +pub(crate) mod common; +pub(crate) mod endpoint; +pub(crate) mod error; +pub(crate) mod provider; +pub(crate) mod rate_limits; +pub(crate) mod requests; +pub(crate) mod sse; +pub(crate) mod telemetry; pub use crate::requests::headers::build_conversation_headers; pub use codex_client::RequestTelemetry; pub use codex_client::ReqwestTransport; pub use codex_client::TransportError; +pub use crate::api_bridge::CoreAuthProvider; +pub use crate::api_bridge::map_api_error; pub use crate::auth::AuthProvider; pub use crate::common::CompactionInput; pub use crate::common::MemorySummarizeInput; pub use crate::common::MemorySummarizeOutput; +pub use crate::common::OpenAiVerbosity; pub use crate::common::RawMemory; pub use crate::common::RawMemoryMetadata; +pub use crate::common::Reasoning; pub use crate::common::ResponseCreateWsRequest; pub use crate::common::ResponseEvent; pub use crate::common::ResponseStream; pub use crate::common::ResponsesApiRequest; +pub use crate::common::ResponsesWsRequest; +pub use crate::common::TextControls; pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY; pub use crate::common::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY; pub use crate::common::create_text_param_for_request; pub use crate::common::response_create_client_metadata; -pub use crate::endpoint::compact::CompactClient; -pub use crate::endpoint::memories::MemoriesClient; -pub use crate::endpoint::models::ModelsClient; -pub use crate::endpoint::realtime_websocket::RealtimeEventParser; -pub use crate::endpoint::realtime_websocket::RealtimeSessionConfig; -pub use crate::endpoint::realtime_websocket::RealtimeSessionMode; -pub use crate::endpoint::realtime_websocket::RealtimeWebsocketClient; -pub use crate::endpoint::realtime_websocket::RealtimeWebsocketConnection; -pub use crate::endpoint::responses::ResponsesClient; -pub use crate::endpoint::responses::ResponsesOptions; -pub use crate::endpoint::responses_websocket::ResponsesWebsocketClient; -pub use crate::endpoint::responses_websocket::ResponsesWebsocketConnection; +pub use crate::endpoint::CompactClient; +pub use crate::endpoint::MemoriesClient; +pub use crate::endpoint::ModelsClient; +pub use crate::endpoint::RealtimeEventParser; +pub use crate::endpoint::RealtimeSessionConfig; +pub use crate::endpoint::RealtimeSessionMode; +pub use crate::endpoint::RealtimeWebsocketClient; +pub use crate::endpoint::RealtimeWebsocketConnection; +pub use crate::endpoint::RealtimeWebsocketEvents; +pub use crate::endpoint::RealtimeWebsocketWriter; +pub use crate::endpoint::ResponsesClient; +pub use crate::endpoint::ResponsesOptions; +pub use crate::endpoint::ResponsesWebsocketClient; +pub use crate::endpoint::ResponsesWebsocketConnection; pub use crate::error::ApiError; pub use crate::provider::Provider; +pub use crate::provider::RetryConfig; pub use crate::provider::is_azure_responses_wire_base_url; +pub use crate::requests::Compression; pub use crate::sse::stream_from_fixture; pub use crate::telemetry::SseTelemetry; pub use crate::telemetry::WebsocketTelemetry; diff --git a/codex-rs/codex-api/src/requests/mod.rs b/codex-rs/codex-api/src/requests/mod.rs index 4e98bb8cac..1c357b2a61 100644 --- a/codex-rs/codex-api/src/requests/mod.rs +++ b/codex-rs/codex-api/src/requests/mod.rs @@ -1,2 +1,5 @@ pub(crate) mod headers; -pub mod responses; +pub(crate) mod responses; + +pub use responses::Compression; +pub(crate) use responses::attach_item_ids; diff --git a/codex-rs/codex-api/src/sse/mod.rs b/codex-rs/codex-api/src/sse/mod.rs index cb689afc1d..06b9855890 100644 --- a/codex-rs/codex-api/src/sse/mod.rs +++ b/codex-rs/codex-api/src/sse/mod.rs @@ -1,5 +1,6 @@ -pub mod responses; +pub(crate) mod responses; -pub use responses::process_sse; +pub(crate) use responses::ResponsesStreamEvent; +pub(crate) use responses::process_responses_event; pub use responses::spawn_response_stream; pub use responses::stream_from_fixture; diff --git a/codex-rs/codex-api/tests/clients.rs b/codex-rs/codex-api/tests/clients.rs index 2f3bc17e2c..3c22c01203 100644 --- a/codex-rs/codex-api/tests/clients.rs +++ b/codex-rs/codex-api/tests/clients.rs @@ -6,11 +6,11 @@ use anyhow::Result; use async_trait::async_trait; use bytes::Bytes; use codex_api::AuthProvider; +use codex_api::Compression; use codex_api::Provider; use codex_api::ResponsesApiRequest; use codex_api::ResponsesClient; use codex_api::ResponsesOptions; -use codex_api::requests::responses::Compression; use codex_client::HttpTransport; use codex_client::Request; use codex_client::Response; @@ -126,7 +126,7 @@ fn provider(name: &str) -> Provider { base_url: "https://example.com/v1".to_string(), query_params: None, headers: HeaderMap::new(), - retry: codex_api::provider::RetryConfig { + retry: codex_api::RetryConfig { max_attempts: 1, base_delay: Duration::from_millis(1), retry_429: false, diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index 3ffb2496b4..c6b28fa71a 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -1,7 +1,7 @@ use codex_api::AuthProvider; use codex_api::ModelsClient; -use codex_api::provider::Provider; -use codex_api::provider::RetryConfig; +use codex_api::Provider; +use codex_api::RetryConfig; use codex_client::ReqwestTransport; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; diff --git a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs index 130ab6fd35..42c7a92e2d 100644 --- a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs +++ b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs @@ -2,14 +2,14 @@ use std::collections::HashMap; use std::future::Future; use std::time::Duration; +use codex_api::Provider; use codex_api::RealtimeAudioFrame; use codex_api::RealtimeEvent; use codex_api::RealtimeEventParser; use codex_api::RealtimeSessionConfig; use codex_api::RealtimeSessionMode; use codex_api::RealtimeWebsocketClient; -use codex_api::provider::Provider; -use codex_api::provider::RetryConfig; +use codex_api::RetryConfig; use codex_protocol::protocol::RealtimeHandoffRequested; use futures::SinkExt; use futures::StreamExt; diff --git a/codex-rs/codex-api/tests/sse_end_to_end.rs b/codex-rs/codex-api/tests/sse_end_to_end.rs index 80972340dd..b15de296a8 100644 --- a/codex-rs/codex-api/tests/sse_end_to_end.rs +++ b/codex-rs/codex-api/tests/sse_end_to_end.rs @@ -4,10 +4,10 @@ use anyhow::Result; use async_trait::async_trait; use bytes::Bytes; use codex_api::AuthProvider; +use codex_api::Compression; use codex_api::Provider; use codex_api::ResponseEvent; use codex_api::ResponsesClient; -use codex_api::requests::responses::Compression; use codex_client::HttpTransport; use codex_client::Request; use codex_client::Response; @@ -64,7 +64,7 @@ fn provider(name: &str) -> Provider { base_url: "https://example.com/v1".to_string(), query_params: None, headers: HeaderMap::new(), - retry: codex_api::provider::RetryConfig { + retry: codex_api::RetryConfig { max_attempts: 1, base_delay: Duration::from_millis(1), retry_429: false, diff --git a/codex-rs/codex-backend-openapi-models/src/models/mod.rs b/codex-rs/codex-backend-openapi-models/src/models/mod.rs index 90bc058334..2140c83f91 100644 --- a/codex-rs/codex-backend-openapi-models/src/models/mod.rs +++ b/codex-rs/codex-backend-openapi-models/src/models/mod.rs @@ -4,41 +4,41 @@ // The process for this will change // Config -pub mod config_file_response; +pub(crate) mod config_file_response; pub use self::config_file_response::ConfigFileResponse; // Cloud Tasks -pub mod code_task_details_response; +pub(crate) mod code_task_details_response; pub use self::code_task_details_response::CodeTaskDetailsResponse; -pub mod task_response; +pub(crate) mod task_response; pub use self::task_response::TaskResponse; -pub mod external_pull_request_response; +pub(crate) mod external_pull_request_response; pub use self::external_pull_request_response::ExternalPullRequestResponse; -pub mod git_pull_request; +pub(crate) mod git_pull_request; pub use self::git_pull_request::GitPullRequest; -pub mod task_list_item; +pub(crate) mod task_list_item; pub use self::task_list_item::TaskListItem; -pub mod paginated_list_task_list_item_; +pub(crate) mod paginated_list_task_list_item_; pub use self::paginated_list_task_list_item_::PaginatedListTaskListItem; // Rate Limits -pub mod additional_rate_limit_details; +pub(crate) mod additional_rate_limit_details; pub use self::additional_rate_limit_details::AdditionalRateLimitDetails; -pub mod rate_limit_status_payload; +pub(crate) mod rate_limit_status_payload; pub use self::rate_limit_status_payload::PlanType; pub use self::rate_limit_status_payload::RateLimitStatusPayload; -pub mod rate_limit_status_details; +pub(crate) mod rate_limit_status_details; pub use self::rate_limit_status_details::RateLimitStatusDetails; -pub mod rate_limit_window_snapshot; +pub(crate) mod rate_limit_window_snapshot; pub use self::rate_limit_window_snapshot::RateLimitWindowSnapshot; -pub mod credit_status_details; +pub(crate) mod credit_status_details; pub use self::credit_status_details::CreditStatusDetails; diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index 149578c967..48969841c4 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -1,2 +1,40 @@ -pub mod mcp; -pub mod mcp_connection_manager; +pub(crate) mod mcp; +pub(crate) mod mcp_connection_manager; + +pub use mcp::CODEX_APPS_MCP_SERVER_NAME; +pub use mcp::McpAuthStatusEntry; +pub use mcp::McpConfig; +pub use mcp::McpManager; +pub use mcp::McpOAuthLoginConfig; +pub use mcp::McpOAuthLoginSupport; +pub use mcp::McpOAuthScopesSource; +pub use mcp::McpSnapshotDetail; +pub use mcp::ResolvedMcpOAuthScopes; +pub use mcp::ToolPluginProvenance; +pub use mcp::canonical_mcp_server_key; +pub use mcp::collect_mcp_snapshot; +pub use mcp::collect_mcp_snapshot_from_manager; +pub use mcp::collect_mcp_snapshot_from_manager_with_detail; +pub use mcp::collect_mcp_snapshot_with_detail; +pub use mcp::collect_missing_mcp_dependencies; +pub use mcp::compute_auth_statuses; +pub use mcp::configured_mcp_servers; +pub use mcp::discover_supported_scopes; +pub use mcp::effective_mcp_servers; +pub use mcp::group_tools_by_server; +pub use mcp::oauth_login_support; +pub use mcp::qualified_mcp_tool_name_prefix; +pub use mcp::resolve_oauth_scopes; +pub use mcp::should_retry_without_scopes; +pub use mcp::split_qualified_tool_name; +pub use mcp::tool_plugin_provenance; +pub use mcp::with_codex_apps_mcp; +pub use mcp_connection_manager::CodexAppsToolsCacheKey; +pub use mcp_connection_manager::DEFAULT_STARTUP_TIMEOUT; +pub use mcp_connection_manager::MCP_SANDBOX_STATE_CAPABILITY; +pub use mcp_connection_manager::MCP_SANDBOX_STATE_METHOD; +pub use mcp_connection_manager::McpConnectionManager; +pub use mcp_connection_manager::SandboxState; +pub use mcp_connection_manager::ToolInfo; +pub use mcp_connection_manager::codex_apps_tools_cache_key; +pub use mcp_connection_manager::filter_non_codex_apps_mcp_tools_only; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index faa8ecc2fc..9301ff1008 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -1,5 +1,15 @@ -pub mod auth; +pub(crate) mod auth; mod skill_dependencies; +pub use auth::McpAuthStatusEntry; +pub use auth::McpOAuthLoginConfig; +pub use auth::McpOAuthLoginSupport; +pub use auth::McpOAuthScopesSource; +pub use auth::ResolvedMcpOAuthScopes; +pub use auth::compute_auth_statuses; +pub use auth::discover_supported_scopes; +pub use auth::oauth_login_support; +pub use auth::resolve_oauth_scopes; +pub use auth::should_retry_without_scopes; pub use skill_dependencies::canonical_mcp_server_key; pub use skill_dependencies::collect_missing_mcp_dependencies; @@ -23,7 +33,6 @@ use codex_protocol::protocol::McpListToolsResponseEvent; use codex_protocol::protocol::SandboxPolicy; use serde_json::Value; -use crate::mcp::auth::compute_auth_statuses; use crate::mcp_connection_manager::McpConnectionManager; use crate::mcp_connection_manager::SandboxState; use crate::mcp_connection_manager::codex_apps_tools_cache_key; @@ -388,7 +397,7 @@ pub fn group_tools_by_server( pub async fn collect_mcp_snapshot_from_manager( mcp_connection_manager: &McpConnectionManager, - auth_status_entries: HashMap, + auth_status_entries: HashMap, ) -> McpListToolsResponseEvent { collect_mcp_snapshot_from_manager_with_detail( mcp_connection_manager, @@ -400,7 +409,7 @@ pub async fn collect_mcp_snapshot_from_manager( pub async fn collect_mcp_snapshot_from_manager_with_detail( mcp_connection_manager: &McpConnectionManager, - auth_status_entries: HashMap, + auth_status_entries: HashMap, detail: McpSnapshotDetail, ) -> McpListToolsResponseEvent { let (tools, resources, resource_templates) = tokio::join!( diff --git a/codex-rs/codex-mcp/src/mcp_connection_manager.rs b/codex-rs/codex-mcp/src/mcp_connection_manager.rs index b4de70ee95..c90088c7dc 100644 --- a/codex-rs/codex-mcp/src/mcp_connection_manager.rs +++ b/codex-rs/codex-mcp/src/mcp_connection_manager.rs @@ -19,10 +19,10 @@ use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; +use crate::McpAuthStatusEntry; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::McpConfig; use crate::mcp::ToolPluginProvenance; -use crate::mcp::auth::McpAuthStatusEntry; use crate::mcp::configured_mcp_servers; use crate::mcp::effective_mcp_servers; use crate::mcp::sanitize_responses_api_tool_name; @@ -1568,7 +1568,7 @@ fn filter_disallowed_codex_apps_tools(tools: Vec) -> Vec { } fn emit_duration(metric: &str, duration: Duration, tags: &[(&str, &str)]) { - if let Some(metrics) = codex_otel::metrics::global() { + if let Some(metrics) = codex_otel::global() { let _ = metrics.record_duration(metric, duration, tags); } } diff --git a/codex-rs/config/src/requirements_exec_policy.rs b/codex-rs/config/src/requirements_exec_policy.rs index 64d60f8814..30a1a0e694 100644 --- a/codex-rs/config/src/requirements_exec_policy.rs +++ b/codex-rs/config/src/requirements_exec_policy.rs @@ -1,9 +1,9 @@ use codex_execpolicy::Decision; +use codex_execpolicy::PatternToken; use codex_execpolicy::Policy; -use codex_execpolicy::rule::PatternToken; -use codex_execpolicy::rule::PrefixPattern; -use codex_execpolicy::rule::PrefixRule; -use codex_execpolicy::rule::RuleRef; +use codex_execpolicy::PrefixPattern; +use codex_execpolicy::PrefixRule; +use codex_execpolicy::RuleRef; use multimap::MultiMap; use serde::Deserialize; use std::sync::Arc; diff --git a/codex-rs/core/src/agent/registry.rs b/codex-rs/core/src/agent/registry.rs index c600d5c64b..1acd73085f 100644 --- a/codex-rs/core/src/agent/registry.rs +++ b/codex-rs/core/src/agent/registry.rs @@ -220,7 +220,7 @@ impl AgentRegistry { } else { active_agents.used_agent_nicknames.clear(); active_agents.nickname_reset_count += 1; - if let Some(metrics) = codex_otel::metrics::global() { + if let Some(metrics) = codex_otel::global() { let _ = metrics.counter( "codex.multi_agent.nickname_pool_reset", /*inc*/ 1, diff --git a/codex-rs/core/src/apps/render.rs b/codex-rs/core/src/apps/render.rs index 9b93913d78..fe23a09f8d 100644 --- a/codex-rs/core/src/apps/render.rs +++ b/codex-rs/core/src/apps/render.rs @@ -1,5 +1,5 @@ use codex_app_server_protocol::AppInfo; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_protocol::protocol::APPS_INSTRUCTIONS_CLOSE_TAG; use codex_protocol::protocol::APPS_INSTRUCTIONS_OPEN_TAG; diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index b77dda2b75..e11e4362ca 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -31,12 +31,15 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; +use codex_api::ApiError; use codex_api::CompactClient as ApiCompactClient; use codex_api::CompactionInput as ApiCompactionInput; +use codex_api::Compression; use codex_api::MemoriesClient as ApiMemoriesClient; use codex_api::MemorySummarizeInput as ApiMemorySummarizeInput; use codex_api::MemorySummarizeOutput as ApiMemorySummarizeOutput; use codex_api::RawMemory as ApiRawMemory; +use codex_api::Reasoning; use codex_api::RequestTelemetry; use codex_api::ReqwestTransport; use codex_api::ResponseCreateWsRequest; @@ -45,15 +48,12 @@ use codex_api::ResponsesClient as ApiResponsesClient; use codex_api::ResponsesOptions as ApiResponsesOptions; use codex_api::ResponsesWebsocketClient as ApiWebSocketResponsesClient; use codex_api::ResponsesWebsocketConnection as ApiWebSocketConnection; +use codex_api::ResponsesWsRequest; use codex_api::SseTelemetry; use codex_api::TransportError; use codex_api::WebsocketTelemetry; use codex_api::build_conversation_headers; -use codex_api::common::Reasoning; -use codex_api::common::ResponsesWsRequest; use codex_api::create_text_param_for_request; -use codex_api::error::ApiError; -use codex_api::requests::responses::Compression; use codex_api::response_create_client_metadata; use codex_app_server_protocol::AuthMode; use codex_login::AuthManager; @@ -98,8 +98,8 @@ use crate::client_common::ResponseEvent; use crate::client_common::ResponseStream; use crate::flags::CODEX_RS_SSE_FIXTURE; use crate::util::emit_feedback_auth_recovery_tags; -use codex_api::api_bridge::CoreAuthProvider; -use codex_api::api_bridge::map_api_error; +use codex_api::CoreAuthProvider; +use codex_api::map_api_error; use codex_feedback::FeedbackRequestTags; use codex_feedback::emit_feedback_request_tags_with_auth_env; use codex_login::api_bridge::auth_provider_from_auth; diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index 828839ae77..a90d75bf01 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -1,4 +1,4 @@ -pub use codex_api::common::ResponseEvent; +pub use codex_api::ResponseEvent; use codex_config::types::Personality; use codex_protocol::error::Result; use codex_protocol::models::BaseInstructions; diff --git a/codex-rs/core/src/client_common_tests.rs b/codex-rs/core/src/client_common_tests.rs index 968703046e..3d804cda83 100644 --- a/codex-rs/core/src/client_common_tests.rs +++ b/codex-rs/core/src/client_common_tests.rs @@ -1,6 +1,6 @@ +use codex_api::OpenAiVerbosity; use codex_api::ResponsesApiRequest; -use codex_api::common::OpenAiVerbosity; -use codex_api::common::TextControls; +use codex_api::TextControls; use codex_api::create_text_param_for_request; use codex_protocol::config_types::ServiceTier; use codex_protocol::models::FunctionCallOutputPayload; diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index a4fb681201..02d7422475 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -6,7 +6,7 @@ use super::X_CODEX_PARENT_THREAD_ID_HEADER; use super::X_CODEX_TURN_METADATA_HEADER; use super::X_CODEX_WINDOW_ID_HEADER; use super::X_OPENAI_SUBAGENT_HEADER; -use codex_api::api_bridge::CoreAuthProvider; +use codex_api::CoreAuthProvider; use codex_app_server_protocol::AuthMode; use codex_model_provider_info::WireApi; use codex_model_provider_info::create_oss_provider_with_base_url; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 237b77e38d..822dbefa5c 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -70,11 +70,11 @@ use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::auth_env_telemetry::collect_auth_env_telemetry; use codex_login::default_client::originator; -use codex_mcp::mcp_connection_manager::McpConnectionManager; -use codex_mcp::mcp_connection_manager::SandboxState; -use codex_mcp::mcp_connection_manager::ToolInfo as McpToolInfo; -use codex_mcp::mcp_connection_manager::codex_apps_tools_cache_key; -use codex_mcp::mcp_connection_manager::filter_non_codex_apps_mcp_tools_only; +use codex_mcp::McpConnectionManager; +use codex_mcp::SandboxState; +use codex_mcp::ToolInfo as McpToolInfo; +use codex_mcp::codex_apps_tools_cache_key; +use codex_mcp::filter_non_codex_apps_mcp_tools_only; #[cfg(test)] use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_models_manager::manager::ModelsManager; @@ -149,7 +149,6 @@ use rmcp::model::PaginatedRequestParams; use rmcp::model::ReadResourceRequestParams; use rmcp::model::ReadResourceResult; use rmcp::model::RequestId; -use serde_json; use serde_json::Value; use tokio::sync::Mutex; use tokio::sync::RwLock; @@ -322,12 +321,12 @@ use crate::util::backoff; use crate::windows_sandbox::WindowsSandboxLevelExt; use codex_async_utils::OrCancelExt; use codex_git_utils::get_git_repo_root; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::mcp::auth::compute_auth_statuses; -use codex_mcp::mcp::with_codex_apps_mcp; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::compute_auth_statuses; +use codex_mcp::with_codex_apps_mcp; use codex_otel::SessionTelemetry; +use codex_otel::THREAD_STARTED_METRIC; use codex_otel::TelemetryAuthMode; -use codex_otel::metrics::names::THREAD_STARTED_METRIC; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; @@ -407,8 +406,6 @@ pub(crate) type SessionLoopTermination = Shared>; pub struct CodexSpawnOk { pub codex: Codex, pub thread_id: ThreadId, - #[deprecated(note = "use thread_id")] - pub conversation_id: ThreadId, } pub(crate) struct CodexSpawnArgs { @@ -701,12 +698,7 @@ impl Codex { session_loop_termination: session_loop_termination_from_handle(session_loop_handle), }; - #[allow(deprecated)] - Ok(CodexSpawnOk { - codex, - thread_id, - conversation_id: thread_id, - }) + Ok(CodexSpawnOk { codex, thread_id }) } /// Submit the `op` wrapped in a `Submission` with a unique ID. @@ -4791,8 +4783,8 @@ mod handlers { use crate::tasks::UserShellCommandMode; use crate::tasks::UserShellCommandTask; use crate::tasks::execute_user_shell_command; - use codex_mcp::mcp::auth::compute_auth_statuses; - use codex_mcp::mcp::collect_mcp_snapshot_from_manager; + use codex_mcp::collect_mcp_snapshot_from_manager; + use codex_mcp::compute_auth_statuses; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::Event; diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index 0bfb0c3033..ef9a69d347 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -15,7 +15,7 @@ use crate::tools::format_exec_output_str; use codex_features::Features; use codex_login::CodexAuth; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::ToolInfo; use codex_model_provider_info::ModelProviderInfo; use codex_models_manager::bundled_models_response; use codex_models_manager::model_info; @@ -36,9 +36,9 @@ use codex_protocol::request_permissions::PermissionGrantScope; use codex_protocol::request_permissions::RequestPermissionProfile; use tracing::Span; +use crate::RolloutRecorderParams; use crate::rollout::policy::EventPersistenceMode; use crate::rollout::recorder::RolloutRecorder; -use crate::rollout::recorder::RolloutRecorderParams; use crate::state::TaskKind; use crate::tasks::SessionTask; use crate::tasks::SessionTaskContext; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 20d3dd2f1b..5b1bfe83cb 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -54,7 +54,7 @@ use codex_features::FeatureConfigSource; use codex_features::FeatureOverrides; use codex_features::Features; use codex_login::AuthManagerConfig; -use codex_mcp::mcp::McpConfig; +use codex_mcp::McpConfig; use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID; use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::OLLAMA_CHAT_PROVIDER_REMOVED_ERROR; @@ -100,7 +100,7 @@ mod network_proxy_spec; mod permissions; #[cfg(test)] mod schema; -pub mod service; +pub(crate) mod service; pub use codex_config::Constrained; pub use codex_config::ConstraintError; pub use codex_config::ConstraintResult; diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 334e160f12..ad3447eaf3 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -40,14 +40,14 @@ use codex_login::CodexAuth; use codex_login::default_client::create_client; use codex_login::default_client::is_first_party_chat_originator; use codex_login::default_client::originator; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::mcp::ToolPluginProvenance; -use codex_mcp::mcp::auth::compute_auth_statuses; -use codex_mcp::mcp::with_codex_apps_mcp; -use codex_mcp::mcp_connection_manager::McpConnectionManager; -use codex_mcp::mcp_connection_manager::SandboxState; -use codex_mcp::mcp_connection_manager::ToolInfo; -use codex_mcp::mcp_connection_manager::codex_apps_tools_cache_key; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::McpConnectionManager; +use codex_mcp::SandboxState; +use codex_mcp::ToolInfo; +use codex_mcp::ToolPluginProvenance; +use codex_mcp::codex_apps_tools_cache_key; +use codex_mcp::compute_auth_statuses; +use codex_mcp::with_codex_apps_mcp; pub use codex_connectors::CONNECTORS_CACHE_TTL; const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30); diff --git a/codex-rs/core/src/connectors_tests.rs b/codex-rs/core/src/connectors_tests.rs index 893ab243ca..7a45a97a1f 100644 --- a/codex-rs/core/src/connectors_tests.rs +++ b/codex-rs/core/src/connectors_tests.rs @@ -12,8 +12,8 @@ use codex_config::types::AppToolConfig; use codex_config::types::AppToolsConfig; use codex_config::types::AppsDefaultConfig; use codex_features::Feature; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::ToolInfo; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use rmcp::model::JsonObject; diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 309dbbb01b..8a5572a36e 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -417,7 +417,7 @@ fn record_windows_sandbox_spawn_failure( } else { "legacy" }; - if let Some(metrics) = codex_otel::metrics::global() { + if let Some(metrics) = codex_otel::global() { let _ = metrics.counter( "codex.windows_sandbox.createprocessasuserw_failed", /*inc*/ 1, diff --git a/codex-rs/core/src/external_agent_config.rs b/codex-rs/core/src/external_agent_config.rs index 6011d18ee4..efa90c8494 100644 --- a/codex-rs/core/src/external_agent_config.rs +++ b/codex-rs/core/src/external_agent_config.rs @@ -676,7 +676,7 @@ fn emit_migration_metric( item_type: ExternalAgentConfigMigrationItemType, skills_count: Option, ) { - let Some(metrics) = codex_otel::metrics::global() else { + let Some(metrics) = codex_otel::global() else { return; }; let tags = migration_metric_tags(item_type, skills_count); diff --git a/codex-rs/core/src/instructions/mod.rs b/codex-rs/core/src/instructions/mod.rs index 5af9a6e890..a1f77ba5e8 100644 --- a/codex-rs/core/src/instructions/mod.rs +++ b/codex-rs/core/src/instructions/mod.rs @@ -1,2 +1 @@ -pub use codex_instructions::USER_INSTRUCTIONS_PREFIX; pub(crate) use codex_instructions::UserInstructions; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index d68c2b2992..e13a19b290 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -10,7 +10,7 @@ mod apps; mod arc_monitor; mod client; mod client_common; -pub mod codex; +pub(crate) mod codex; mod realtime_context; mod realtime_conversation; pub use codex::SteerInputError; @@ -38,28 +38,40 @@ mod flags; mod git_info_tests; mod guardian; mod hook_runtime; -pub mod instructions; -pub mod landlock; -pub mod mcp; +pub(crate) mod instructions; +pub(crate) mod landlock; +pub use landlock::spawn_command_under_linux_sandbox; +pub(crate) mod mcp; mod mcp_skill_dependencies; mod mcp_tool_approval_templates; mod network_policy_decision; -pub mod network_proxy_loader; +pub(crate) mod network_proxy_loader; +pub use mcp::McpManager; +pub use network_proxy_loader::MtimeConfigReloader; +pub use network_proxy_loader::build_network_proxy_state; +pub use network_proxy_loader::build_network_proxy_state_and_reloader; mod original_image_detail; -pub use codex_mcp::mcp_connection_manager; -pub use codex_mcp::mcp_connection_manager::MCP_SANDBOX_STATE_CAPABILITY; -pub use codex_mcp::mcp_connection_manager::MCP_SANDBOX_STATE_METHOD; -pub use codex_mcp::mcp_connection_manager::SandboxState; +pub use codex_mcp::MCP_SANDBOX_STATE_CAPABILITY; +pub use codex_mcp::MCP_SANDBOX_STATE_METHOD; +pub use codex_mcp::SandboxState; mod mcp_tool_call; mod memories; -pub mod mention_syntax; -pub mod message_history; -pub mod utils; +pub(crate) mod mention_syntax; +pub(crate) mod message_history; +pub(crate) mod utils; +pub use mention_syntax::PLUGIN_TEXT_MENTION_SIGIL; +pub use mention_syntax::TOOL_MENTION_SIGIL; +pub use message_history::HistoryEntry as MessageHistoryEntry; +pub use message_history::append_entry as append_message_history_entry; +pub use message_history::history_metadata as message_history_metadata; +pub use message_history::lookup as lookup_message_history_entry; pub use utils::path_utils; pub mod personality_migration; pub mod plugins; #[doc(hidden)] -pub mod prompt_debug; +pub(crate) mod prompt_debug; +#[doc(hidden)] +pub use prompt_debug::build_prompt_input; pub(crate) mod mentions { pub(crate) use crate::plugins::build_connector_slug_counts; pub(crate) use crate::plugins::build_skill_name_counts; @@ -102,54 +114,63 @@ mod event_mapping; pub mod review_format; pub mod review_prompts; mod thread_manager; -pub mod web_search; -pub mod windows_sandbox_read_grants; +pub(crate) mod web_search; +pub(crate) mod windows_sandbox_read_grants; pub use thread_manager::ForkSnapshot; pub use thread_manager::NewThread; pub use thread_manager::ThreadManager; +pub use web_search::web_search_action_detail; +pub use web_search::web_search_detail; +pub use windows_sandbox_read_grants::grant_read_root_non_elevated; #[deprecated(note = "use ThreadManager")] pub type ConversationManager = ThreadManager; #[deprecated(note = "use NewThread")] pub type NewConversation = NewThread; #[deprecated(note = "use CodexThread")] pub type CodexConversation = CodexThread; -pub mod project_doc; +pub(crate) mod project_doc; +pub use project_doc::DEFAULT_PROJECT_DOC_FILENAME; +pub use project_doc::LOCAL_PROJECT_DOC_FILENAME; +pub use project_doc::discover_project_doc_paths; +pub use project_doc::read_project_docs; mod rollout; pub(crate) mod safety; pub mod seatbelt; mod session_rollout_init_error; pub mod shell; -pub mod shell_snapshot; +pub(crate) mod shell_snapshot; pub mod spawn; -pub mod state_db_bridge; +pub(crate) mod state_db_bridge; +pub use state_db_bridge::StateDbHandle; +pub use state_db_bridge::get_state_db; mod thread_rollout_truncation; mod tools; -pub mod turn_diff_tracker; +pub(crate) mod turn_diff_tracker; mod turn_metadata; mod turn_timing; pub use rollout::ARCHIVED_SESSIONS_SUBDIR; +pub use rollout::Cursor; +pub use rollout::EventPersistenceMode; pub use rollout::INTERACTIVE_SESSION_SOURCES; pub use rollout::RolloutRecorder; pub use rollout::RolloutRecorderParams; pub use rollout::SESSIONS_SUBDIR; pub use rollout::SessionMeta; +pub use rollout::ThreadItem; +pub use rollout::ThreadSortKey; +pub use rollout::ThreadsPage; pub use rollout::append_thread_name; pub use rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use rollout::find_conversation_path_by_id_str; pub use rollout::find_thread_name_by_id; +pub use rollout::find_thread_names_by_ids; pub use rollout::find_thread_path_by_id_str; pub use rollout::find_thread_path_by_name_str; -pub use rollout::list::Cursor; -pub use rollout::list::ThreadItem; -pub use rollout::list::ThreadSortKey; -pub use rollout::list::ThreadsPage; -pub use rollout::list::parse_cursor; -pub use rollout::list::read_head_for_summary; -pub use rollout::list::read_session_meta_line; -pub use rollout::policy::EventPersistenceMode; +pub use rollout::parse_cursor; +pub use rollout::read_head_for_summary; +pub use rollout::read_session_meta_line; pub use rollout::rollout_date_parts; -pub use rollout::session_index::find_thread_names_by_ids; mod function_tool; mod state; mod tasks; @@ -172,5 +193,7 @@ pub use exec_policy::load_exec_policy; pub use file_watcher::FileWatcherEvent; pub use turn_metadata::build_turn_metadata_header; pub mod compact; -pub mod memory_trace; +pub(crate) mod memory_trace; +pub use memory_trace::BuiltMemory; +pub use memory_trace::build_memories_from_trace_files; pub mod otel_init; diff --git a/codex-rs/core/src/mcp.rs b/codex-rs/core/src/mcp.rs index d82452c54d..83becdc07e 100644 --- a/codex-rs/core/src/mcp.rs +++ b/codex-rs/core/src/mcp.rs @@ -5,10 +5,10 @@ use crate::config::Config; use crate::plugins::PluginsManager; use codex_config::McpServerConfig; use codex_login::CodexAuth; -use codex_mcp::mcp::ToolPluginProvenance; -use codex_mcp::mcp::configured_mcp_servers; -use codex_mcp::mcp::effective_mcp_servers; -use codex_mcp::mcp::tool_plugin_provenance as collect_tool_plugin_provenance; +use codex_mcp::ToolPluginProvenance; +use codex_mcp::configured_mcp_servers; +use codex_mcp::effective_mcp_servers; +use codex_mcp::tool_plugin_provenance as collect_tool_plugin_provenance; #[derive(Clone)] pub struct McpManager { diff --git a/codex-rs/core/src/mcp_skill_dependencies.rs b/codex-rs/core/src/mcp_skill_dependencies.rs index dfd8a4c5c3..fca38919a0 100644 --- a/codex-rs/core/src/mcp_skill_dependencies.rs +++ b/codex-rs/core/src/mcp_skill_dependencies.rs @@ -21,10 +21,10 @@ use crate::SkillMetadata; use crate::codex::Session; use crate::codex::TurnContext; use crate::skills::model::SkillToolDependency; -use codex_mcp::mcp::auth::McpOAuthLoginSupport; -use codex_mcp::mcp::auth::oauth_login_support; -use codex_mcp::mcp::auth::resolve_oauth_scopes; -use codex_mcp::mcp::auth::should_retry_without_scopes; +use codex_mcp::McpOAuthLoginSupport; +use codex_mcp::oauth_login_support; +use codex_mcp::resolve_oauth_scopes; +use codex_mcp::should_retry_without_scopes; const SKILL_MCP_DEPENDENCY_PROMPT_ID: &str = "skill_mcp_dependency_install"; const MCP_DEPENDENCY_OPTION_INSTALL: &str = "Install"; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 344e46d0be..2a94d13f89 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -32,7 +32,7 @@ use codex_analytics::InvocationType; use codex_analytics::build_track_events_context; use codex_config::types::AppToolApproval; use codex_features::Feature; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_otel::sanitize_metric_tag_value; use codex_protocol::mcp::CallToolResult; use codex_protocol::openai_models::InputModality; diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index c732692d62..4a0e7cd984 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -3,11 +3,11 @@ use codex_config::types::OtelExporterKind as Kind; use codex_config::types::OtelHttpProtocol as Protocol; use codex_features::Feature; use codex_login::default_client::originator; +use codex_otel::OtelExporter; +use codex_otel::OtelHttpProtocol; use codex_otel::OtelProvider; -use codex_otel::config::OtelExporter; -use codex_otel::config::OtelHttpProtocol; -use codex_otel::config::OtelSettings; -use codex_otel::config::OtelTlsConfig as OtelTlsSettings; +use codex_otel::OtelSettings; +use codex_otel::OtelTlsConfig as OtelTlsSettings; use std::error::Error; /// Build an OpenTelemetry provider from the app Config. diff --git a/codex-rs/core/src/plugins/injection.rs b/codex-rs/core/src/plugins/injection.rs index e482010b2e..3e5bb6ecb5 100644 --- a/codex-rs/core/src/plugins/injection.rs +++ b/codex-rs/core/src/plugins/injection.rs @@ -7,8 +7,8 @@ use codex_protocol::models::ResponseItem; use crate::connectors; use crate::plugins::PluginCapabilitySummary; use crate::plugins::render_explicit_plugin_instructions; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::ToolInfo; pub(crate) fn build_plugin_injections( mentioned_plugins: &[PluginCapabilitySummary], diff --git a/codex-rs/core/src/plugins/startup_sync.rs b/codex-rs/core/src/plugins/startup_sync.rs index 14608d1313..5bca32de13 100644 --- a/codex-rs/core/src/plugins/startup_sync.rs +++ b/codex-rs/core/src/plugins/startup_sync.rs @@ -6,8 +6,8 @@ use std::process::Stdio; use std::sync::Arc; use std::time::Duration; -use codex_otel::metrics::names::CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC; -use codex_otel::metrics::names::CURATED_PLUGINS_STARTUP_SYNC_METRIC; +use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC; +use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_METRIC; use reqwest::Client; use serde::Deserialize; use tempfile::TempDir; @@ -451,7 +451,7 @@ fn emit_curated_plugins_startup_sync_counter( transport: &'static str, status: &'static str, ) { - let Some(metrics) = codex_otel::metrics::global() else { + let Some(metrics) = codex_otel::global() else { return; }; let tags = [("transport", transport), ("status", status)]; diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 4eb4278048..16f88650a4 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -12,9 +12,9 @@ use codex_api::RealtimeEventParser; use codex_api::RealtimeSessionConfig; use codex_api::RealtimeSessionMode; use codex_api::RealtimeWebsocketClient; -use codex_api::api_bridge::map_api_error; -use codex_api::endpoint::realtime_websocket::RealtimeWebsocketEvents; -use codex_api::endpoint::realtime_websocket::RealtimeWebsocketWriter; +use codex_api::RealtimeWebsocketEvents; +use codex_api::RealtimeWebsocketWriter; +use codex_api::map_api_error; use codex_app_server_protocol::AuthMode; use codex_config::config_toml::RealtimeWsMode; use codex_config::config_toml::RealtimeWsVersion; diff --git a/codex-rs/core/src/rollout.rs b/codex-rs/core/src/rollout.rs index c3a7218710..492b0bc058 100644 --- a/codex-rs/core/src/rollout.rs +++ b/codex-rs/core/src/rollout.rs @@ -1,17 +1,26 @@ use crate::config::Config; pub use codex_rollout::ARCHIVED_SESSIONS_SUBDIR; +pub use codex_rollout::Cursor; +pub use codex_rollout::EventPersistenceMode; pub use codex_rollout::INTERACTIVE_SESSION_SOURCES; pub use codex_rollout::RolloutRecorder; pub use codex_rollout::RolloutRecorderParams; pub use codex_rollout::SESSIONS_SUBDIR; pub use codex_rollout::SessionMeta; +pub use codex_rollout::ThreadItem; +pub use codex_rollout::ThreadSortKey; +pub use codex_rollout::ThreadsPage; pub use codex_rollout::append_thread_name; pub use codex_rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use codex_rollout::find_conversation_path_by_id_str; pub use codex_rollout::find_thread_name_by_id; +pub use codex_rollout::find_thread_names_by_ids; pub use codex_rollout::find_thread_path_by_id_str; pub use codex_rollout::find_thread_path_by_name_str; +pub use codex_rollout::parse_cursor; +pub use codex_rollout::read_head_for_summary; +pub use codex_rollout::read_session_meta_line; pub use codex_rollout::rollout_date_parts; impl codex_rollout::RolloutConfigView for Config { @@ -36,24 +45,30 @@ impl codex_rollout::RolloutConfigView for Config { } } -pub mod list { - pub use codex_rollout::list::*; +pub(crate) mod list { + pub use codex_rollout::ThreadListConfig; + pub use codex_rollout::ThreadListLayout; + pub use codex_rollout::ThreadSortKey; + pub use codex_rollout::find_thread_path_by_id_str; + pub use codex_rollout::get_threads_in_root; } pub(crate) mod metadata { - pub(crate) use codex_rollout::metadata::builder_from_items; + pub(crate) use codex_rollout::builder_from_items; } -pub mod policy { - pub use codex_rollout::policy::*; +pub(crate) mod policy { + pub use codex_rollout::EventPersistenceMode; + pub use codex_rollout::should_persist_response_item_for_memories; } -pub mod recorder { - pub use codex_rollout::recorder::*; +pub(crate) mod recorder { + pub use codex_rollout::RolloutRecorder; } -pub mod session_index { - pub use codex_rollout::session_index::*; +pub(crate) mod session_index { + pub use codex_rollout::append_thread_name; + pub use codex_rollout::find_thread_name_by_id; } pub(crate) use crate::session_rollout_init_error::map_session_init_error; diff --git a/codex-rs/core/src/session_startup_prewarm.rs b/codex-rs/core/src/session_startup_prewarm.rs index 708401aedd..d3ab0e6198 100644 --- a/codex-rs/core/src/session_startup_prewarm.rs +++ b/codex-rs/core/src/session_startup_prewarm.rs @@ -13,9 +13,9 @@ use crate::codex::INITIAL_SUBMIT_ID; use crate::codex::Session; use crate::codex::build_prompt; use crate::codex::built_tools; +use codex_otel::STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC; +use codex_otel::STARTUP_PREWARM_DURATION_METRIC; use codex_otel::SessionTelemetry; -use codex_otel::metrics::names::STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC; -use codex_otel::metrics::names::STARTUP_PREWARM_DURATION_METRIC; use codex_protocol::error::Result as CodexResult; use codex_protocol::models::BaseInstructions; diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index a0600ddcec..e5c3a00cb2 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -17,7 +17,7 @@ use codex_analytics::AnalyticsEventsClient; use codex_exec_server::Environment; use codex_hooks::Hooks; use codex_login::AuthManager; -use codex_mcp::mcp_connection_manager::McpConnectionManager; +use codex_mcp::McpConnectionManager; use codex_models_manager::manager::ModelsManager; use codex_otel::SessionTelemetry; use codex_rollout::state_db::StateDbHandle; diff --git a/codex-rs/core/src/state_db_bridge.rs b/codex-rs/core/src/state_db_bridge.rs index f073c498b5..c588f039d2 100644 --- a/codex-rs/core/src/state_db_bridge.rs +++ b/codex-rs/core/src/state_db_bridge.rs @@ -1,18 +1,5 @@ use codex_rollout::state_db as rollout_state_db; pub use codex_rollout::state_db::StateDbHandle; -pub use codex_rollout::state_db::apply_rollout_items; -pub use codex_rollout::state_db::find_rollout_path_by_id; -pub use codex_rollout::state_db::get_dynamic_tools; -pub use codex_rollout::state_db::list_thread_ids_db; -pub use codex_rollout::state_db::list_threads_db; -pub use codex_rollout::state_db::mark_thread_memory_mode_polluted; -pub use codex_rollout::state_db::normalize_cwd_for_state_db; -pub use codex_rollout::state_db::open_if_present; -pub use codex_rollout::state_db::persist_dynamic_tools; -pub use codex_rollout::state_db::read_repair_rollout_path; -pub use codex_rollout::state_db::reconcile_rollout; -pub use codex_rollout::state_db::touch_thread_updated_at; -pub use codex_state::LogEntry; use crate::config::Config; diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index f33e6886f4..5da3650bf8 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -33,10 +33,10 @@ use crate::state::TaskKind; use codex_login::AuthManager; use codex_models_manager::manager::ModelsManager; use codex_otel::SessionTelemetry; -use codex_otel::metrics::names::TURN_E2E_DURATION_METRIC; -use codex_otel::metrics::names::TURN_NETWORK_PROXY_METRIC; -use codex_otel::metrics::names::TURN_TOKEN_USAGE_METRIC; -use codex_otel::metrics::names::TURN_TOOL_CALL_METRIC; +use codex_otel::TURN_E2E_DURATION_METRIC; +use codex_otel::TURN_NETWORK_PROXY_METRIC; +use codex_otel::TURN_TOKEN_USAGE_METRIC; +use codex_otel::TURN_TOOL_CALL_METRIC; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; diff --git a/codex-rs/core/src/tasks/mod_tests.rs b/codex-rs/core/src/tasks/mod_tests.rs index 6573da5d4c..22bf0a99c8 100644 --- a/codex-rs/core/src/tasks/mod_tests.rs +++ b/codex-rs/core/src/tasks/mod_tests.rs @@ -1,8 +1,8 @@ use super::emit_turn_network_proxy_metric; +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; use codex_otel::SessionTelemetry; -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::names::TURN_NETWORK_PROXY_METRIC; +use codex_otel::TURN_NETWORK_PROXY_METRIC; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use opentelemetry::KeyValue; diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index f0a62b8c14..ec6fc02cfa 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -1,5 +1,5 @@ pub(crate) mod agent_jobs; -pub mod apply_patch; +pub(crate) mod apply_patch; mod dynamic; mod js_repl; mod list_dir; diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index df66543da6..984e09a968 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -63,7 +63,7 @@ pub(crate) use send_input::Handler as SendInputHandler; pub(crate) use spawn::Handler as SpawnAgentHandler; pub(crate) use wait::Handler as WaitAgentHandler; -pub mod close_agent; +pub(crate) mod close_agent; mod resume_agent; mod send_input; mod spawn; diff --git a/codex-rs/core/src/tools/handlers/tool_search.rs b/codex-rs/core/src/tools/handlers/tool_search.rs index dd203e93b5..d1033c6135 100644 --- a/codex-rs/core/src/tools/handlers/tool_search.rs +++ b/codex-rs/core/src/tools/handlers/tool_search.rs @@ -7,7 +7,7 @@ use crate::tools::registry::ToolKind; use bm25::Document; use bm25::Language; use bm25::SearchEngineBuilder; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::ToolInfo; use codex_tools::TOOL_SEARCH_DEFAULT_LIMIT; use codex_tools::TOOL_SEARCH_TOOL_NAME; use codex_tools::ToolSearchResultSource; diff --git a/codex-rs/core/src/tools/handlers/tool_suggest.rs b/codex-rs/core/src/tools/handlers/tool_suggest.rs index 380aebd51b..9975f5131f 100644 --- a/codex-rs/core/src/tools/handlers/tool_suggest.rs +++ b/codex-rs/core/src/tools/handlers/tool_suggest.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use codex_app_server_protocol::AppInfo; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_rmcp_client::ElicitationAction; use codex_tools::DiscoverableTool; use codex_tools::DiscoverableToolAction; diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index dfe8c42752..4486cd7917 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -24,7 +24,7 @@ use crate::unified_exec::UnifiedExecProcessManager; use crate::unified_exec::WriteStdinRequest; use codex_features::Feature; use codex_otel::SessionTelemetry; -use codex_otel::metrics::names::TOOL_CALL_UNIFIED_EXEC_METRIC; +use codex_otel::TOOL_CALL_UNIFIED_EXEC_METRIC; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::TerminalInteractionEvent; diff --git a/codex-rs/core/src/tools/mod.rs b/codex-rs/core/src/tools/mod.rs index f94f896d20..06c20d6922 100644 --- a/codex-rs/core/src/tools/mod.rs +++ b/codex-rs/core/src/tools/mod.rs @@ -1,16 +1,16 @@ -pub mod code_mode; -pub mod context; -pub mod events; +pub(crate) mod code_mode; +pub(crate) mod context; +pub(crate) mod events; pub(crate) mod handlers; -pub mod js_repl; +pub(crate) mod js_repl; pub(crate) mod network_approval; -pub mod orchestrator; -pub mod parallel; -pub mod registry; -pub mod router; -pub mod runtimes; -pub mod sandboxing; -pub mod spec; +pub(crate) mod orchestrator; +pub(crate) mod parallel; +pub(crate) mod registry; +pub(crate) mod router; +pub(crate) mod runtimes; +pub(crate) mod sandboxing; +pub(crate) mod spec; use codex_protocol::exec_output::ExecToolCallOutput; use codex_utils_output_truncation::TruncationPolicy; diff --git a/codex-rs/core/src/tools/router.rs b/codex-rs/core/src/tools/router.rs index 4fd64715bb..aad8c1b7dc 100644 --- a/codex-rs/core/src/tools/router.rs +++ b/codex-rs/core/src/tools/router.rs @@ -8,7 +8,7 @@ use crate::tools::context::ToolPayload; use crate::tools::registry::AnyToolResult; use crate::tools::registry::ToolRegistry; use crate::tools::spec::build_specs_with_discoverable_tools; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::ToolInfo; use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::models::LocalShellAction; use codex_protocol::models::ResponseItem; diff --git a/codex-rs/core/src/tools/runtimes/mod.rs b/codex-rs/core/src/tools/runtimes/mod.rs index 53890a89b7..a4b44ff0ec 100644 --- a/codex-rs/core/src/tools/runtimes/mod.rs +++ b/codex-rs/core/src/tools/runtimes/mod.rs @@ -12,9 +12,9 @@ use codex_sandboxing::SandboxCommand; use std::collections::HashMap; use std::path::Path; -pub mod apply_patch; -pub mod shell; -pub mod unified_exec; +pub(crate) mod apply_patch; +pub(crate) mod shell; +pub(crate) mod unified_exec; /// Shared helper to construct sandbox transform inputs from a tokenized command line. /// Validates that at least a program is present. diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 90b9a382aa..37a68d4081 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -5,8 +5,8 @@ use crate::tools::handlers::multi_agents_common::DEFAULT_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MIN_WAIT_TIMEOUT_MS; use crate::tools::registry::ToolRegistryBuilder; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::mcp_connection_manager::ToolInfo; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::ToolInfo; use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_tools::DiscoverableTool; use codex_tools::ToolHandlerKind; diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index 4615b45319..13fa4930db 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -8,7 +8,7 @@ use crate::tools::router::ToolRouterParams; use codex_app_server_protocol::AppInfo; use codex_features::Feature; use codex_features::Features; -use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_models_manager::bundled_models_response; use codex_models_manager::model_info::with_config_overrides; use codex_protocol::config_types::WebSearchMode; diff --git a/codex-rs/core/src/turn_timing.rs b/codex-rs/core/src/turn_timing.rs index a4451a52f9..6c47d3b528 100644 --- a/codex-rs/core/src/turn_timing.rs +++ b/codex-rs/core/src/turn_timing.rs @@ -3,8 +3,8 @@ use std::time::Instant; use std::time::SystemTime; use std::time::UNIX_EPOCH; -use codex_otel::metrics::names::TURN_TTFM_DURATION_METRIC; -use codex_otel::metrics::names::TURN_TTFT_DURATION_METRIC; +use codex_otel::TURN_TTFM_DURATION_METRIC; +use codex_otel::TURN_TTFT_DURATION_METRIC; use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use tokio::sync::Mutex; diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index 789b1ce34a..65230b1a17 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -363,7 +363,7 @@ fn emit_windows_sandbox_setup_success_metrics( originator_tag: &str, duration: std::time::Duration, ) { - let Some(metrics) = codex_otel::metrics::global() else { + let Some(metrics) = codex_otel::global() else { return; }; let mode_tag = windows_sandbox_setup_mode_tag(mode); @@ -389,7 +389,7 @@ fn emit_windows_sandbox_setup_failure_metrics( duration: std::time::Duration, _err: &anyhow::Error, ) { - let Some(metrics) = codex_otel::metrics::global() else { + let Some(metrics) = codex_otel::global() else { return; }; let mode_tag = windows_sandbox_setup_mode_tag(mode); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 0a1195a11b..8bf45a23dd 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -10,11 +10,11 @@ use codex_features::Feature; use codex_login::CodexAuth; use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::WireApi; +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; use codex_otel::current_span_w3c_trace_context; -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::config_types::ReasoningSummary; diff --git a/codex-rs/core/tests/suite/pending_input.rs b/codex-rs/core/tests/suite/pending_input.rs index 2fc5bf4e34..25a08120ae 100644 --- a/codex-rs/core/tests/suite/pending_input.rs +++ b/codex-rs/core/tests/suite/pending_input.rs @@ -101,6 +101,19 @@ async fn submit_user_input(codex: &CodexThread, text: &str) { .unwrap_or_else(|err| panic!("submit user input: {err}")); } +async fn steer_user_input(codex: &CodexThread, text: &str) { + codex + .steer_input( + vec![UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }], + /*expected_turn_id*/ None, + ) + .await + .unwrap_or_else(|err| panic!("steer user input: {err:?}")); +} + async fn submit_queue_only_agent_mail(codex: &CodexThread, text: &str) { codex .submit(Op::InterAgentCommunication { @@ -410,7 +423,7 @@ async fn user_input_does_not_preempt_after_reasoning_item() { wait_for_reasoning_item_started(&codex).await; - submit_user_input(&codex, "second prompt").await; + steer_user_input(&codex, "second prompt").await; let _ = gate_reasoning_done_tx.send(()); diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 346e8e9e5e..8c849ca806 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -7,8 +7,8 @@ mod cli; mod event_processor; mod event_processor_with_human_output; -pub mod event_processor_with_jsonl_output; -pub mod exec_events; +pub(crate) mod event_processor_with_jsonl_output; +pub(crate) mod exec_events; pub use cli::Cli; pub use cli::Command; @@ -85,7 +85,42 @@ use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_oss::ensure_oss_provider_ready; use codex_utils_oss::get_default_model_for_oss_provider; use event_processor_with_human_output::EventProcessorWithHumanOutput; -use event_processor_with_jsonl_output::EventProcessorWithJsonOutput; +pub use event_processor_with_jsonl_output::CodexStatus; +pub use event_processor_with_jsonl_output::CollectedThreadEvents; +pub use event_processor_with_jsonl_output::EventProcessorWithJsonOutput; +pub use exec_events::AgentMessageItem; +pub use exec_events::CollabAgentState; +pub use exec_events::CollabAgentStatus; +pub use exec_events::CollabTool; +pub use exec_events::CollabToolCallItem; +pub use exec_events::CollabToolCallStatus; +pub use exec_events::CommandExecutionItem; +pub use exec_events::CommandExecutionStatus; +pub use exec_events::ErrorItem; +pub use exec_events::FileChangeItem; +pub use exec_events::FileUpdateChange; +pub use exec_events::ItemCompletedEvent; +pub use exec_events::ItemStartedEvent; +pub use exec_events::ItemUpdatedEvent; +pub use exec_events::McpToolCallItem; +pub use exec_events::McpToolCallItemError; +pub use exec_events::McpToolCallItemResult; +pub use exec_events::McpToolCallStatus; +pub use exec_events::PatchApplyStatus; +pub use exec_events::PatchChangeKind; +pub use exec_events::ReasoningItem; +pub use exec_events::ThreadErrorEvent; +pub use exec_events::ThreadEvent; +pub use exec_events::ThreadItem as ExecThreadItem; +pub use exec_events::ThreadItemDetails; +pub use exec_events::ThreadStartedEvent; +pub use exec_events::TodoItem; +pub use exec_events::TodoListItem; +pub use exec_events::TurnCompletedEvent; +pub use exec_events::TurnFailedEvent; +pub use exec_events::TurnStartedEvent; +pub use exec_events::Usage; +pub use exec_events::WebSearchItem; use serde_json::Value; use std::collections::HashMap; use std::io::IsTerminal; @@ -105,7 +140,6 @@ use tracing_subscriber::prelude::*; use uuid::Uuid; use crate::cli::Command as ExecCommand; -use crate::event_processor::CodexStatus; use crate::event_processor::EventProcessor; const DEFAULT_ANALYTICS_ENABLED: bool = true; diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index c22207c914..a6b25b66b8 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -37,42 +37,42 @@ use codex_protocol::protocol::SessionConfiguredEvent; use pretty_assertions::assert_eq; use serde_json::json; -use codex_exec::event_processor_with_jsonl_output::CodexStatus; -use codex_exec::event_processor_with_jsonl_output::CollectedThreadEvents; -use codex_exec::event_processor_with_jsonl_output::EventProcessorWithJsonOutput; -use codex_exec::exec_events::AgentMessageItem; -use codex_exec::exec_events::CollabAgentState; -use codex_exec::exec_events::CollabAgentStatus; -use codex_exec::exec_events::CollabTool; -use codex_exec::exec_events::CollabToolCallItem; -use codex_exec::exec_events::CollabToolCallStatus; -use codex_exec::exec_events::CommandExecutionItem; -use codex_exec::exec_events::CommandExecutionStatus; -use codex_exec::exec_events::ErrorItem; -use codex_exec::exec_events::FileChangeItem; -use codex_exec::exec_events::FileUpdateChange as ExecFileUpdateChange; -use codex_exec::exec_events::ItemCompletedEvent; -use codex_exec::exec_events::ItemStartedEvent; -use codex_exec::exec_events::ItemUpdatedEvent; -use codex_exec::exec_events::McpToolCallItem; -use codex_exec::exec_events::McpToolCallItemError; -use codex_exec::exec_events::McpToolCallItemResult; -use codex_exec::exec_events::McpToolCallStatus; -use codex_exec::exec_events::PatchApplyStatus; -use codex_exec::exec_events::PatchChangeKind; -use codex_exec::exec_events::ReasoningItem; -use codex_exec::exec_events::ThreadErrorEvent; -use codex_exec::exec_events::ThreadEvent; -use codex_exec::exec_events::ThreadItem as ExecThreadItem; -use codex_exec::exec_events::ThreadItemDetails; -use codex_exec::exec_events::ThreadStartedEvent; -use codex_exec::exec_events::TodoItem; -use codex_exec::exec_events::TodoListItem; -use codex_exec::exec_events::TurnCompletedEvent; -use codex_exec::exec_events::TurnFailedEvent; -use codex_exec::exec_events::TurnStartedEvent; -use codex_exec::exec_events::Usage; -use codex_exec::exec_events::WebSearchItem; +use codex_exec::AgentMessageItem; +use codex_exec::CodexStatus; +use codex_exec::CollabAgentState; +use codex_exec::CollabAgentStatus; +use codex_exec::CollabTool; +use codex_exec::CollabToolCallItem; +use codex_exec::CollabToolCallStatus; +use codex_exec::CollectedThreadEvents; +use codex_exec::CommandExecutionItem; +use codex_exec::CommandExecutionStatus; +use codex_exec::ErrorItem; +use codex_exec::EventProcessorWithJsonOutput; +use codex_exec::ExecThreadItem; +use codex_exec::FileChangeItem; +use codex_exec::FileUpdateChange as ExecFileUpdateChange; +use codex_exec::ItemCompletedEvent; +use codex_exec::ItemStartedEvent; +use codex_exec::ItemUpdatedEvent; +use codex_exec::McpToolCallItem; +use codex_exec::McpToolCallItemError; +use codex_exec::McpToolCallItemResult; +use codex_exec::McpToolCallStatus; +use codex_exec::PatchApplyStatus; +use codex_exec::PatchChangeKind; +use codex_exec::ReasoningItem; +use codex_exec::ThreadErrorEvent; +use codex_exec::ThreadEvent; +use codex_exec::ThreadItemDetails; +use codex_exec::ThreadStartedEvent; +use codex_exec::TodoItem; +use codex_exec::TodoListItem; +use codex_exec::TurnCompletedEvent; +use codex_exec::TurnFailedEvent; +use codex_exec::TurnStartedEvent; +use codex_exec::Usage; +use codex_exec::WebSearchItem; #[test] fn map_todo_items_preserves_text_and_completion_state() { diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index 70f5197e82..ee53e7d437 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -42,7 +42,7 @@ async fn spawn_command_under_sandbox( stdio_policy: StdioPolicy, env: HashMap, ) -> std::io::Result { - use codex_core::landlock::spawn_command_under_linux_sandbox; + 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( diff --git a/codex-rs/execpolicy/src/amend.rs b/codex-rs/execpolicy/src/amend.rs index 7909fc14a4..e25fd1bd91 100644 --- a/codex-rs/execpolicy/src/amend.rs +++ b/codex-rs/execpolicy/src/amend.rs @@ -9,7 +9,6 @@ use std::path::PathBuf; use crate::decision::Decision; use crate::rule::NetworkRuleProtocol; use crate::rule::normalize_network_rule_host; -use serde_json; use thiserror::Error; #[derive(Debug, Error)] diff --git a/codex-rs/execpolicy/src/lib.rs b/codex-rs/execpolicy/src/lib.rs index 8cb89c36e4..128c9dd41e 100644 --- a/codex-rs/execpolicy/src/lib.rs +++ b/codex-rs/execpolicy/src/lib.rs @@ -1,11 +1,11 @@ -pub mod amend; -pub mod decision; -pub mod error; -pub mod execpolicycheck; +pub(crate) mod amend; +pub(crate) mod decision; +pub(crate) mod error; +pub(crate) mod execpolicycheck; mod executable_name; -pub mod parser; -pub mod policy; -pub mod rule; +pub(crate) mod parser; +pub(crate) mod policy; +pub(crate) mod rule; pub use amend::AmendError; pub use amend::blocking_append_allow_prefix_rule; @@ -22,6 +22,9 @@ pub use policy::Evaluation; pub use policy::MatchOptions; pub use policy::Policy; pub use rule::NetworkRuleProtocol; +pub use rule::PatternToken; +pub use rule::PrefixPattern; +pub use rule::PrefixRule; pub use rule::Rule; pub use rule::RuleMatch; pub use rule::RuleRef; diff --git a/codex-rs/execpolicy/src/main.rs b/codex-rs/execpolicy/src/main.rs index d3b34a3307..82e1bc12c4 100644 --- a/codex-rs/execpolicy/src/main.rs +++ b/codex-rs/execpolicy/src/main.rs @@ -1,6 +1,6 @@ use anyhow::Result; use clap::Parser; -use codex_execpolicy::execpolicycheck::ExecPolicyCheckCommand; +use codex_execpolicy::ExecPolicyCheckCommand; /// CLI for evaluating exec policies #[derive(Parser)] diff --git a/codex-rs/execpolicy/src/parser.rs b/codex-rs/execpolicy/src/parser.rs index 46764d0e07..5d01df18bb 100644 --- a/codex-rs/execpolicy/src/parser.rs +++ b/codex-rs/execpolicy/src/parser.rs @@ -1,6 +1,5 @@ use codex_utils_absolute_path::AbsolutePathBuf; use multimap::MultiMap; -use shlex; use starlark::any::ProvidesStaticType; use starlark::codemap::FileSpan; use starlark::environment::GlobalsBuilder; diff --git a/codex-rs/execpolicy/tests/basic.rs b/codex-rs/execpolicy/tests/basic.rs index bef845da67..50c3f5361f 100644 --- a/codex-rs/execpolicy/tests/basic.rs +++ b/codex-rs/execpolicy/tests/basic.rs @@ -10,14 +10,14 @@ use codex_execpolicy::Error; use codex_execpolicy::Evaluation; use codex_execpolicy::MatchOptions; use codex_execpolicy::NetworkRuleProtocol; +use codex_execpolicy::PatternToken; use codex_execpolicy::Policy; use codex_execpolicy::PolicyParser; +use codex_execpolicy::PrefixPattern; +use codex_execpolicy::PrefixRule; use codex_execpolicy::RuleMatch; use codex_execpolicy::RuleRef; use codex_execpolicy::blocking_append_allow_prefix_rule; -use codex_execpolicy::rule::PatternToken; -use codex_execpolicy::rule::PrefixPattern; -use codex_execpolicy::rule::PrefixRule; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use tempfile::tempdir; diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 8d9489dbe6..712aeee219 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -14,8 +14,6 @@ use anyhow::anyhow; use codex_login::AuthEnvTelemetry; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; -use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; -use feedback_diagnostics::FeedbackDiagnostics; use tracing::Event; use tracing::Level; use tracing::field::Visit; @@ -24,7 +22,10 @@ use tracing_subscriber::filter::Targets; use tracing_subscriber::fmt::writer::MakeWriter; use tracing_subscriber::registry::LookupSpan; -pub mod feedback_diagnostics; +pub(crate) mod feedback_diagnostics; +pub use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; +pub use feedback_diagnostics::FeedbackDiagnostic; +pub use feedback_diagnostics::FeedbackDiagnostics; const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB const SENTRY_DSN: &str = @@ -609,7 +610,7 @@ mod tests { use std::fs; use super::*; - use feedback_diagnostics::FeedbackDiagnostic; + use crate::FeedbackDiagnostic; use pretty_assertions::assert_eq; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; diff --git a/codex-rs/hooks/src/lib.rs b/codex-rs/hooks/src/lib.rs index 16334a6476..784b414427 100644 --- a/codex-rs/hooks/src/lib.rs +++ b/codex-rs/hooks/src/lib.rs @@ -1,5 +1,5 @@ mod engine; -pub mod events; +pub(crate) mod events; mod legacy_notify; mod registry; mod schema; diff --git a/codex-rs/login/src/api_bridge.rs b/codex-rs/login/src/api_bridge.rs index 4c432ff18d..d8b9dbb77c 100644 --- a/codex-rs/login/src/api_bridge.rs +++ b/codex-rs/login/src/api_bridge.rs @@ -1,4 +1,4 @@ -use codex_api::api_bridge::CoreAuthProvider; +use codex_api::CoreAuthProvider; use codex_model_provider_info::ModelProviderInfo; use crate::CodexAuth; diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index f786884b34..1b52223bc3 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -9,6 +9,7 @@ mod pkce; mod server; pub use codex_client::BuildCustomCaTransportError as BuildLoginHttpClientError; +pub use codex_config::types::AuthCredentialsStoreMode; pub use device_code_auth::DeviceCode; pub use device_code_auth::complete_device_code_login; pub use device_code_auth::request_device_code; diff --git a/codex-rs/model-provider-info/src/lib.rs b/codex-rs/model-provider-info/src/lib.rs index 968bcc8ed0..f39ff0c7fe 100644 --- a/codex-rs/model-provider-info/src/lib.rs +++ b/codex-rs/model-provider-info/src/lib.rs @@ -6,7 +6,7 @@ //! key. These override or extend the defaults at runtime. use codex_api::Provider as ApiProvider; -use codex_api::provider::RetryConfig as ApiRetryConfig; +use codex_api::RetryConfig as ApiRetryConfig; use codex_app_server_protocol::AuthMode; use codex_protocol::config_types::ModelProviderAuthInfo; use codex_protocol::error::CodexErr; diff --git a/codex-rs/models-manager/src/lib.rs b/codex-rs/models-manager/src/lib.rs index a9c0d489d3..e99c33edb9 100644 --- a/codex-rs/models-manager/src/lib.rs +++ b/codex-rs/models-manager/src/lib.rs @@ -1,6 +1,6 @@ -pub mod cache; +pub(crate) mod cache; pub mod collaboration_mode_presets; -pub mod config; +pub(crate) mod config; pub mod manager; pub mod model_info; pub mod model_presets; diff --git a/codex-rs/models-manager/src/manager.rs b/codex-rs/models-manager/src/manager.rs index 984c612296..a7d4aa12ab 100644 --- a/codex-rs/models-manager/src/manager.rs +++ b/codex-rs/models-manager/src/manager.rs @@ -7,7 +7,7 @@ use codex_api::ModelsClient; use codex_api::RequestTelemetry; use codex_api::ReqwestTransport; use codex_api::TransportError; -use codex_api::api_bridge::map_api_error; +use codex_api::map_api_error; use codex_app_server_protocol::AuthMode; use codex_feedback::FeedbackRequestTags; use codex_feedback::emit_feedback_request_tags_with_auth_env; diff --git a/codex-rs/otel/src/events/session_telemetry.rs b/codex-rs/otel/src/events/session_telemetry.rs index 42fd6e50c3..b1bf9b0947 100644 --- a/codex-rs/otel/src/events/session_telemetry.rs +++ b/codex-rs/otel/src/events/session_telemetry.rs @@ -3,29 +3,29 @@ use crate::ToolDecisionSource; use crate::events::shared::log_and_trace_event; use crate::events::shared::log_event; use crate::events::shared::trace_event; +use crate::metrics::API_CALL_COUNT_METRIC; +use crate::metrics::API_CALL_DURATION_METRIC; use crate::metrics::MetricsClient; use crate::metrics::MetricsConfig; use crate::metrics::MetricsError; +use crate::metrics::PROFILE_USAGE_METRIC; +use crate::metrics::RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC; +use crate::metrics::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC; +use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC; +use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC; +use crate::metrics::RESPONSES_API_INFERENCE_TIME_DURATION_METRIC; +use crate::metrics::RESPONSES_API_OVERHEAD_DURATION_METRIC; use crate::metrics::Result as MetricsResult; -use crate::metrics::names::API_CALL_COUNT_METRIC; -use crate::metrics::names::API_CALL_DURATION_METRIC; -use crate::metrics::names::PROFILE_USAGE_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_INFERENCE_TIME_DURATION_METRIC; -use crate::metrics::names::RESPONSES_API_OVERHEAD_DURATION_METRIC; -use crate::metrics::names::SSE_EVENT_COUNT_METRIC; -use crate::metrics::names::SSE_EVENT_DURATION_METRIC; -use crate::metrics::names::TOOL_CALL_COUNT_METRIC; -use crate::metrics::names::TOOL_CALL_DURATION_METRIC; -use crate::metrics::names::WEBSOCKET_EVENT_COUNT_METRIC; -use crate::metrics::names::WEBSOCKET_EVENT_DURATION_METRIC; -use crate::metrics::names::WEBSOCKET_REQUEST_COUNT_METRIC; -use crate::metrics::names::WEBSOCKET_REQUEST_DURATION_METRIC; +use crate::metrics::SSE_EVENT_COUNT_METRIC; +use crate::metrics::SSE_EVENT_DURATION_METRIC; +use crate::metrics::SessionMetricTagValues; +use crate::metrics::TOOL_CALL_COUNT_METRIC; +use crate::metrics::TOOL_CALL_DURATION_METRIC; +use crate::metrics::WEBSOCKET_EVENT_COUNT_METRIC; +use crate::metrics::WEBSOCKET_EVENT_DURATION_METRIC; +use crate::metrics::WEBSOCKET_REQUEST_COUNT_METRIC; +use crate::metrics::WEBSOCKET_REQUEST_DURATION_METRIC; use crate::metrics::runtime_metrics::RuntimeMetricsSummary; -use crate::metrics::tags::SessionMetricTagValues; use crate::metrics::timer::Timer; use crate::provider::OtelProvider; use crate::sanitize_metric_tag_value; diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index ea13ad9b96..c7d0b7c419 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -1,23 +1,27 @@ -pub mod config; +pub(crate) mod config; mod events; -pub mod metrics; -pub mod provider; -pub mod trace_context; +pub(crate) mod metrics; +pub(crate) mod provider; +pub(crate) mod trace_context; mod otlp; mod targets; -use crate::metrics::MetricsError; use crate::metrics::Result as MetricsResult; use serde::Serialize; use strum_macros::Display; +pub use crate::config::OtelExporter; +pub use crate::config::OtelHttpProtocol; +pub use crate::config::OtelSettings; +pub use crate::config::OtelTlsConfig; pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata; pub use crate::events::session_telemetry::SessionTelemetry; pub use crate::events::session_telemetry::SessionTelemetryMetadata; pub use crate::metrics::runtime_metrics::RuntimeMetricTotals; pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary; pub use crate::metrics::timer::Timer; +pub use crate::metrics::*; pub use crate::provider::OtelProvider; pub use crate::trace_context::context_from_w3c_trace_context; pub use crate::trace_context::current_span_trace_id; diff --git a/codex-rs/otel/src/metrics/mod.rs b/codex-rs/otel/src/metrics/mod.rs index 1d1195e5fe..bcbb85d35c 100644 --- a/codex-rs/otel/src/metrics/mod.rs +++ b/codex-rs/otel/src/metrics/mod.rs @@ -1,9 +1,9 @@ mod client; mod config; mod error; -pub mod names; +pub(crate) mod names; pub(crate) mod runtime_metrics; -pub mod tags; +pub(crate) mod tags; pub(crate) mod timer; pub(crate) mod validation; @@ -12,7 +12,9 @@ pub use crate::metrics::config::MetricsConfig; pub use crate::metrics::config::MetricsExporter; pub use crate::metrics::error::MetricsError; pub use crate::metrics::error::Result; +pub use names::*; use std::sync::OnceLock; +pub use tags::SessionMetricTagValues; static GLOBAL_METRICS: OnceLock = OnceLock::new(); diff --git a/codex-rs/otel/tests/harness/mod.rs b/codex-rs/otel/tests/harness/mod.rs index acdba0b7e1..fbba56411c 100644 --- a/codex-rs/otel/tests/harness/mod.rs +++ b/codex-rs/otel/tests/harness/mod.rs @@ -1,6 +1,6 @@ -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::Result; +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; +use codex_otel::Result; use opentelemetry::KeyValue; use opentelemetry_sdk::metrics::InMemoryMetricExporter; use opentelemetry_sdk::metrics::data::AggregatedMetrics; diff --git a/codex-rs/otel/tests/suite/manager_metrics.rs b/codex-rs/otel/tests/suite/manager_metrics.rs index 8a61403c77..d95f42dfc5 100644 --- a/codex-rs/otel/tests/suite/manager_metrics.rs +++ b/codex-rs/otel/tests/suite/manager_metrics.rs @@ -2,9 +2,9 @@ use crate::harness::attributes_to_map; use crate::harness::build_metrics_with_defaults; use crate::harness::find_metric; use crate::harness::latest_metrics; +use codex_otel::Result; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; -use codex_otel::metrics::Result; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use opentelemetry_sdk::metrics::data::AggregatedMetrics; diff --git a/codex-rs/otel/tests/suite/otlp_http_loopback.rs b/codex-rs/otel/tests/suite/otlp_http_loopback.rs index eb84dfdf5b..fd4e3531d8 100644 --- a/codex-rs/otel/tests/suite/otlp_http_loopback.rs +++ b/codex-rs/otel/tests/suite/otlp_http_loopback.rs @@ -1,10 +1,10 @@ +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; +use codex_otel::OtelExporter; +use codex_otel::OtelHttpProtocol; use codex_otel::OtelProvider; -use codex_otel::config::OtelExporter; -use codex_otel::config::OtelHttpProtocol; -use codex_otel::config::OtelSettings; -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::Result; +use codex_otel::OtelSettings; +use codex_otel::Result; use std::collections::HashMap; use std::io::Read as _; use std::io::Write as _; diff --git a/codex-rs/otel/tests/suite/runtime_summary.rs b/codex-rs/otel/tests/suite/runtime_summary.rs index 7ffa03e026..21fc7bf76c 100644 --- a/codex-rs/otel/tests/suite/runtime_summary.rs +++ b/codex-rs/otel/tests/suite/runtime_summary.rs @@ -1,10 +1,10 @@ +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; +use codex_otel::Result; use codex_otel::RuntimeMetricTotals; use codex_otel::RuntimeMetricsSummary; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::Result; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use eventsource_stream::Event as StreamEvent; diff --git a/codex-rs/otel/tests/suite/send.rs b/codex-rs/otel/tests/suite/send.rs index a50c579089..fc382bf88a 100644 --- a/codex-rs/otel/tests/suite/send.rs +++ b/codex-rs/otel/tests/suite/send.rs @@ -3,7 +3,7 @@ use crate::harness::build_metrics_with_defaults; use crate::harness::find_metric; use crate::harness::histogram_data; use crate::harness::latest_metrics; -use codex_otel::metrics::Result; +use codex_otel::Result; use pretty_assertions::assert_eq; use std::collections::BTreeMap; diff --git a/codex-rs/otel/tests/suite/snapshot.rs b/codex-rs/otel/tests/suite/snapshot.rs index 4686e79d3d..e631100004 100644 --- a/codex-rs/otel/tests/suite/snapshot.rs +++ b/codex-rs/otel/tests/suite/snapshot.rs @@ -1,10 +1,10 @@ use crate::harness::attributes_to_map; use crate::harness::find_metric; +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; +use codex_otel::Result; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::Result; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use opentelemetry_sdk::metrics::InMemoryMetricExporter; diff --git a/codex-rs/otel/tests/suite/timing.rs b/codex-rs/otel/tests/suite/timing.rs index 8398e1a0d7..0cf73b9a56 100644 --- a/codex-rs/otel/tests/suite/timing.rs +++ b/codex-rs/otel/tests/suite/timing.rs @@ -2,7 +2,7 @@ use crate::harness::attributes_to_map; use crate::harness::build_metrics_with_defaults; use crate::harness::histogram_data; use crate::harness::latest_metrics; -use codex_otel::metrics::Result; +use codex_otel::Result; use pretty_assertions::assert_eq; use std::time::Duration; diff --git a/codex-rs/otel/tests/suite/validation.rs b/codex-rs/otel/tests/suite/validation.rs index 81f07ed147..6308506112 100644 --- a/codex-rs/otel/tests/suite/validation.rs +++ b/codex-rs/otel/tests/suite/validation.rs @@ -1,7 +1,7 @@ -use codex_otel::metrics::MetricsClient; -use codex_otel::metrics::MetricsConfig; -use codex_otel::metrics::MetricsError; -use codex_otel::metrics::Result; +use codex_otel::MetricsClient; +use codex_otel::MetricsConfig; +use codex_otel::MetricsError; +use codex_otel::Result; use opentelemetry_sdk::metrics::InMemoryMetricExporter; fn build_in_memory_client() -> Result { diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index d4e568fea9..0f18b68393 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -27,7 +27,7 @@ use crate::user_input::UserInput; use codex_execpolicy::Policy; use codex_git_utils::GhostCommit; use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_image::error::ImageProcessingError; +use codex_utils_image::ImageProcessingError; use schemars::JsonSchema; use crate::mcp::CallToolResult; diff --git a/codex-rs/response-debug-context/src/lib.rs b/codex-rs/response-debug-context/src/lib.rs index ed5a6bdc6f..f7c90b7533 100644 --- a/codex-rs/response-debug-context/src/lib.rs +++ b/codex-rs/response-debug-context/src/lib.rs @@ -1,6 +1,6 @@ use base64::Engine; +use codex_api::ApiError; use codex_api::TransportError; -use codex_api::error::ApiError; const REQUEST_ID_HEADER: &str = "x-request-id"; const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id"; @@ -91,8 +91,8 @@ mod tests { use super::extract_response_debug_context; use super::telemetry_api_error_message; use super::telemetry_transport_error_message; + use codex_api::ApiError; use codex_api::TransportError; - use codex_api::error::ApiError; use http::HeaderMap; use http::HeaderValue; use http::StatusCode; diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs index 160792a390..6acf2c3be4 100644 --- a/codex-rs/rollout/src/lib.rs +++ b/codex-rs/rollout/src/lib.rs @@ -4,12 +4,12 @@ use std::sync::LazyLock; use codex_protocol::protocol::SessionSource; -pub mod config; -pub mod list; -pub mod metadata; -pub mod policy; -pub mod recorder; -pub mod session_index; +pub(crate) mod config; +pub(crate) mod list; +pub(crate) mod metadata; +pub(crate) mod policy; +pub(crate) mod recorder; +pub(crate) mod session_index; pub mod state_db; pub(crate) mod default_client { @@ -30,14 +30,28 @@ pub static INTERACTIVE_SESSION_SOURCES: LazyLock> = LazyLock: }); pub use codex_protocol::protocol::SessionMeta; +pub use config::Config; pub use config::RolloutConfig; pub use config::RolloutConfigView; +pub use list::Cursor; +pub use list::ThreadItem; +pub use list::ThreadListConfig; +pub use list::ThreadListLayout; +pub use list::ThreadSortKey; +pub use list::ThreadsPage; pub use list::find_archived_thread_path_by_id_str; pub use list::find_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use list::find_thread_path_by_id_str as find_conversation_path_by_id_str; +pub use list::get_threads; +pub use list::get_threads_in_root; +pub use list::parse_cursor; +pub use list::read_head_for_summary; +pub use list::read_session_meta_line; pub use list::rollout_date_parts; +pub use metadata::builder_from_items; pub use policy::EventPersistenceMode; +pub use policy::should_persist_response_item_for_memories; pub use recorder::RolloutRecorder; pub use recorder::RolloutRecorderParams; pub use session_index::append_thread_name; diff --git a/codex-rs/rollout/src/metadata.rs b/codex-rs/rollout/src/metadata.rs index 51ebb5ef1e..e8a95839d7 100644 --- a/codex-rs/rollout/src/metadata.rs +++ b/codex-rs/rollout/src/metadata.rs @@ -137,7 +137,7 @@ pub(crate) async fn backfill_sessions( runtime: &codex_state::StateRuntime, config: &impl RolloutConfigView, ) { - let metric_client = codex_otel::metrics::global(); + let metric_client = codex_otel::global(); let timer = metric_client .as_ref() .and_then(|otel| otel.start_timer(DB_METRIC_BACKFILL_DURATION_MS, &[]).ok()); diff --git a/codex-rs/shell-command/src/command_safety/mod.rs b/codex-rs/shell-command/src/command_safety/mod.rs index 12e467bdbe..31fa64f8af 100644 --- a/codex-rs/shell-command/src/command_safety/mod.rs +++ b/codex-rs/shell-command/src/command_safety/mod.rs @@ -2,4 +2,4 @@ mod powershell_parser; pub mod is_dangerous_command; pub mod is_safe_command; -pub mod windows_safe_commands; +pub(crate) mod windows_safe_commands; diff --git a/codex-rs/shell-command/src/lib.rs b/codex-rs/shell-command/src/lib.rs index 215c30fd7d..1d9e302a4e 100644 --- a/codex-rs/shell-command/src/lib.rs +++ b/codex-rs/shell-command/src/lib.rs @@ -3,7 +3,7 @@ mod shell_detect; pub mod bash; -pub mod command_safety; +pub(crate) mod command_safety; pub mod parse_command; pub mod powershell; diff --git a/codex-rs/shell-escalation/src/lib.rs b/codex-rs/shell-escalation/src/lib.rs index edad193afd..6c7e1ec605 100644 --- a/codex-rs/shell-escalation/src/lib.rs +++ b/codex-rs/shell-escalation/src/lib.rs @@ -1,6 +1,8 @@ #[cfg(unix)] mod unix; +#[cfg(unix)] +pub use unix::ESCALATE_SOCKET_ENV_VAR; #[cfg(unix)] pub use unix::EscalateAction; #[cfg(unix)] @@ -28,8 +30,6 @@ pub use unix::ShellCommandExecutor; #[cfg(unix)] pub use unix::Stopwatch; #[cfg(unix)] -pub use unix::escalate_protocol::ESCALATE_SOCKET_ENV_VAR; -#[cfg(unix)] pub use unix::main_execve_wrapper; #[cfg(unix)] pub use unix::run_shell_escalation_execve_wrapper; diff --git a/codex-rs/shell-escalation/src/unix/mod.rs b/codex-rs/shell-escalation/src/unix/mod.rs index 13b7146ab4..b5d999411c 100644 --- a/codex-rs/shell-escalation/src/unix/mod.rs +++ b/codex-rs/shell-escalation/src/unix/mod.rs @@ -53,15 +53,16 @@ //! | | //! o<-----x //! -pub mod escalate_client; -pub mod escalate_protocol; -pub mod escalate_server; -pub mod escalation_policy; -pub mod execve_wrapper; -pub mod socket; -pub mod stopwatch; +pub(crate) mod escalate_client; +pub(crate) mod escalate_protocol; +pub(crate) mod escalate_server; +pub(crate) mod escalation_policy; +pub(crate) mod execve_wrapper; +pub(crate) mod socket; +pub(crate) mod stopwatch; pub use self::escalate_client::run_shell_escalation_execve_wrapper; +pub use self::escalate_protocol::ESCALATE_SOCKET_ENV_VAR; pub use self::escalate_protocol::EscalateAction; pub use self::escalate_protocol::EscalationDecision; pub use self::escalate_protocol::EscalationExecution; diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index cf42e85160..5bd7bb7efe 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -85,13 +85,14 @@ use codex_app_server_protocol::TurnError as AppServerTurnError; use codex_app_server_protocol::TurnStatus; use codex_config::types::ApprovalsReviewer; use codex_config::types::ModelAvailabilityNuxConfig; +use codex_core::append_message_history_entry; use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config_loader::ConfigLayerStackOrdering; -use codex_core::message_history; +use codex_core::lookup_message_history_entry; #[cfg(target_os = "windows")] use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_features::Feature; @@ -2159,8 +2160,7 @@ impl App { let text = text.clone(); let config = self.chat_widget.config_ref().clone(); tokio::spawn(async move { - if let Err(err) = - message_history::append_entry(&text, &thread_id, &config).await + if let Err(err) = append_message_history_entry(&text, &thread_id, &config).await { tracing::warn!( thread_id = %thread_id, @@ -2178,7 +2178,7 @@ impl App { let app_event_tx = self.app_event_tx.clone(); tokio::spawn(async move { let entry_opt = tokio::task::spawn_blocking(move || { - message_history::lookup(log_id, offset, &config) + lookup_message_history_entry(log_id, offset, &config) }) .await .unwrap_or_else(|err| { @@ -4693,7 +4693,7 @@ impl App { tokio::task::spawn_blocking(move || { let requested_path = PathBuf::from(path); - let event = match codex_core::windows_sandbox_read_grants::grant_read_root_non_elevated( + let event = match codex_core::grant_read_root_non_elevated( &policy, policy_cwd.as_path(), command_cwd.as_path(), diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index d152e99f68..03072632bc 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -63,8 +63,10 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::TurnSteerResponse; +#[cfg(test)] +use codex_core::append_message_history_entry; use codex_core::config::Config; -use codex_core::message_history; +use codex_core::message_history_metadata; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; use codex_protocol::openai_models::ModelAvailabilityNux; @@ -1076,7 +1078,7 @@ async fn thread_session_state_from_thread_response( .map(ThreadId::from_string) .transpose() .map_err(|err| format!("forked_from_id is invalid: {err}"))?; - let (history_log_id, history_entry_count) = message_history::history_metadata(config).await; + let (history_log_id, history_entry_count) = message_history_metadata(config).await; let history_entry_count = u64::try_from(history_entry_count).unwrap_or(u64::MAX); Ok(ThreadSessionState { @@ -1316,10 +1318,10 @@ mod tests { let config = build_config(&temp_dir).await; let thread_id = ThreadId::new(); - message_history::append_entry("older", &thread_id, &config) + append_message_history_entry("older", &thread_id, &config) .await .expect("history append should succeed"); - message_history::append_entry("newer", &thread_id, &config) + append_message_history_entry("newer", &thread_id, &config) .await .expect("history append should succeed"); diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index f4f641c5d5..b1889abca0 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -1,5 +1,5 @@ -use codex_feedback::feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; -use codex_feedback::feedback_diagnostics::FeedbackDiagnostics; +use codex_feedback::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; +use codex_feedback::FeedbackDiagnostics; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; @@ -556,7 +556,7 @@ mod tests { use super::*; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; - use codex_feedback::feedback_diagnostics::FeedbackDiagnostic; + use codex_feedback::FeedbackDiagnostic; use pretty_assertions::assert_eq; fn render(view: &FeedbackNoteView, width: u16) -> String { diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index da5e2421f7..cbb698e3a2 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -76,7 +76,7 @@ pub(crate) struct MentionBinding { mod chat_composer; mod chat_composer_history; mod command_popup; -pub mod custom_prompt_view; +pub(crate) mod custom_prompt_view; mod experimental_features_view; mod file_search_popup; mod footer; @@ -108,7 +108,7 @@ pub(crate) use title_setup::TerminalTitleSetupView; mod paste_burst; mod pending_input_preview; mod pending_thread_approvals; -pub mod popup_consts; +pub(crate) mod popup_consts; mod scroll_state; mod selection_popup_common; mod textarea; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index f942308aa7..e8713704d2 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -95,13 +95,13 @@ use codex_chatgpt::connectors; use codex_config::types::ApprovalsReviewer; use codex_config::types::Notifications; use codex_config::types::WindowsSandboxModeToml; +use codex_core::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::config::Config; use codex_core::config::Constrained; use codex_core::config::ConstraintResult; use codex_core::config_loader::ConfigLayerStackOrdering; use codex_core::find_thread_name_by_id; use codex_core::plugins::PluginsManager; -use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::skills::model::SkillMetadata; #[cfg(target_os = "windows")] use codex_core::windows_sandbox::WindowsSandboxLevelExt; diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index 53dd7e8b8e..b5794f6c4b 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -13,8 +13,8 @@ use crate::bottom_pane::popup_consts::standard_popup_hint_line; use crate::skills_helpers::skill_description; use crate::skills_helpers::skill_display_name; use codex_chatgpt::connectors::AppInfo; +use codex_core::TOOL_MENTION_SIGIL; use codex_core::connectors::connector_mention_slug; -use codex_core::mention_syntax::TOOL_MENTION_SIGIL; use codex_core::skills::model::SkillDependencies; use codex_core::skills::model::SkillInterface; use codex_core::skills::model::SkillMetadata; diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index f899267858..8d14d4dda6 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -1761,13 +1761,11 @@ async fn feedback_upload_consent_popup_snapshot() { chat.app_event_tx.clone(), crate::app_event::FeedbackCategory::Bug, chat.current_rollout_path.clone(), - &codex_feedback::feedback_diagnostics::FeedbackDiagnostics::new(vec![ - codex_feedback::feedback_diagnostics::FeedbackDiagnostic { - headline: "Proxy environment variables are set and may affect connectivity." - .to_string(), - details: vec!["HTTPS_PROXY = hello".to_string()], - }, - ]), + &codex_feedback::FeedbackDiagnostics::new(vec![codex_feedback::FeedbackDiagnostic { + headline: "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec!["HTTPS_PROXY = hello".to_string()], + }]), )); let popup = render_bottom_popup(&chat, /*width*/ 80); @@ -1782,13 +1780,11 @@ async fn feedback_good_result_consent_popup_includes_connectivity_diagnostics_fi chat.app_event_tx.clone(), crate::app_event::FeedbackCategory::GoodResult, chat.current_rollout_path.clone(), - &codex_feedback::feedback_diagnostics::FeedbackDiagnostics::new(vec![ - codex_feedback::feedback_diagnostics::FeedbackDiagnostic { - headline: "Proxy environment variables are set and may affect connectivity." - .to_string(), - details: vec!["HTTPS_PROXY = hello".to_string()], - }, - ]), + &codex_feedback::FeedbackDiagnostics::new(vec![codex_feedback::FeedbackDiagnostic { + headline: "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec!["HTTPS_PROXY = hello".to_string()], + }]), )); let popup = render_bottom_popup(&chat, /*width*/ 80); diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 6821adb5a8..67c7e9f98b 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -42,14 +42,14 @@ use base64::Engine; use codex_app_server_protocol::McpServerStatus; use codex_app_server_protocol::McpServerStatusDetail; use codex_config::types::McpServerTransportConfig; +#[cfg(test)] +use codex_core::McpManager; use codex_core::config::Config; #[cfg(test)] -use codex_core::mcp::McpManager; -#[cfg(test)] use codex_core::plugins::PluginsManager; -use codex_core::web_search::web_search_detail; +use codex_core::web_search_detail; #[cfg(test)] -use codex_mcp::mcp::qualified_mcp_tool_name_prefix; +use codex_mcp::qualified_mcp_tool_name_prefix; use codex_otel::RuntimeMetricsSummary; use codex_protocol::account::PlanType; use codex_protocol::config_types::ServiceTier; @@ -70,7 +70,7 @@ use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputQuestion; use codex_protocol::user_input::TextElement; -use codex_utils_cli::format_env_display::format_env_display; +use codex_utils_cli::format_env_display; use image::DynamicImage; use image::ImageReader; use ratatui::prelude::*; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 4e90c909e1..7cd4c64949 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -102,7 +102,8 @@ mod clipboard_paste; mod clipboard_text; mod collaboration_modes; mod color; -pub mod custom_terminal; +pub(crate) mod custom_terminal; +pub use custom_terminal::Terminal; mod cwd_prompt; mod debug_config; mod diff_render; @@ -113,10 +114,12 @@ mod file_search; mod frames; mod get_git_diff; mod history_cell; -pub mod insert_history; +pub(crate) mod insert_history; +pub use insert_history::insert_history_lines; mod key_hint; mod line_truncation; -pub mod live_wrap; +pub(crate) mod live_wrap; +pub use live_wrap::RowBuilder; mod local_chatgpt_auth; mod markdown; mod markdown_render; @@ -126,10 +129,10 @@ mod model_catalog; mod model_migration; mod multi_agents; mod notifications; -pub mod onboarding; +pub(crate) mod onboarding; mod oss_selection; mod pager_overlay; -pub mod public_widgets; +pub(crate) mod public_widgets; mod render; mod resume_picker; mod selection_list; @@ -148,7 +151,8 @@ mod theme_picker; mod tooltips; mod tui; mod ui_consts; -pub mod update_action; +pub(crate) mod update_action; +pub use update_action::UpdateAction; mod update_prompt; mod updates; mod version; @@ -212,7 +216,7 @@ mod voice { mod wrapping; #[cfg(test)] -pub mod test_backend; +pub(crate) mod test_backend; #[cfg(test)] pub(crate) mod test_support; diff --git a/codex-rs/tui/src/mention_codec.rs b/codex-rs/tui/src/mention_codec.rs index 6e95067ba4..d3d1ead4de 100644 --- a/codex-rs/tui/src/mention_codec.rs +++ b/codex-rs/tui/src/mention_codec.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use std::collections::VecDeque; -use codex_core::mention_syntax::PLUGIN_TEXT_MENTION_SIGIL; -use codex_core::mention_syntax::TOOL_MENTION_SIGIL; +use codex_core::PLUGIN_TEXT_MENTION_SIGIL; +use codex_core::TOOL_MENTION_SIGIL; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct LinkedMention { diff --git a/codex-rs/tui/src/onboarding/mod.rs b/codex-rs/tui/src/onboarding/mod.rs index 8a4dc760fa..0db5204d31 100644 --- a/codex-rs/tui/src/onboarding/mod.rs +++ b/codex-rs/tui/src/onboarding/mod.rs @@ -1,6 +1,5 @@ mod auth; -pub mod onboarding_screen; +pub(crate) mod onboarding_screen; mod trust_directory; pub(crate) use auth::mark_url_hyperlink; -pub use trust_directory::TrustDirectorySelection; mod welcome; diff --git a/codex-rs/tui/src/public_widgets/mod.rs b/codex-rs/tui/src/public_widgets/mod.rs index c752189f3b..b8db1c6bff 100644 --- a/codex-rs/tui/src/public_widgets/mod.rs +++ b/codex-rs/tui/src/public_widgets/mod.rs @@ -1 +1 @@ -pub mod composer_input; +pub(crate) mod composer_input; diff --git a/codex-rs/tui/src/render/mod.rs b/codex-rs/tui/src/render/mod.rs index a2e4920586..02c19fc9f7 100644 --- a/codex-rs/tui/src/render/mod.rs +++ b/codex-rs/tui/src/render/mod.rs @@ -1,8 +1,8 @@ use ratatui::layout::Rect; -pub mod highlight; -pub mod line_utils; -pub mod renderable; +pub(crate) mod highlight; +pub(crate) mod line_utils; +pub(crate) mod renderable; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Insets { diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 9f4c8f793b..76aaa3da1a 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -4,7 +4,7 @@ use crate::text_formatting; use chrono::DateTime; use chrono::Local; use codex_core::config::Config; -use codex_core::project_doc::discover_project_doc_paths; +use codex_core::discover_project_doc_paths; use codex_exec_server::LOCAL_FS; use codex_protocol::account::PlanType; use codex_utils_absolute_path::AbsolutePathBuf; diff --git a/codex-rs/tui/tests/suite/vt100_history.rs b/codex-rs/tui/tests/suite/vt100_history.rs index 2b89363e66..609671cc35 100644 --- a/codex-rs/tui/tests/suite/vt100_history.rs +++ b/codex-rs/tui/tests/suite/vt100_history.rs @@ -22,20 +22,20 @@ macro_rules! assert_contains { } struct TestScenario { - term: codex_tui::custom_terminal::Terminal, + term: codex_tui::Terminal, } impl TestScenario { fn new(width: u16, height: u16, viewport: Rect) -> Self { let backend = VT100Backend::new(width, height); - let mut term = codex_tui::custom_terminal::Terminal::with_options(backend) - .expect("failed to construct terminal"); + let mut term = + codex_tui::Terminal::with_options(backend).expect("failed to construct terminal"); term.set_viewport_area(viewport); Self { term } } fn run_insert(&mut self, lines: Vec>) { - codex_tui::insert_history::insert_history_lines(&mut self.term, lines) + codex_tui::insert_history_lines(&mut self.term, lines) .expect("Failed to insert history lines in test"); } } diff --git a/codex-rs/tui/tests/suite/vt100_live_commit.rs b/codex-rs/tui/tests/suite/vt100_live_commit.rs index 4c13bb402d..01b3f72578 100644 --- a/codex-rs/tui/tests/suite/vt100_live_commit.rs +++ b/codex-rs/tui/tests/suite/vt100_live_commit.rs @@ -5,7 +5,7 @@ use ratatui::text::Line; #[test] fn live_001_commit_on_overflow() { let backend = VT100Backend::new(/*width*/ 20, /*height*/ 6); - let mut term = match codex_tui::custom_terminal::Terminal::with_options(backend) { + let mut term = match codex_tui::Terminal::with_options(backend) { Ok(t) => t, Err(e) => panic!("failed to construct terminal: {e}"), }; @@ -15,7 +15,7 @@ fn live_001_commit_on_overflow() { term.set_viewport_area(area); // Build 5 explicit rows at width 20. - let mut rb = codex_tui::live_wrap::RowBuilder::new(/*target_width*/ 20); + let mut rb = codex_tui::RowBuilder::new(/*target_width*/ 20); rb.push_fragment("one\n"); rb.push_fragment("two\n"); rb.push_fragment("three\n"); @@ -26,7 +26,7 @@ fn live_001_commit_on_overflow() { let commit_rows = rb.drain_commit_ready(/*max_keep*/ 3); let lines: Vec> = commit_rows.into_iter().map(|r| r.text.into()).collect(); - codex_tui::insert_history::insert_history_lines(&mut term, lines) + codex_tui::insert_history_lines(&mut term, lines) .expect("Failed to insert history lines in test"); let screen = term.backend().vt100().screen(); diff --git a/codex-rs/utils/cli/src/lib.rs b/codex-rs/utils/cli/src/lib.rs index b3ce23b908..ed00d683f9 100644 --- a/codex-rs/utils/cli/src/lib.rs +++ b/codex-rs/utils/cli/src/lib.rs @@ -1,8 +1,9 @@ mod approval_mode_cli_arg; mod config_override; -pub mod format_env_display; +pub(crate) mod format_env_display; mod sandbox_mode_cli_arg; pub use approval_mode_cli_arg::ApprovalModeCliArg; pub use config_override::CliConfigOverrides; +pub use format_env_display::format_env_display; pub use sandbox_mode_cli_arg::SandboxModeCliArg; diff --git a/codex-rs/utils/image/src/lib.rs b/codex-rs/utils/image/src/lib.rs index b150f76a18..9d491bc107 100644 --- a/codex-rs/utils/image/src/lib.rs +++ b/codex-rs/utils/image/src/lib.rs @@ -2,7 +2,6 @@ use std::num::NonZeroUsize; use std::path::Path; use std::sync::LazyLock; -use crate::error::ImageProcessingError; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_utils_cache::BlockingLruCache; @@ -21,7 +20,9 @@ pub const MAX_WIDTH: u32 = 2048; /// Maximum height used when resizing images before uploading. pub const MAX_HEIGHT: u32 = 768; -pub mod error; +pub(crate) mod error; + +pub use crate::error::ImageProcessingError; #[derive(Debug, Clone)] pub struct EncodedImage { diff --git a/codex-rs/utils/path-utils/src/lib.rs b/codex-rs/utils/path-utils/src/lib.rs index a6dc6f8b3a..4e053c0398 100644 --- a/codex-rs/utils/path-utils/src/lib.rs +++ b/codex-rs/utils/path-utils/src/lib.rs @@ -1,6 +1,8 @@ //! Path normalization, symlink resolution, and atomic writes shared across Codex crates. -pub mod env; +pub(crate) mod env; +pub use env::is_headless_environment; +pub use env::is_wsl; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashSet; diff --git a/codex-rs/utils/pty/src/win/mod.rs b/codex-rs/utils/pty/src/win/mod.rs index 78f5af2ce7..33b6e52fbd 100644 --- a/codex-rs/utils/pty/src/win/mod.rs +++ b/codex-rs/utils/pty/src/win/mod.rs @@ -44,7 +44,7 @@ use winapi::um::processthreadsapi::*; use winapi::um::synchapi::WaitForSingleObject; use winapi::um::winbase::INFINITE; -pub mod conpty; +pub(crate) mod conpty; mod procthreadattr; mod psuedocon; diff --git a/codex-rs/windows-sandbox-rs/src/elevated/command_runner_win.rs b/codex-rs/windows-sandbox-rs/src/elevated/command_runner_win.rs index 7777055e28..9cb59e18dc 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated/command_runner_win.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated/command_runner_win.rs @@ -12,31 +12,33 @@ use anyhow::Context; use anyhow::Result; +use codex_windows_sandbox::ErrorPayload; +use codex_windows_sandbox::ExitPayload; +use codex_windows_sandbox::FramedMessage; +use codex_windows_sandbox::Message; +use codex_windows_sandbox::OutputPayload; +use codex_windows_sandbox::OutputStream; use codex_windows_sandbox::PipeSpawnHandles; use codex_windows_sandbox::SandboxPolicy; +use codex_windows_sandbox::SpawnReady; +use codex_windows_sandbox::SpawnRequest; use codex_windows_sandbox::StderrMode; use codex_windows_sandbox::StdinMode; use codex_windows_sandbox::allow_null_device; use codex_windows_sandbox::convert_string_sid_to_sid; use codex_windows_sandbox::create_readonly_token_with_caps_from; use codex_windows_sandbox::create_workspace_write_token_with_caps_from; +use codex_windows_sandbox::decode_bytes; +use codex_windows_sandbox::encode_bytes; use codex_windows_sandbox::get_current_token_for_restriction; use codex_windows_sandbox::hide_current_user_profile_dir; -use codex_windows_sandbox::ipc_framed::ErrorPayload; -use codex_windows_sandbox::ipc_framed::ExitPayload; -use codex_windows_sandbox::ipc_framed::FramedMessage; -use codex_windows_sandbox::ipc_framed::Message; -use codex_windows_sandbox::ipc_framed::OutputPayload; -use codex_windows_sandbox::ipc_framed::OutputStream; -use codex_windows_sandbox::ipc_framed::decode_bytes; -use codex_windows_sandbox::ipc_framed::encode_bytes; -use codex_windows_sandbox::ipc_framed::read_frame; -use codex_windows_sandbox::ipc_framed::write_frame; use codex_windows_sandbox::log_note; use codex_windows_sandbox::parse_policy; +use codex_windows_sandbox::read_frame; use codex_windows_sandbox::read_handle_loop; use codex_windows_sandbox::spawn_process_with_pipes; use codex_windows_sandbox::to_wide; +use codex_windows_sandbox::write_frame; use std::ffi::c_void; use std::fs::File; use std::os::windows::io::FromRawHandle; @@ -144,9 +146,7 @@ fn send_error(writer: &Arc>, code: &str, message: String) -> Resu } /// Read and validate the initial spawn request frame. -fn read_spawn_request( - reader: &mut File, -) -> Result { +fn read_spawn_request(reader: &mut File) -> Result { let Some(msg) = read_frame(reader)? else { anyhow::bail!("runner: pipe closed before spawn_request"); }; @@ -184,9 +184,7 @@ fn effective_cwd(req_cwd: &Path, log_dir: Option<&Path>) -> PathBuf { } } -fn spawn_ipc_process( - req: &codex_windows_sandbox::ipc_framed::SpawnRequest, -) -> Result { +fn spawn_ipc_process(req: &SpawnRequest) -> Result { let log_dir = req.codex_home.clone(); hide_current_user_profile_dir(req.codex_home.as_path()); log_note( @@ -466,7 +464,7 @@ pub fn main() -> Result<()> { let msg = FramedMessage { version: 1, message: Message::SpawnReady { - payload: codex_windows_sandbox::ipc_framed::SpawnReady { + payload: SpawnReady { process_id: unsafe { GetProcessId(pi.hProcess) }, }, }, diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index 9dea9414ba..dd8f23d00f 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -34,7 +34,7 @@ mod conpty; #[cfg(target_os = "windows")] #[path = "elevated/ipc_framed.rs"] -pub mod ipc_framed; +pub(crate) mod ipc_framed; #[cfg(target_os = "windows")] #[path = "setup_orchestrator.rs"] @@ -88,6 +88,30 @@ pub use identity::require_logon_sandbox_creds; #[cfg(target_os = "windows")] pub use identity::sandbox_setup_is_complete; #[cfg(target_os = "windows")] +pub use ipc_framed::ErrorPayload; +#[cfg(target_os = "windows")] +pub use ipc_framed::ExitPayload; +#[cfg(target_os = "windows")] +pub use ipc_framed::FramedMessage; +#[cfg(target_os = "windows")] +pub use ipc_framed::Message; +#[cfg(target_os = "windows")] +pub use ipc_framed::OutputPayload; +#[cfg(target_os = "windows")] +pub use ipc_framed::OutputStream; +#[cfg(target_os = "windows")] +pub use ipc_framed::SpawnReady; +#[cfg(target_os = "windows")] +pub use ipc_framed::SpawnRequest; +#[cfg(target_os = "windows")] +pub use ipc_framed::decode_bytes; +#[cfg(target_os = "windows")] +pub use ipc_framed::encode_bytes; +#[cfg(target_os = "windows")] +pub use ipc_framed::read_frame; +#[cfg(target_os = "windows")] +pub use ipc_framed::write_frame; +#[cfg(target_os = "windows")] pub use logging::LOG_FILE_NAME; #[cfg(target_os = "windows")] pub use logging::log_note; From 4cc6818996bbe47b4f490f9ca3ce3cd8504bf6c3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 7 Apr 2026 17:53:31 +0200 Subject: [PATCH 13/28] chore: keep request_user_input tool to persist cache on multi-agents (#17009) --- .../src/tools/handlers/request_user_input.rs | 11 ++++ .../handlers/request_user_input_tests.rs | 66 +++++++++++++++++++ codex-rs/tools/src/tool_config.rs | 5 +- codex-rs/tools/src/tool_config_tests.rs | 6 +- codex-rs/tools/src/tool_registry_plan.rs | 24 ++++--- .../tools/src/tool_registry_plan_tests.rs | 2 +- 6 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 codex-rs/core/src/tools/handlers/request_user_input_tests.rs diff --git a/codex-rs/core/src/tools/handlers/request_user_input.rs b/codex-rs/core/src/tools/handlers/request_user_input.rs index dcc9445a94..69d222aa87 100644 --- a/codex-rs/core/src/tools/handlers/request_user_input.rs +++ b/codex-rs/core/src/tools/handlers/request_user_input.rs @@ -5,6 +5,7 @@ use crate::tools::context::ToolPayload; use crate::tools::handlers::parse_arguments; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; +use codex_protocol::protocol::SessionSource; use codex_protocol::request_user_input::RequestUserInputArgs; use codex_tools::REQUEST_USER_INPUT_TOOL_NAME; use codex_tools::normalize_request_user_input_args; @@ -39,6 +40,12 @@ impl ToolHandler for RequestUserInputHandler { } }; + if matches!(turn.session_source, SessionSource::SubAgent(_)) { + return Err(FunctionCallError::RespondToModel( + "request_user_input can only be used by the root thread".to_string(), + )); + } + let mode = session.collaboration_mode().await.mode; if let Some(message) = request_user_input_unavailable_message(mode, self.default_mode_request_user_input) @@ -67,3 +74,7 @@ impl ToolHandler for RequestUserInputHandler { Ok(FunctionToolOutput::from_text(content, Some(true))) } } + +#[cfg(test)] +#[path = "request_user_input_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/tools/handlers/request_user_input_tests.rs b/codex-rs/core/src/tools/handlers/request_user_input_tests.rs new file mode 100644 index 0000000000..0275a12860 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/request_user_input_tests.rs @@ -0,0 +1,66 @@ +use super::*; +use crate::codex::make_session_and_context; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolPayload; +use crate::turn_diff_tracker::TurnDiffTracker; +use codex_protocol::ThreadId; +use codex_protocol::protocol::SubAgentSource; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; + +#[tokio::test] +async fn multi_agent_v2_request_user_input_rejects_subagent_threads() { + let (session, mut turn) = make_session_and_context().await; + turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: ThreadId::new(), + depth: 1, + agent_path: None, + agent_nickname: None, + agent_role: None, + }); + + let result = RequestUserInputHandler { + default_mode_request_user_input: true, + } + .handle(ToolInvocation { + session: Arc::new(session), + turn: Arc::new(turn), + tracker: Arc::new(Mutex::new(TurnDiffTracker::default())), + call_id: "call-1".to_string(), + tool_name: REQUEST_USER_INPUT_TOOL_NAME.to_string(), + tool_namespace: None, + payload: ToolPayload::Function { + arguments: json!({ + "questions": [{ + "header": "Hdr", + "question": "Pick one", + "id": "pick_one", + "options": [ + { + "label": "A", + "description": "A" + }, + { + "label": "B", + "description": "B" + } + ] + }] + }) + .to_string(), + }, + }) + .await; + + let Err(err) = result else { + panic!("sub-agent request_user_input should fail"); + }; + assert_eq!( + err, + FunctionCallError::RespondToModel( + "request_user_input can only be used by the root thread".to_string(), + ) + ); +} diff --git a/codex-rs/tools/src/tool_config.rs b/codex-rs/tools/src/tool_config.rs index 3143976a5c..1b55d2c4f4 100644 --- a/codex-rs/tools/src/tool_config.rs +++ b/codex-rs/tools/src/tool_config.rs @@ -105,7 +105,6 @@ pub struct ToolsConfig { pub collab_tools: bool, pub multi_agent_v2: bool, pub hide_spawn_agent_metadata: bool, - pub request_user_input: bool, pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, pub agent_jobs_tools: bool, @@ -144,9 +143,8 @@ impl ToolsConfig { let include_multi_agent_v2 = features.enabled(Feature::MultiAgentV2); let hide_spawn_agent_metadata = features.enabled(Feature::DebugHideSpawnAgentMetadata); let include_agent_jobs = features.enabled(Feature::SpawnCsv); - let include_request_user_input = !matches!(session_source, SessionSource::SubAgent(_)); let include_default_mode_request_user_input = - include_request_user_input && features.enabled(Feature::DefaultModeRequestUserInput); + features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = model_info.supports_search_tool && features.enabled(Feature::ToolSearch); let include_tool_suggest = features.enabled(Feature::ToolSuggest) @@ -222,7 +220,6 @@ impl ToolsConfig { collab_tools: include_collab_tools, multi_agent_v2: include_multi_agent_v2, hide_spawn_agent_metadata, - request_user_input: include_request_user_input, default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), agent_jobs_tools: include_agent_jobs, diff --git a/codex-rs/tools/src/tool_config_tests.rs b/codex-rs/tools/src/tool_config_tests.rs index 168c8e80a0..5f121ff020 100644 --- a/codex-rs/tools/src/tool_config_tests.rs +++ b/codex-rs/tools/src/tool_config_tests.rs @@ -131,9 +131,10 @@ fn shell_zsh_fork_prefers_shell_command_over_unified_exec() { } #[test] -fn subagents_disable_request_user_input_and_agent_jobs_workers_opt_in_by_label() { +fn subagents_keep_request_user_input_mode_config_and_agent_jobs_workers_opt_in_by_label() { let model_info = model_info(); let mut features = Features::with_defaults(); + features.enable(Feature::DefaultModeRequestUserInput); features.enable(Feature::SpawnCsv); let available_models = Vec::new(); @@ -149,8 +150,7 @@ fn subagents_disable_request_user_input_and_agent_jobs_workers_opt_in_by_label() windows_sandbox_level: WindowsSandboxLevel::Disabled, }); - assert!(!tools_config.request_user_input); - assert!(!tools_config.default_mode_request_user_input); + assert!(tools_config.default_mode_request_user_input); assert!(tools_config.agent_jobs_tools); assert!(tools_config.agent_jobs_worker_tools); } diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs index d63174c4c9..dc76c12d36 100644 --- a/codex-rs/tools/src/tool_registry_plan.rs +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -206,19 +206,17 @@ pub fn build_tool_registry_plan( plan.register_handler("js_repl_reset", ToolHandlerKind::JsReplReset); } - if config.request_user_input { - plan.push_spec( - create_request_user_input_tool(request_user_input_tool_description( - config.default_mode_request_user_input, - )), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - plan.register_handler( - REQUEST_USER_INPUT_TOOL_NAME, - ToolHandlerKind::RequestUserInput, - ); - } + plan.push_spec( + create_request_user_input_tool(request_user_input_tool_description( + config.default_mode_request_user_input, + )), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler( + REQUEST_USER_INPUT_TOOL_NAME, + ToolHandlerKind::RequestUserInput, + ); if config.request_permissions_tool_enabled { plan.push_spec( diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index 9e5fac1fcc..d8d264e2e8 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -534,9 +534,9 @@ fn test_build_specs_agent_job_worker_tools_enabled() { "close_agent", "spawn_agents_on_csv", "report_agent_job_result", + REQUEST_USER_INPUT_TOOL_NAME, ], ); - assert_lacks_tool_name(&tools, "request_user_input"); } #[test] From 3b32de4fabc4460b17506bc3126977768c24e33f Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 7 Apr 2026 09:24:14 -0700 Subject: [PATCH 14/28] Stabilize flaky multi-agent followup interrupt test (#16739) Problem: The multi-agent followup interrupt test polled history before interrupt cleanup and mailbox wakeup were guaranteed to settle, which made it flaky under CI scheduling variance. Solution: Wait for the child turn's `TurnAborted(Interrupted)` event before asserting that the redirected assistant envelope is recorded and no plain user message is left behind. --- .../src/tools/handlers/multi_agents_tests.rs | 119 ++++++++++++------ 1 file changed, 81 insertions(+), 38 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 923f7a6b7f..7fec089320 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::CodexThread; use crate::ThreadManager; use crate::codex::make_session_and_context; use crate::config::DEFAULT_AGENT_MAX_DEPTH; @@ -112,6 +113,73 @@ fn history_contains_inter_agent_communication( }) } +async fn wait_for_turn_aborted( + thread: &Arc, + expected_turn_id: &str, + expected_reason: TurnAbortReason, +) { + timeout(Duration::from_secs(5), async { + loop { + let event = thread + .next_event() + .await + .expect("child thread should emit events"); + if matches!( + event.msg, + EventMsg::TurnAborted(TurnAbortedEvent { + turn_id: Some(ref turn_id), + ref reason, + }) if turn_id == expected_turn_id && *reason == expected_reason + ) { + break; + } + } + }) + .await + .expect("expected child turn to be interrupted"); +} + +async fn wait_for_redirected_envelope_in_history( + thread: &Arc, + expected: &InterAgentCommunication, +) { + timeout(Duration::from_secs(5), async { + loop { + let history_items = thread + .codex + .session + .clone_history() + .await + .raw_items() + .to_vec(); + let saw_envelope = + history_contains_inter_agent_communication(&history_items, expected); + let saw_user_message = history_items.iter().any(|item| { + matches!( + item, + ResponseItem::Message { role, content, .. } + if role == "user" + && content.iter().any(|content_item| matches!( + content_item, + ContentItem::InputText { text } + if text == &expected.content + )) + ) + }); + if saw_envelope { + assert!( + !saw_user_message, + "redirected followup should be stored as an assistant envelope, not a plain user message" + ); + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("redirected followup envelope should appear in history"); +} + #[derive(Clone, Copy)] struct NeverEndingTask; @@ -1203,6 +1271,7 @@ async fn multi_agent_v2_followup_task_interrupts_busy_child_without_losing_messa .expect("worker thread should exist"); let active_turn = thread.codex.session.new_default_turn().await; + let interrupted_turn_id = active_turn.sub_id.clone(); thread .codex .session @@ -1247,44 +1316,18 @@ async fn multi_agent_v2_followup_task_interrupts_busy_child_without_losing_messa ) })); - timeout(Duration::from_secs(5), async { - loop { - let history_items = thread - .codex - .session - .clone_history() - .await - .raw_items() - .to_vec(); - let saw_envelope = history_contains_inter_agent_communication( - &history_items, - &InterAgentCommunication::new( - AgentPath::root(), - AgentPath::try_from("/root/worker").expect("agent path"), - Vec::new(), - "continue".to_string(), - /*trigger_turn*/ true, - ), - ); - let saw_user_message = history_items.iter().any(|item| { - matches!( - item, - ResponseItem::Message { role, content, .. } - if role == "user" - && content.iter().any(|content_item| matches!( - content_item, - ContentItem::InputText { text } if text == "continue" - )) - ) - }); - if saw_envelope && !saw_user_message { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("interrupting v2 followup_task should preserve the redirected message"); + wait_for_turn_aborted(&thread, &interrupted_turn_id, TurnAbortReason::Interrupted).await; + wait_for_redirected_envelope_in_history( + &thread, + &InterAgentCommunication::new( + AgentPath::root(), + AgentPath::try_from("/root/worker").expect("agent path"), + Vec::new(), + "continue".to_string(), + /*trigger_turn*/ true, + ), + ) + .await; let _ = thread .submit(Op::Shutdown {}) From 82506527f1e4f701064b8d9133a7e0fdd5e410c7 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 7 Apr 2026 09:25:39 -0700 Subject: [PATCH 15/28] Fix read-only apply_patch rejection message (#16885) Addresses #15532 Problem: Nested read-only `apply_patch` rejections report in-project files as outside the project. Solution: Choose the rejection message based on sandbox mode so read-only sessions report a read-only-specific reason, and add focused safety coverage. --- codex-rs/core/src/safety.rs | 21 +++++++++++++++----- codex-rs/core/src/safety_tests.rs | 32 +++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/safety.rs b/codex-rs/core/src/safety.rs index dec7a00876..4ed88783a6 100644 --- a/codex-rs/core/src/safety.rs +++ b/codex-rs/core/src/safety.rs @@ -12,6 +12,11 @@ use codex_protocol::protocol::SandboxPolicy; use codex_sandboxing::SandboxType; use codex_sandboxing::get_platform_sandbox; +const PATCH_REJECTED_OUTSIDE_PROJECT_REASON: &str = + "writing outside of the project; rejected by user approval settings"; +const PATCH_REJECTED_READ_ONLY_REASON: &str = + "writing is blocked by read-only sandbox; rejected by user approval settings"; + #[derive(Debug, PartialEq)] pub enum SafetyCheck { AutoApprove { @@ -85,9 +90,7 @@ pub fn assess_patch_safety( None => { if rejects_sandbox_approval { SafetyCheck::Reject { - reason: - "writing outside of the project; rejected by user approval settings" - .to_string(), + reason: patch_rejection_reason(sandbox_policy).to_string(), } } else { SafetyCheck::AskUser @@ -97,14 +100,22 @@ pub fn assess_patch_safety( } } else if rejects_sandbox_approval { SafetyCheck::Reject { - reason: "writing outside of the project; rejected by user approval settings" - .to_string(), + reason: patch_rejection_reason(sandbox_policy).to_string(), } } else { SafetyCheck::AskUser } } +fn patch_rejection_reason(sandbox_policy: &SandboxPolicy) -> &'static str { + match sandbox_policy { + SandboxPolicy::ReadOnly { .. } => PATCH_REJECTED_READ_ONLY_REASON, + SandboxPolicy::WorkspaceWrite { .. } + | SandboxPolicy::DangerFullAccess + | SandboxPolicy::ExternalSandbox { .. } => PATCH_REJECTED_OUTSIDE_PROJECT_REASON, + } +} + fn is_write_patch_constrained_to_writable_paths( action: &ApplyPatchAction, file_system_sandbox_policy: &FileSystemSandboxPolicy, diff --git a/codex-rs/core/src/safety_tests.rs b/codex-rs/core/src/safety_tests.rs index e7f55693d1..5ebeb64e0e 100644 --- a/codex-rs/core/src/safety_tests.rs +++ b/codex-rs/core/src/safety_tests.rs @@ -162,8 +162,36 @@ fn granular_sandbox_approval_false_rejects_out_of_root_patch() { WindowsSandboxLevel::Disabled, ), SafetyCheck::Reject { - reason: "writing outside of the project; rejected by user approval settings" - .to_string(), + reason: PATCH_REJECTED_OUTSIDE_PROJECT_REASON.to_string(), + }, + ); +} + +#[test] +fn read_only_policy_rejects_patch_with_read_only_reason() { + let tmp = TempDir::new().unwrap(); + let cwd = tmp.path().to_path_buf(); + let action = ApplyPatchAction::new_add_for_test(&cwd.join("inside.txt"), "".to_string()); + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let file_system_sandbox_policy = + FileSystemSandboxPolicy::from_legacy_sandbox_policy(&sandbox_policy, &cwd); + + assert!(!is_write_patch_constrained_to_writable_paths( + &action, + &file_system_sandbox_policy, + &cwd, + )); + assert_eq!( + assess_patch_safety( + &action, + AskForApproval::Never, + &sandbox_policy, + &file_system_sandbox_policy, + &cwd, + WindowsSandboxLevel::Disabled, + ), + SafetyCheck::Reject { + reason: PATCH_REJECTED_READ_ONLY_REASON.to_string(), }, ); } From feb4f0051a5952310f8e08207418a4ba26bd4b4e Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 7 Apr 2026 09:26:22 -0700 Subject: [PATCH 16/28] Fix nested exec thread ID restore (#16882) Addresses #15527 Problem: Nested `codex exec` commands could source a shell snapshot that re-exported the parent `CODEX_THREAD_ID`, so commands inside the nested session were attributed to the wrong thread. Solution: Reapply the live command env's `CODEX_THREAD_ID` after sourcing the snapshot. --- codex-rs/core/src/tasks/user_shell.rs | 10 +- codex-rs/core/src/tools/runtimes/mod.rs | 15 ++- codex-rs/core/src/tools/runtimes/mod_tests.rs | 116 +++++++++++++++--- codex-rs/core/src/tools/runtimes/shell.rs | 1 + .../core/src/tools/runtimes/unified_exec.rs | 1 + 5 files changed, 122 insertions(+), 21 deletions(-) diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 3181e73698..744d8d797c 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -124,11 +124,16 @@ pub(crate) async fn execute_user_shell_command( let use_login_shell = true; let session_shell = session.user_shell(); let display_command = session_shell.derive_exec_args(&command, use_login_shell); + let exec_env_map = create_env( + &turn_context.shell_environment_policy, + Some(session.conversation_id), + ); let exec_command = maybe_wrap_shell_lc_with_snapshot( &display_command, session_shell.as_ref(), turn_context.cwd.as_path(), &turn_context.shell_environment_policy.r#set, + &exec_env_map, ); let call_id = Uuid::new_v4().to_string(); @@ -156,10 +161,7 @@ pub(crate) async fn execute_user_shell_command( let exec_env = ExecRequest { command: exec_command.clone(), cwd: cwd.to_path_buf(), - env: create_env( - &turn_context.shell_environment_policy, - Some(session.conversation_id), - ), + env: exec_env_map, network: turn_context.network.clone(), // TODO(zhao-oai): Now that we have ExecExpiration::Cancellation, we // should use that instead of an "arbitrarily large" timeout here. diff --git a/codex-rs/core/src/tools/runtimes/mod.rs b/codex-rs/core/src/tools/runtimes/mod.rs index a4b44ff0ec..99b5371f17 100644 --- a/codex-rs/core/src/tools/runtimes/mod.rs +++ b/codex-rs/core/src/tools/runtimes/mod.rs @@ -4,6 +4,7 @@ Module: runtimes Concrete ToolRuntime implementations for specific tools. Each runtime stays small and focused and reuses the orchestrator for approvals + sandbox + retry. */ +use crate::exec_env::CODEX_THREAD_ID_ENV_VAR; use crate::path_utils; use crate::shell::Shell; use crate::tools::sandboxing::ToolError; @@ -48,11 +49,19 @@ pub(crate) fn build_sandbox_command( /// This wrapper script uses POSIX constructs (`if`, `.`, `exec`) so it can /// be run by Bash/Zsh/sh. On non-matching commands, or when command cwd does /// not match the snapshot cwd, this is a no-op. +/// +/// `explicit_env_overrides` and `env` are intentionally separate inputs. +/// `explicit_env_overrides` contains policy-driven shell env overrides that +/// should win after the snapshot is sourced, while `env` is the full live exec +/// environment. We need access to both so snapshot restore logic can preserve +/// runtime-only vars like `CODEX_THREAD_ID` without pretending they came from +/// the explicit override policy. pub(crate) fn maybe_wrap_shell_lc_with_snapshot( command: &[String], session_shell: &Shell, cwd: &Path, explicit_env_overrides: &HashMap, + env: &HashMap, ) -> Vec { if cfg!(windows) { return command.to_vec(); @@ -95,7 +104,11 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot( .iter() .map(|arg| format!(" '{}'", shell_single_quote(arg))) .collect::(); - let (override_captures, override_exports) = build_override_exports(explicit_env_overrides); + let mut override_env = explicit_env_overrides.clone(); + if let Some(thread_id) = env.get(CODEX_THREAD_ID_ENV_VAR) { + override_env.insert(CODEX_THREAD_ID_ENV_VAR.to_string(), thread_id.clone()); + } + let (override_captures, override_exports) = build_override_exports(&override_env); let rewritten_script = if override_exports.is_empty() { format!( "if . '{snapshot_path}' >/dev/null 2>&1; then :; fi\n\nexec '{original_shell}' -c '{original_script}'{trailing_args}" diff --git a/codex-rs/core/src/tools/runtimes/mod_tests.rs b/codex-rs/core/src/tools/runtimes/mod_tests.rs index dbc341d1de..22c22770ab 100644 --- a/codex-rs/core/src/tools/runtimes/mod_tests.rs +++ b/codex-rs/core/src/tools/runtimes/mod_tests.rs @@ -42,8 +42,13 @@ fn maybe_wrap_shell_lc_with_snapshot_bootstraps_in_user_shell() { "echo hello".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); assert_eq!(rewritten[0], "/bin/zsh"); assert_eq!(rewritten[1], "-c"); @@ -68,8 +73,13 @@ fn maybe_wrap_shell_lc_with_snapshot_escapes_single_quotes() { "echo 'hello'".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); assert!(rewritten[2].contains(r#"exec '/bin/bash' -c 'echo '"'"'hello'"'"''"#)); } @@ -91,8 +101,13 @@ fn maybe_wrap_shell_lc_with_snapshot_uses_bash_bootstrap_shell() { "echo hello".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); assert_eq!(rewritten[0], "/bin/bash"); assert_eq!(rewritten[1], "-c"); @@ -117,8 +132,13 @@ fn maybe_wrap_shell_lc_with_snapshot_uses_sh_bootstrap_shell() { "echo hello".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); assert_eq!(rewritten[0], "/bin/sh"); assert_eq!(rewritten[1], "-c"); @@ -145,8 +165,13 @@ fn maybe_wrap_shell_lc_with_snapshot_preserves_trailing_args() { "arg1".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); assert!( rewritten[2] @@ -171,8 +196,13 @@ fn maybe_wrap_shell_lc_with_snapshot_skips_when_cwd_mismatch() { "echo hello".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, &command_cwd, &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + &command_cwd, + &HashMap::new(), + &HashMap::new(), + ); assert_eq!(rewritten, command); } @@ -195,8 +225,13 @@ fn maybe_wrap_shell_lc_with_snapshot_accepts_dot_alias_cwd() { ]; let command_cwd = dir.path().join("."); - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, &command_cwd, &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + &command_cwd, + &HashMap::new(), + &HashMap::new(), + ); assert_eq!(rewritten[0], "/bin/zsh"); assert_eq!(rewritten[1], "-c"); @@ -231,6 +266,7 @@ fn maybe_wrap_shell_lc_with_snapshot_restores_explicit_override_precedence() { &session_shell, dir.path(), &explicit_env_overrides, + &HashMap::from([("TEST_ENV_SNAPSHOT".to_string(), "worktree".to_string())]), ); let output = Command::new(&rewritten[0]) .args(&rewritten[1..]) @@ -245,6 +281,43 @@ fn maybe_wrap_shell_lc_with_snapshot_restores_explicit_override_precedence() { ); } +#[test] +fn maybe_wrap_shell_lc_with_snapshot_restores_codex_thread_id_from_env() { + let dir = tempdir().expect("create temp dir"); + let snapshot_path = dir.path().join("snapshot.sh"); + std::fs::write( + &snapshot_path, + "# Snapshot file\nexport CODEX_THREAD_ID='parent-thread'\n", + ) + .expect("write snapshot"); + let session_shell = shell_with_snapshot( + ShellType::Bash, + "/bin/bash", + snapshot_path, + dir.path().to_path_buf(), + ); + let command = vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "printf '%s' \"$CODEX_THREAD_ID\"".to_string(), + ]; + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::from([("CODEX_THREAD_ID".to_string(), "nested-thread".to_string())]), + ); + let output = Command::new(&rewritten[0]) + .args(&rewritten[1..]) + .env("CODEX_THREAD_ID", "nested-thread") + .output() + .expect("run rewritten command"); + + assert!(output.status.success(), "command failed: {output:?}"); + assert_eq!(String::from_utf8_lossy(&output.stdout), "nested-thread"); +} + #[test] fn maybe_wrap_shell_lc_with_snapshot_keeps_snapshot_path_without_override() { let dir = tempdir().expect("create temp dir"); @@ -265,8 +338,13 @@ fn maybe_wrap_shell_lc_with_snapshot_keeps_snapshot_path_without_override() { "-lc".to_string(), "printf '%s' \"$PATH\"".to_string(), ]; - let rewritten = - maybe_wrap_shell_lc_with_snapshot(&command, &session_shell, dir.path(), &HashMap::new()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + dir.path(), + &HashMap::new(), + &HashMap::new(), + ); let output = Command::new(&rewritten[0]) .args(&rewritten[1..]) .output() @@ -302,6 +380,7 @@ fn maybe_wrap_shell_lc_with_snapshot_applies_explicit_path_override() { &session_shell, dir.path(), &explicit_env_overrides, + &HashMap::from([("PATH".to_string(), "/worktree/bin".to_string())]), ); let output = Command::new(&rewritten[0]) .args(&rewritten[1..]) @@ -342,6 +421,10 @@ fn maybe_wrap_shell_lc_with_snapshot_does_not_embed_override_values_in_argv() { &session_shell, dir.path(), &explicit_env_overrides, + &HashMap::from([( + "OPENAI_API_KEY".to_string(), + "super-secret-value".to_string(), + )]), ); assert!(!rewritten[2].contains("super-secret-value")); @@ -386,6 +469,7 @@ fn maybe_wrap_shell_lc_with_snapshot_preserves_unset_override_variables() { &session_shell, dir.path(), &explicit_env_overrides, + &HashMap::new(), ); let output = Command::new(&rewritten[0]) diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index ba8713254a..7b0c81ac60 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -226,6 +226,7 @@ impl ToolRuntime for ShellRuntime { session_shell.as_ref(), &req.cwd, &req.explicit_env_overrides, + &req.env, ); let command = if matches!(session_shell.shell_type, ShellType::PowerShell) { prefix_powershell_script_with_utf8(&command) diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 3858150da5..7b271363b2 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -207,6 +207,7 @@ impl<'a> ToolRuntime for UnifiedExecRunt session_shell.as_ref(), &req.cwd, &req.explicit_env_overrides, + &req.env, ); let command = if matches!(session_shell.shell_type, ShellType::PowerShell) { prefix_powershell_script_with_utf8(&command) From cd591dc4571d19259b9ddd9380583d0edfaac758 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 7 Apr 2026 09:32:14 -0700 Subject: [PATCH 17/28] Preserve null developer instructions (#16976) Preserve explicit null developer-instruction overrides across app-server resume and fork flows. --- codex-rs/app-server/tests/common/rollout.rs | 2 ++ .../app-server/tests/suite/v2/thread_fork.rs | 17 +++++++++++ .../tests/suite/v2/thread_resume.rs | 1 + .../app-server/tests/suite/v2/turn_start.rs | 17 +++++++++++ codex-rs/core/src/codex.rs | 18 +++++++++++- codex-rs/core/src/codex_tests.rs | 9 ++++++ codex-rs/core/src/config/config_tests.rs | 4 +++ codex-rs/core/src/config/mod.rs | 6 ++++ .../core/src/personality_migration_tests.rs | 1 + .../core/tests/suite/personality_migration.rs | 2 ++ .../core/tests/suite/rollout_list_find.rs | 1 + codex-rs/core/tests/suite/sqlite_state.rs | 1 + codex-rs/protocol/src/protocol.rs | 28 +++++++++++++++++++ codex-rs/rollout/src/metadata_tests.rs | 3 ++ codex-rs/rollout/src/recorder.rs | 5 ++++ codex-rs/rollout/src/recorder_tests.rs | 2 ++ codex-rs/rollout/src/tests.rs | 1 + codex-rs/state/src/extract.rs | 2 ++ codex-rs/state/src/runtime/threads.rs | 2 ++ 19 files changed, 121 insertions(+), 1 deletion(-) diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index b67390154e..efbed53255 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -84,6 +84,7 @@ pub fn create_fake_rollout_with_source( agent_role: None, model_provider: model_provider.map(str::to_string), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; @@ -167,6 +168,7 @@ pub fn create_fake_rollout_with_text_elements( agent_role: None, model_provider: model_provider.map(str::to_string), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index b4e80d7816..1137f09848 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -200,6 +200,16 @@ async fn thread_fork_honors_explicit_null_thread_instructions() -> Result<()> { let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri())?; + let config_path = codex_home.path().join("config.toml"); + let mut config_toml = std::fs::read_to_string(&config_path)?; + let first_table_index = config_toml + .find("\n[") + .expect("test config must include a table header"); + config_toml.insert_str( + first_table_index, + "\ndeveloper_instructions = \"Config developer instructions sentinel\"\n", + ); + std::fs::write(config_path, config_toml)?; let conversation_id = create_fake_rollout( codex_home.path(), @@ -323,6 +333,13 @@ async fn thread_fork_honors_explicit_null_thread_instructions() -> Result<()> { "unexpected instructions field in payload: {payload:?}" ); let developer_texts = request.message_input_texts("developer"); + assert_eq!( + developer_texts + .iter() + .any(|text| { text.contains("Config developer instructions sentinel") }), + expect_instructions, + "unexpected config developer instruction presence: {developer_texts:?}" + ); assert!( developer_texts.iter().all(|text| !text.is_empty()), "did not expect empty developer instruction messages: {developer_texts:?}" diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 80ae756888..4c92b61c25 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -377,6 +377,7 @@ stream_max_retries = 0 agent_role: None, model_provider: Some("mock_provider".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index e8f3e1df2c..70c388a19d 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -166,6 +166,16 @@ async fn turn_start_honors_explicit_null_thread_instructions() -> Result<()> { let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri(), "never", &BTreeMap::new())?; + let config_path = codex_home.path().join("config.toml"); + let mut config_toml = std::fs::read_to_string(&config_path)?; + let first_table_index = config_toml + .find("\n[") + .expect("test config must include a table header"); + config_toml.insert_str( + first_table_index, + "\ndeveloper_instructions = \"Config developer instructions sentinel\"\n", + ); + std::fs::write(config_path, config_toml)?; let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; @@ -240,6 +250,13 @@ async fn turn_start_honors_explicit_null_thread_instructions() -> Result<()> { "unexpected instructions field in payload: {payload:?}" ); let developer_texts = request.message_input_texts("developer"); + assert_eq!( + developer_texts + .iter() + .any(|text| { text.contains("Config developer instructions sentinel") }), + expect_instructions, + "unexpected config developer instruction presence: {developer_texts:?}" + ); assert!( developer_texts.iter().all(|text| !text.is_empty()), "did not expect empty developer instruction messages: {developer_texts:?}" diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 822dbefa5c..b5ae3970f3 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -615,6 +615,14 @@ impl Codex { dynamic_tools }; + let developer_instructions_override = config + .developer_instructions_override + .clone() + .or_else(|| conversation_history.get_developer_instructions()); + let developer_instructions = developer_instructions_override + .clone() + .unwrap_or_else(|| config.developer_instructions.clone()); + // TODO (aibrahim): Consolidate config.model and config.model_reasoning_effort into config.collaboration_mode // to avoid extracting these fields separately and constructing CollaborationMode here. let collaboration_mode = CollaborationMode { @@ -630,7 +638,8 @@ impl Codex { collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, service_tier: config.service_tier, - developer_instructions: config.developer_instructions.clone(), + developer_instructions, + developer_instructions_override, user_instructions, personality: config.personality, base_instructions, @@ -1095,6 +1104,10 @@ pub(crate) struct SessionConfiguration { /// Developer instructions that supplement the base instructions. developer_instructions: Option, + /// Explicit developer instructions override, preserving `null` as distinct + /// from a missing override. + developer_instructions_override: Option>, + /// Model instructions that are appended to the base instructions. user_instructions: Option, @@ -1545,6 +1558,9 @@ impl Session { .base_instructions .clone() .map(|text| BaseInstructions { text }), + session_configuration + .developer_instructions_override + .clone(), session_configuration.dynamic_tools.clone(), if session_configuration.persist_extended_history { EventPersistenceMode::Extended diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index ef9a69d347..a97af982cd 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -1853,6 +1853,7 @@ async fn set_rate_limits_retains_previous_credits() { collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -1955,6 +1956,7 @@ async fn set_rate_limits_updates_plan_type_when_present() { collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -2227,6 +2229,7 @@ async fn attach_rollout_recorder(session: &Arc) -> PathBuf { /*forked_from_id*/ None, SessionSource::Exec, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), @@ -2304,6 +2307,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -2570,6 +2574,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -2673,6 +2678,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -3513,6 +3519,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), + developer_instructions_override: config.developer_instructions_override.clone(), user_instructions: config.user_instructions.clone(), service_tier: None, personality: config.personality, @@ -4264,6 +4271,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_baseline /*forked_from_id*/ None, SessionSource::Exec, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), @@ -4361,6 +4369,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_full_rei /*forked_from_id*/ None, SessionSource::Exec, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index deba8a47b3..1201537da9 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -4506,6 +4506,7 @@ fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { experimental_realtime_ws_startup_context: None, base_instructions: None, developer_instructions: None, + developer_instructions_override: None, guardian_developer_instructions: None, include_permissions_instructions: true, include_apps_instructions: true, @@ -4651,6 +4652,7 @@ fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { experimental_realtime_ws_startup_context: None, base_instructions: None, developer_instructions: None, + developer_instructions_override: None, guardian_developer_instructions: None, include_permissions_instructions: true, include_apps_instructions: true, @@ -4794,6 +4796,7 @@ fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { experimental_realtime_ws_startup_context: None, base_instructions: None, developer_instructions: None, + developer_instructions_override: None, guardian_developer_instructions: None, include_permissions_instructions: true, include_apps_instructions: true, @@ -4923,6 +4926,7 @@ fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { experimental_realtime_ws_startup_context: None, base_instructions: None, developer_instructions: None, + developer_instructions_override: None, guardian_developer_instructions: None, include_permissions_instructions: true, include_apps_instructions: true, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 5b1bfe83cb..84873baf00 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -248,6 +248,10 @@ pub struct Config { /// Developer instructions override injected as a separate message. pub developer_instructions: Option, + /// Explicit developer instructions override, preserving `null` as distinct + /// from a missing override. + pub developer_instructions_override: Option>, + /// Guardian-specific developer instructions override from requirements.toml. pub guardian_developer_instructions: Option, @@ -1761,6 +1765,7 @@ impl Config { let file_base_instructions = Self::try_read_non_empty_file(model_instructions_path, "model instructions file")?; let base_instructions = base_instructions.or_else(|| file_base_instructions.map(Some)); + let developer_instructions_override = developer_instructions.clone(); let developer_instructions = developer_instructions.unwrap_or_else(|| cfg.developer_instructions.clone()); let include_permissions_instructions = config_profile @@ -1945,6 +1950,7 @@ impl Config { base_instructions, personality, developer_instructions, + developer_instructions_override, compact_prompt, commit_attribution, include_permissions_instructions, diff --git a/codex-rs/core/src/personality_migration_tests.rs b/codex-rs/core/src/personality_migration_tests.rs index de1070ad34..3c8bb077fb 100644 --- a/codex-rs/core/src/personality_migration_tests.rs +++ b/codex-rs/core/src/personality_migration_tests.rs @@ -43,6 +43,7 @@ async fn write_session_with_user_event(codex_home: &Path) -> io::Result<()> { agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index 3f19d55eff..3ce6925f41 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -71,6 +71,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, @@ -116,6 +117,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index 93edd1621a..1954654266 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -174,6 +174,7 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()> /*forked_from_id*/ None, SessionSource::Exec, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index f35152e185..d99c3865c7 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -146,6 +146,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: Some(dynamic_tools_for_hook), memory_mode: None, }, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 05926a9544..4be5620fc4 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2351,6 +2351,26 @@ impl InitialHistory { } } + pub fn get_developer_instructions(&self) -> Option> { + match self { + InitialHistory::New => None, + InitialHistory::Resumed(resumed) => { + resumed.history.iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => { + meta_line.meta.developer_instructions.clone() + } + _ => None, + }) + } + InitialHistory::Forked(items) => items.iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => { + meta_line.meta.developer_instructions.clone() + } + _ => None, + }), + } + } + pub fn get_dynamic_tools(&self) -> Option> { match self { InitialHistory::New => None, @@ -2549,6 +2569,13 @@ pub struct SessionMeta { skip_serializing_if = "Option::is_none" )] pub base_instructions: Option>, + #[serde( + default, + deserialize_with = "deserialize_double_option", + serialize_with = "serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + pub developer_instructions: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub dynamic_tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] @@ -2570,6 +2597,7 @@ impl Default for SessionMeta { agent_path: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, } diff --git a/codex-rs/rollout/src/metadata_tests.rs b/codex-rs/rollout/src/metadata_tests.rs index 8a149313dc..fdea29206a 100644 --- a/codex-rs/rollout/src/metadata_tests.rs +++ b/codex-rs/rollout/src/metadata_tests.rs @@ -56,6 +56,7 @@ async fn extract_metadata_from_rollout_uses_session_meta() { agent_role: None, model_provider: Some("openai".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; @@ -107,6 +108,7 @@ async fn extract_metadata_from_rollout_returns_latest_memory_mode() { agent_role: None, model_provider: Some("openai".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; @@ -369,6 +371,7 @@ fn write_rollout_in_sessions_with_cwd( agent_role: None, model_provider: Some("test-provider".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }; diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index aa7b485b0c..b589ffac97 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -82,6 +82,7 @@ pub enum RolloutRecorderParams { forked_from_id: Option, source: SessionSource, base_instructions: Option, + developer_instructions: Option>, dynamic_tools: Vec, event_persistence_mode: EventPersistenceMode, }, @@ -111,6 +112,7 @@ impl RolloutRecorderParams { forked_from_id: Option, source: SessionSource, base_instructions: Option, + developer_instructions: Option>, dynamic_tools: Vec, event_persistence_mode: EventPersistenceMode, ) -> Self { @@ -119,6 +121,7 @@ impl RolloutRecorderParams { forked_from_id, source, base_instructions, + developer_instructions, dynamic_tools, event_persistence_mode, } @@ -380,6 +383,7 @@ impl RolloutRecorder { forked_from_id, source, base_instructions, + developer_instructions, dynamic_tools, event_persistence_mode, } => { @@ -409,6 +413,7 @@ impl RolloutRecorder { source, model_provider: Some(config.model_provider_id().to_string()), base_instructions: Some(base_instructions), + developer_instructions, dynamic_tools: if dynamic_tools.is_empty() { None } else { diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 6ee55672e7..44e8ecb8c8 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -74,6 +74,7 @@ async fn recorder_materializes_only_after_explicit_persist() -> std::io::Result< /*forked_from_id*/ None, SessionSource::Exec, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), @@ -167,6 +168,7 @@ async fn metadata_irrelevant_events_touch_state_db_updated_at() -> std::io::Resu /*forked_from_id*/ None, SessionSource::Cli, Some(BaseInstructions::default()), + /*developer_instructions*/ None, Vec::new(), EventPersistenceMode::Limited, ), diff --git a/codex-rs/rollout/src/tests.rs b/codex-rs/rollout/src/tests.rs index aeda089a25..4fbd58c14b 100644 --- a/codex-rs/rollout/src/tests.rs +++ b/codex-rs/rollout/src/tests.rs @@ -1140,6 +1140,7 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { agent_role: None, model_provider: Some("test-provider".into()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 8d35d393a8..31545e3f6c 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -257,6 +257,7 @@ mod tests { agent_role: None, model_provider: Some("openai".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, @@ -384,6 +385,7 @@ mod tests { agent_role: None, model_provider: Some("openai".to_string()), base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index 09b23a4319..06fd9a7b42 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -1030,6 +1030,7 @@ mod tests { agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: Some("polluted".to_string()), }, @@ -1088,6 +1089,7 @@ mod tests { agent_role: None, model_provider: None, base_instructions: None, + developer_instructions: None, dynamic_tools: None, memory_mode: None, }, From 2b9bf5d3d43e39811d9f8db8d65b79bc2f7c12e9 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 7 Apr 2026 09:34:04 -0700 Subject: [PATCH 18/28] Fix missing resume hint on zero-token exits (#16987) Addresses #16421 Problem: Resumed interactive sessions exited before new token usage skipped all footer lines, hiding the `codex resume` continuation command. It's not clear whether this was an intentional design choice, but I think it's reasonable to expect this message under these circumstances. Solution: Compose token usage and resume hints independently so resumable sessions still print the continuation command with zero usage. --- codex-rs/cli/src/main.rs | 13 ++++++------- codex-rs/tui/src/app.rs | 30 +++++++++++++++++++----------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 0477162718..24dd558ea7 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -438,15 +438,14 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec, thread_name: Option, ) -> Option { - if token_usage.is_zero() { + let usage_line = (!token_usage.is_zero()).then(|| FinalOutput::from(token_usage).to_string()); + let resume_command = codex_core::util::resume_command(thread_name.as_deref(), thread_id); + + if usage_line.is_none() && resume_command.is_none() { return None; } - let usage_line = FinalOutput::from(token_usage).to_string(); - let resume_command = codex_core::util::resume_command(thread_name.as_deref(), thread_id); Some(SessionSummary { usage_line, resume_command, @@ -486,7 +487,7 @@ fn emit_system_bwrap_warning(app_event_tx: &AppEventSender, config: &Config) { #[derive(Debug, Clone, PartialEq, Eq)] struct SessionSummary { - usage_line: String, + usage_line: Option, resume_command: Option, } @@ -3301,7 +3302,10 @@ impl App { "Failed to attach to fresh app-server thread: {err}" )); } else if let Some(summary) = summary { - let mut lines: Vec> = vec![summary.usage_line.clone().into()]; + let mut lines: Vec> = Vec::new(); + if let Some(usage_line) = summary.usage_line { + lines.push(usage_line.into()); + } if let Some(command) = summary.resume_command { let spans = vec!["To continue this session, run ".into(), command.cyan()]; lines.push(spans.into()); @@ -4114,8 +4118,10 @@ impl App { { Ok(()) => { if let Some(summary) = summary { - let mut lines: Vec> = - vec![summary.usage_line.clone().into()]; + let mut lines: Vec> = Vec::new(); + if let Some(usage_line) = summary.usage_line { + lines.push(usage_line.into()); + } if let Some(command) = summary.resume_command { let spans = vec![ "To continue this session, run ".into(), @@ -4174,8 +4180,10 @@ impl App { { Ok(()) => { if let Some(summary) = summary { - let mut lines: Vec> = - vec![summary.usage_line.clone().into()]; + let mut lines: Vec> = Vec::new(); + if let Some(usage_line) = summary.usage_line { + lines.push(usage_line.into()); + } if let Some(command) = summary.resume_command { let spans = vec![ "To continue this session, run ".into(), @@ -10897,7 +10905,7 @@ guardian_approval = true } #[tokio::test] - async fn session_summary_skip_zero_usage() { + async fn session_summary_skips_when_no_usage_or_resume_hint() { assert!( session_summary( TokenUsage::default(), @@ -10922,7 +10930,7 @@ guardian_approval = true session_summary(usage, Some(conversation), /*thread_name*/ None).expect("summary"); assert_eq!( summary.usage_line, - "Token usage: total=12 input=10 output=2" + Some("Token usage: total=12 input=10 output=2".to_string()) ); assert_eq!( summary.resume_command, From 5d1671ca70ca18e2c42f16cc6cd706b58a9b6ead Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 7 Apr 2026 09:52:17 -0700 Subject: [PATCH 19/28] feat(analytics): generate an installation_id and pass it in responsesapi client_metadata (#16912) ## Summary This adds a stable Codex installation ID and includes it on Responses API requests via `x-codex-installation-id` passed in via the `client_metadata` field for analytics/debugging. The main pieces are: - persist a UUID in `$CODEX_HOME/installation_id` - thread the installation ID into `ModelClient` - send it in `client_metadata` on Responses requests so it works consistently across HTTP and WebSocket transports --- codex-rs/codex-api/src/common.rs | 4 +- codex-rs/codex-api/tests/clients.rs | 2 + codex-rs/core/src/client.rs | 18 ++- codex-rs/core/src/client_common_tests.rs | 4 + codex-rs/core/src/client_tests.rs | 6 + codex-rs/core/src/codex.rs | 3 + codex-rs/core/src/codex_tests.rs | 3 + codex-rs/core/src/installation_id.rs | 145 ++++++++++++++++++ codex-rs/core/src/lib.rs | 2 + codex-rs/core/tests/responses_headers.rs | 9 ++ codex-rs/core/tests/suite/client.rs | 19 +++ .../core/tests/suite/client_websockets.rs | 6 + 12 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 codex-rs/core/src/installation_id.rs diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index a2a2c1d478..6a88cd1f47 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -169,6 +169,8 @@ pub struct ResponsesApiRequest { pub prompt_cache_key: Option, #[serde(skip_serializing_if = "Option::is_none")] pub text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub client_metadata: Option>, } impl From<&ResponsesApiRequest> for ResponseCreateWsRequest { @@ -189,7 +191,7 @@ impl From<&ResponsesApiRequest> for ResponseCreateWsRequest { prompt_cache_key: request.prompt_cache_key.clone(), text: request.text.clone(), generate: None, - client_metadata: None, + client_metadata: request.client_metadata.clone(), } } } diff --git a/codex-rs/codex-api/tests/clients.rs b/codex-rs/codex-api/tests/clients.rs index 3c22c01203..2e8411dd81 100644 --- a/codex-rs/codex-api/tests/clients.rs +++ b/codex-rs/codex-api/tests/clients.rs @@ -278,6 +278,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> { service_tier: None, prompt_cache_key: None, text: None, + client_metadata: None, }; let client = ResponsesClient::new(transport.clone(), provider, NoAuth); @@ -320,6 +321,7 @@ async fn azure_default_store_attaches_ids_and_headers() -> Result<()> { service_tier: None, prompt_cache_key: None, text: None, + client_metadata: None, }; let mut extra_headers = HeaderMap::new(); diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index e11e4362ca..80ad24be5b 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -118,6 +118,7 @@ use codex_response_debug_context::telemetry_api_error_message; use codex_response_debug_context::telemetry_transport_error_message; pub const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; +pub const X_CODEX_INSTALLATION_ID_HEADER: &str = "x-codex-installation-id"; pub const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state"; pub const X_CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata"; pub const X_CODEX_PARENT_THREAD_ID_HEADER: &str = "x-codex-parent-thread-id"; @@ -142,6 +143,7 @@ struct ModelClientState { auth_manager: Option>, conversation_id: ThreadId, window_generation: AtomicU64, + installation_id: String, provider: ModelProviderInfo, auth_env_telemetry: AuthEnvTelemetry, session_source: SessionSource, @@ -263,6 +265,7 @@ impl ModelClient { pub fn new( auth_manager: Option>, conversation_id: ThreadId, + installation_id: String, provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, @@ -280,6 +283,7 @@ impl ModelClient { auth_manager, conversation_id, window_generation: AtomicU64::new(0), + installation_id, provider, auth_env_telemetry, session_source, @@ -429,7 +433,11 @@ impl ModelClient { text, }; - let mut extra_headers = self.build_responses_identity_headers(); + let mut extra_headers = ApiHeaderMap::new(); + if let Ok(header_value) = HeaderValue::from_str(&self.state.installation_id) { + extra_headers.insert(X_CODEX_INSTALLATION_ID_HEADER, header_value); + } + extra_headers.extend(self.build_responses_identity_headers()); extra_headers.extend(build_conversation_headers(Some( self.state.conversation_id.to_string(), ))); @@ -515,6 +523,10 @@ impl ModelClient { turn_metadata_header: Option<&str>, ) -> HashMap { let mut client_metadata = HashMap::new(); + client_metadata.insert( + X_CODEX_INSTALLATION_ID_HEADER.to_string(), + self.state.installation_id.clone(), + ); client_metadata.insert( X_CODEX_WINDOW_ID_HEADER.to_string(), self.current_window_id(), @@ -817,6 +829,10 @@ impl ModelClientSession { }, prompt_cache_key, text, + client_metadata: Some(HashMap::from([( + X_CODEX_INSTALLATION_ID_HEADER.to_string(), + self.client.state.installation_id.clone(), + )])), }; Ok(request) } diff --git a/codex-rs/core/src/client_common_tests.rs b/codex-rs/core/src/client_common_tests.rs index 3d804cda83..4d4b5af4ff 100644 --- a/codex-rs/core/src/client_common_tests.rs +++ b/codex-rs/core/src/client_common_tests.rs @@ -29,6 +29,7 @@ fn serializes_text_verbosity_when_set() { verbosity: Some(OpenAiVerbosity::Low), format: None, }), + client_metadata: None, }; let v = serde_json::to_value(&req).expect("json"); @@ -69,6 +70,7 @@ fn serializes_text_schema_with_strict_format() { prompt_cache_key: None, service_tier: None, text: Some(text_controls), + client_metadata: None, }; let v = serde_json::to_value(&req).expect("json"); @@ -106,6 +108,7 @@ fn omits_text_when_not_set() { prompt_cache_key: None, service_tier: None, text: None, + client_metadata: None, }; let v = serde_json::to_value(&req).expect("json"); @@ -128,6 +131,7 @@ fn serializes_flex_service_tier_when_set() { prompt_cache_key: None, service_tier: Some(ServiceTier::Flex.to_string()), text: None, + client_metadata: None, }; let v = serde_json::to_value(&req).expect("json"); diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index 02d7422475..2fd5f04f95 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -2,6 +2,7 @@ use super::AuthRequestTelemetryContext; use super::ModelClient; use super::PendingUnauthorizedRetry; use super::UnauthorizedRecoveryExecution; +use super::X_CODEX_INSTALLATION_ID_HEADER; use super::X_CODEX_PARENT_THREAD_ID_HEADER; use super::X_CODEX_TURN_METADATA_HEADER; use super::X_CODEX_WINDOW_ID_HEADER; @@ -23,6 +24,7 @@ fn test_model_client(session_source: SessionSource) -> ModelClient { ModelClient::new( /*auth_manager*/ None, ThreadId::new(), + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), provider, session_source, /*model_verbosity*/ None, @@ -107,6 +109,10 @@ fn build_ws_client_metadata_includes_window_lineage_and_turn_metadata() { assert_eq!( client_metadata, std::collections::HashMap::from([ + ( + X_CODEX_INSTALLATION_ID_HEADER.to_string(), + "11111111-1111-4111-8111-111111111111".to_string(), + ), ( X_CODEX_WINDOW_ID_HEADER.to_string(), format!("{conversation_id}:1"), diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index b5ae3970f3..dce76bf3d2 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -24,6 +24,7 @@ use crate::compact_remote::run_inline_remote_auto_compact_task; use crate::config::ManagedFeatures; use crate::connectors; use crate::exec_policy::ExecPolicyManager; +use crate::installation_id::resolve_installation_id; use crate::parse_turn_item; use crate::path_utils::normalize_for_native_workdir; use crate::realtime_conversation::RealtimeConversationManager; @@ -1927,6 +1928,7 @@ impl Session { }); } + let installation_id = resolve_installation_id(&config.codex_home).await?; let services = SessionServices { // Initialize the MCP connection manager with an uninitialized // instance. It will be replaced with one created via @@ -1970,6 +1972,7 @@ impl Session { model_client: ModelClient::new( Some(Arc::clone(&auth_manager)), conversation_id, + installation_id, session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index a97af982cd..6e11dd825a 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -255,6 +255,7 @@ fn test_model_client_session() -> crate::client::ModelClientSession { /*auth_manager*/ None, ThreadId::try_from("00000000-0000-4000-8000-000000000001") .expect("test thread id should be valid"), + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), ModelProviderInfo::create_openai_provider(/* base_url */ /*base_url*/ None), codex_protocol::protocol::SessionSource::Exec, /*model_verbosity*/ None, @@ -2772,6 +2773,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { model_client: ModelClient::new( Some(auth_manager.clone()), conversation_id, + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, @@ -3613,6 +3615,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( model_client: ModelClient::new( Some(Arc::clone(&auth_manager)), conversation_id, + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, diff --git a/codex-rs/core/src/installation_id.rs b/codex-rs/core/src/installation_id.rs new file mode 100644 index 0000000000..940e17eb01 --- /dev/null +++ b/codex-rs/core/src/installation_id.rs @@ -0,0 +1,145 @@ +use std::fs::OpenOptions; +use std::io::Read; +use std::io::Result; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::path::Path; + +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt; +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; + +use tokio::fs; +use uuid::Uuid; + +pub(crate) const INSTALLATION_ID_FILENAME: &str = "installation_id"; + +pub(crate) async fn resolve_installation_id(codex_home: &Path) -> Result { + let path = codex_home.join(INSTALLATION_ID_FILENAME); + fs::create_dir_all(codex_home).await?; + tokio::task::spawn_blocking(move || { + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true); + + #[cfg(unix)] + { + options.mode(0o644); + } + + let mut file = options.open(&path)?; + file.lock()?; + + #[cfg(unix)] + { + let metadata = file.metadata()?; + let current_mode = metadata.permissions().mode() & 0o777; + if current_mode != 0o644 { + let mut permissions = metadata.permissions(); + permissions.set_mode(0o644); + file.set_permissions(permissions)?; + } + } + + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + let trimmed = contents.trim(); + if !trimmed.is_empty() + && let Ok(existing) = Uuid::parse_str(trimmed) + { + return Ok(existing.to_string()); + } + + let installation_id = Uuid::new_v4().to_string(); + file.set_len(0)?; + file.seek(SeekFrom::Start(0))?; + file.write_all(installation_id.as_bytes())?; + file.flush()?; + file.sync_all()?; + + Ok(installation_id) + }) + .await? +} + +#[cfg(test)] +mod tests { + use super::INSTALLATION_ID_FILENAME; + use super::resolve_installation_id; + use pretty_assertions::assert_eq; + use tempfile::TempDir; + use uuid::Uuid; + + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; + + #[tokio::test] + async fn resolve_installation_id_generates_and_persists_uuid() { + let codex_home = TempDir::new().expect("create temp dir"); + let persisted_path = codex_home.path().join(INSTALLATION_ID_FILENAME); + + let installation_id = resolve_installation_id(codex_home.path()) + .await + .expect("resolve installation id"); + + assert_eq!( + std::fs::read_to_string(&persisted_path).expect("read persisted installation id"), + installation_id + ); + assert!(Uuid::parse_str(&installation_id).is_ok()); + + #[cfg(unix)] + { + let mode = std::fs::metadata(&persisted_path) + .expect("read installation id metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o644); + } + } + + #[tokio::test] + async fn resolve_installation_id_reuses_existing_uuid() { + let codex_home = TempDir::new().expect("create temp dir"); + let existing = Uuid::new_v4().to_string().to_uppercase(); + std::fs::write( + codex_home.path().join(INSTALLATION_ID_FILENAME), + existing.clone(), + ) + .expect("write installation id"); + + let resolved = resolve_installation_id(codex_home.path()) + .await + .expect("resolve installation id"); + + assert_eq!( + resolved, + Uuid::parse_str(existing.as_str()) + .expect("parse existing installation id") + .to_string() + ); + } + + #[tokio::test] + async fn resolve_installation_id_rewrites_invalid_file_contents() { + let codex_home = TempDir::new().expect("create temp dir"); + std::fs::write( + codex_home.path().join(INSTALLATION_ID_FILENAME), + "not-a-uuid", + ) + .expect("write invalid installation id"); + + let resolved = resolve_installation_id(codex_home.path()) + .await + .expect("resolve installation id"); + + assert!(Uuid::parse_str(&resolved).is_ok()); + assert_eq!( + std::fs::read_to_string(codex_home.path().join(INSTALLATION_ID_FILENAME)) + .expect("read rewritten installation id"), + resolved + ); + } +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index e13a19b290..83232de734 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -38,6 +38,7 @@ mod flags; mod git_info_tests; mod guardian; mod hook_runtime; +mod installation_id; pub(crate) mod instructions; pub(crate) mod landlock; pub use landlock::spawn_command_under_linux_sandbox; @@ -179,6 +180,7 @@ pub mod util; pub use client::ModelClient; pub use client::ModelClientSession; +pub use client::X_CODEX_INSTALLATION_ID_HEADER; pub use client::X_CODEX_TURN_METADATA_HEADER; pub use client_common::Prompt; pub use client_common::REVIEW_PROMPT; diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 7a6e73ed08..03870beab2 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -31,6 +31,8 @@ fn normalize_git_remote_url(url: &str) -> String { .to_string() } +const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111"; + #[tokio::test] async fn responses_stream_includes_subagent_header_on_review() { core_test_support::skip_if_no_network!(); @@ -98,6 +100,7 @@ async fn responses_stream_includes_subagent_header_on_review() { let client = ModelClient::new( /*auth_manager*/ None, conversation_id, + /*installation_id*/ TEST_INSTALLATION_ID.to_string(), provider.clone(), session_source, config.model_verbosity, @@ -147,6 +150,10 @@ async fn responses_stream_includes_subagent_header_on_review() { Some(expected_window_id.as_str()) ); assert_eq!(request.header("x-codex-parent-thread-id"), None); + assert_eq!( + request.body_json()["client_metadata"]["x-codex-installation-id"].as_str(), + Some(TEST_INSTALLATION_ID) + ); assert_eq!(request.header("x-codex-sandbox"), None); } @@ -218,6 +225,7 @@ async fn responses_stream_includes_subagent_header_on_other() { let client = ModelClient::new( /*auth_manager*/ None, conversation_id, + /*installation_id*/ TEST_INSTALLATION_ID.to_string(), provider.clone(), session_source, config.model_verbosity, @@ -331,6 +339,7 @@ async fn responses_respects_model_info_overrides_from_config() { let client = ModelClient::new( /*auth_manager*/ None, conversation_id, + /*installation_id*/ TEST_INSTALLATION_ID.to_string(), provider.clone(), session_source, config.model_verbosity, diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index cb97e4a3b3..15303a58ff 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -81,6 +81,8 @@ use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; +const INSTALLATION_ID_FILENAME: &str = "installation_id"; + #[expect(clippy::unwrap_used)] fn assert_message_role(request_body: &serde_json::Value, role: &str) { assert_eq!(request_body["role"].as_str().unwrap(), role); @@ -760,10 +762,18 @@ async fn includes_conversation_id_and_model_headers_in_request() { .header("authorization") .expect("authorization header"); let request_originator = request.header("originator").expect("originator header"); + let request_body = request.body_json(); + let installation_id = + std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME)) + .expect("read installation id"); assert_eq!(request_session_id, session_id.to_string()); assert_eq!(request_originator, originator().value); assert_eq!(request_authorization, "Bearer Test API Key"); + assert_eq!( + request_body["client_metadata"]["x-codex-installation-id"].as_str(), + Some(installation_id.as_str()) + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -868,6 +878,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth "unused-api-key", ))), conversation_id, + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), provider, SessionSource::Exec, config.model_verbosity, @@ -1048,11 +1059,18 @@ async fn chatgpt_auth_sends_correct_request() { let request_body = request.body_json(); let session_id = request.header("session_id").expect("session_id header"); + let installation_id = + std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME)) + .expect("read installation id"); assert_eq!(session_id, thread_id.to_string()); assert_eq!(request_originator, originator().value); assert_eq!(request_authorization, "Bearer Access Token"); assert_eq!(request_chatgpt_account_id, "account_id"); + assert_eq!( + request_body["client_metadata"]["x-codex-installation-id"].as_str(), + Some(installation_id.as_str()) + ); assert!(request_body["stream"].as_bool().unwrap()); assert_eq!( request_body["include"][0].as_str().unwrap(), @@ -2179,6 +2197,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { let client = ModelClient::new( /*auth_manager*/ None, conversation_id, + /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), provider.clone(), SessionSource::Exec, config.model_verbosity, diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 8bf45a23dd..7ff4a9f88d 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -55,6 +55,7 @@ const MODEL: &str = "gpt-5.2-codex"; const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; const WS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; const X_CLIENT_REQUEST_ID_HEADER: &str = "x-client-request-id"; +const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111"; fn assert_request_trace_matches(body: &serde_json::Value, expected_trace: &W3cTraceContext) { let client_metadata = body["client_metadata"] @@ -125,6 +126,10 @@ async fn responses_websocket_streams_request() { handshake.header(X_CLIENT_REQUEST_ID_HEADER), Some(harness.conversation_id.to_string()) ); + assert_eq!( + body["client_metadata"]["x-codex-installation-id"].as_str(), + Some(TEST_INSTALLATION_ID) + ); server.shutdown().await; } @@ -1756,6 +1761,7 @@ async fn websocket_harness_with_provider_options( let client = ModelClient::new( /*auth_manager*/ None, conversation_id, + /*installation_id*/ TEST_INSTALLATION_ID.to_string(), provider.clone(), SessionSource::Exec, config.model_verbosity, From 0b9e42f6f78ba7eb0166b57fa5b0a9d762efee58 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 7 Apr 2026 10:19:16 -0700 Subject: [PATCH 20/28] fix(guardian): don't throw away transcript when over budget (#16956) ## Description This PR changes guardian transcript compaction so oversized conversations no longer collapse into a nearly empty placeholder. Before this change, if the retained user history alone exceeded the message budget, guardian would replace the entire transcript with ``! That meant approvals, especially network approvals, could lose the recent tool call and tool result that explained what guardian was actually reviewing. Now we keep a compact but usable transcript instead of dropping it all. ### Before ``` The following is the Codex agent history whose request action you are assessing... >>> TRANSCRIPT START >>> TRANSCRIPT END Conversation transcript omitted due to size. The Codex agent has requested the following action: >>> APPROVAL REQUEST START Retry reason: Sandbox blocked outbound network access. Assess the exact planned action below. Use read-only tool checks when local state matters. Planned action JSON: { "tool": "network_access", "target": "https://example.com:443", "host": "example.com", "protocol": "https", "port": 443 } >>> APPROVAL REQUEST END ``` ### After ``` The following is the Codex agent history whose request action you are assessing... >>> TRANSCRIPT START [1] user: Please investigate why uploads to example.com are failing and retry if needed. [8] user: If the request looks correct, go ahead and try again with network access. [9] tool shell call: {"command":["curl","-X","POST","https://example.com/upload"],"cwd":"/repo"} [10] tool shell result: sandbox blocked outbound network access >>> TRANSCRIPT END Some conversation entries were omitted. The Codex agent has requested the following action: >>> APPROVAL REQUEST START Retry reason: Sandbox blocked outbound network access. Assess the exact planned action below. Use read-only tool checks when local state matters. Planned action JSON: { "tool": "network_access", "target": "https://example.com:443", "host": "example.com", "protocol": "https", "port": 443 } >>> APPROVAL REQUEST END ``` --- codex-rs/core/src/guardian/mod.rs | 2 +- codex-rs/core/src/guardian/prompt.rs | 59 +++++++++++++------ codex-rs/core/src/guardian/tests.rs | 51 +++++++++++++++- .../src/tools/handlers/multi_agents_tests.rs | 1 + 4 files changed, 93 insertions(+), 20 deletions(-) diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index e2b72bd049..1a7add9d38 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -38,7 +38,7 @@ const GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS: usize = 10_000; const GUARDIAN_MAX_TOOL_TRANSCRIPT_TOKENS: usize = 10_000; const GUARDIAN_MAX_MESSAGE_ENTRY_TOKENS: usize = 2_000; const GUARDIAN_MAX_TOOL_ENTRY_TOKENS: usize = 1_000; -const GUARDIAN_MAX_ACTION_STRING_TOKENS: usize = 1_000; +const GUARDIAN_MAX_ACTION_STRING_TOKENS: usize = 16_000; const GUARDIAN_APPROVAL_RISK_THRESHOLD: u8 = 80; const GUARDIAN_RECENT_ENTRY_LIMIT: usize = 40; const TRUNCATION_TAG: &str = "truncated"; diff --git a/codex-rs/core/src/guardian/prompt.rs b/codex-rs/core/src/guardian/prompt.rs index 5741a65fc0..7558c005b3 100644 --- a/codex-rs/core/src/guardian/prompt.rs +++ b/codex-rs/core/src/guardian/prompt.rs @@ -107,16 +107,22 @@ pub(crate) async fn build_guardian_prompt_items( Ok(items) } -/// Keeps all user turns plus a bounded amount of recent assistant/tool context. +/// Renders a compact guardian transcript from the retained history entries, +/// which are only user, assistant, and tool call entries. /// -/// The pruning strategy is intentionally simple and reviewable: -/// - always retain user messages because they carry authorization and intent -/// - walk recent non-user entries from newest to oldest -/// - keep them only while the message/tool budgets allow -/// - reserve a separate tool budget so tool evidence cannot crowd out the human -/// conversation +/// Selection is intentionally simple and predictable: +/// - each entry is truncated to its per-entry cap +/// - user and assistant entries share the message budget +/// - tool calls/results use a separate tool budget so tool evidence cannot +/// crowd out the human conversation +/// - if all user turns fit, keep them all +/// - otherwise keep the first and latest user turns as anchors, then fill the +/// remaining message budget with other user turns from newest to oldest +/// - after user turns are selected, keep recent non-user entries from newest to +/// oldest while the budgets and recent-entry limit allow /// -/// User messages are never dropped unless the entire transcript must be omitted. +/// Returns the rendered transcript plus an omission note when some entries were +/// skipped. pub(crate) fn render_guardian_transcript_entries( entries: &[GuardianTranscriptEntry], ) -> (Vec, Option) { @@ -143,20 +149,38 @@ pub(crate) fn render_guardian_transcript_entries( let mut included = vec![false; entries.len()]; let mut message_tokens = 0usize; let mut tool_tokens = 0usize; + let user_indices = entries + .iter() + .enumerate() + .filter_map(|(index, entry)| entry.kind.is_user().then_some(index)) + .collect::>(); - for (index, entry) in entries.iter().enumerate() { - if !entry.kind.is_user() { + if let Some(&first_user_index) = user_indices.first() { + included[first_user_index] = true; + message_tokens += rendered_entries[first_user_index].1; + } + + if let Some(&last_user_index) = user_indices.last() + && !included[last_user_index] + && message_tokens + rendered_entries[last_user_index].1 + <= GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS + { + included[last_user_index] = true; + message_tokens += rendered_entries[last_user_index].1; + } + + for &index in user_indices.iter().rev() { + if included[index] { continue; } - message_tokens += rendered_entries[index].1; - if message_tokens > GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS { - return ( - vec!["".to_string()], - Some("Conversation transcript omitted due to size.".to_string()), - ); + let token_count = rendered_entries[index].1; + if message_tokens + token_count > GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS { + continue; } + included[index] = true; + message_tokens += token_count; } let mut retained_non_user_entries = 0usize; @@ -192,8 +216,7 @@ pub(crate) fn render_guardian_transcript_entries( .map(|(index, _)| rendered_entries[index].0.clone()) .collect::>(); let omitted_any = included.iter().any(|included_entry| !included_entry); - let omission_note = - omitted_any.then(|| "Earlier conversation entries were omitted.".to_string()); + let omission_note = omitted_any.then(|| "Some conversation entries were omitted.".to_string()); (transcript, omission_note) } diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 1cd732f030..2d6ddc7c31 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -260,7 +260,7 @@ fn guardian_truncate_text_keeps_prefix_suffix_and_xml_marker() { #[test] fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json::Result<()> { - let patch = "line\n".repeat(10_000); + let patch = "line\n".repeat(100_000); let action = GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: PathBuf::from("/tmp"), @@ -271,6 +271,7 @@ fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json:: let rendered = format_guardian_action_pretty(&action)?; assert!(rendered.contains("\"tool\": \"apply_patch\"")); + assert!(rendered.contains(">(); + entries.extend([ + GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::Tool("tool shell call".to_string()), + text: serde_json::json!({ + "command": ["curl", "-X", "POST", "https://example.com/upload"], + "cwd": "/repo", + }) + .to_string(), + }, + GuardianTranscriptEntry { + kind: GuardianTranscriptEntryKind::Tool("tool shell result".to_string()), + text: "sandbox blocked outbound network access".to_string(), + }, + ]); + + let (transcript, omission) = render_guardian_transcript_entries(&entries); + + assert!( + transcript + .iter() + .any(|entry| entry.starts_with("[1] user: ")) + ); + assert!(transcript.iter().any(|entry| { + entry.contains("tool shell call:") + && entry.contains("curl") + && entry.contains("https://example.com/upload") + })); + assert!( + transcript + .iter() + .any(|entry| entry + .contains("tool shell result: sandbox blocked outbound network access")) + ); + assert_eq!( + omission, + Some("Some conversation entries were omitted.".to_string()) + ); +} + #[test] fn parse_guardian_assessment_extracts_embedded_json() { let parsed = parse_guardian_assessment(Some( diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 7fec089320..5f09c248a4 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -129,6 +129,7 @@ async fn wait_for_turn_aborted( EventMsg::TurnAborted(TurnAbortedEvent { turn_id: Some(ref turn_id), ref reason, + .. }) if turn_id == expected_turn_id && *reason == expected_reason ) { break; From f1a2b920f977b64c23ee24489c13aa3b1281ebf8 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 7 Apr 2026 10:52:08 -0700 Subject: [PATCH 21/28] [codex] Make AbsolutePathBuf joins infallible (#16981) Having to check for errors every time join is called is painful and unnecessary. --- codex-rs/Cargo.lock | 1 - codex-rs/app-server/src/fs_watch.rs | 14 +- .../app-server/tests/suite/v2/config_rpc.rs | 4 +- codex-rs/core/src/codex_delegate.rs | 106 ++++++----- codex-rs/core/src/codex_tests.rs | 5 +- codex-rs/core/src/config/mod.rs | 2 +- codex-rs/core/src/config/permissions.rs | 2 +- codex-rs/core/src/config/service.rs | 3 +- codex-rs/core/src/config_loader/mod.rs | 6 +- codex-rs/core/src/config_loader/tests.rs | 3 +- codex-rs/core/src/exec_policy.rs | 3 +- codex-rs/core/src/network_proxy_loader.rs | 10 +- codex-rs/core/src/plugins/marketplace.rs | 21 +-- .../core/src/plugins/marketplace_tests.rs | 12 +- codex-rs/core/src/project_doc.rs | 2 +- codex-rs/core/src/project_doc_tests.rs | 3 +- codex-rs/core/src/safety_tests.rs | 2 +- .../core/src/tools/handlers/apply_patch.rs | 2 +- codex-rs/core/src/tools/js_repl/mod_tests.rs | 6 +- codex-rs/core/tests/suite/agents_md.rs | 25 +-- .../core/tests/suite/compact_resume_fork.rs | 2 +- .../core/tests/suite/hierarchical_agents.rs | 2 +- codex-rs/core/tests/suite/view_image.rs | 8 +- codex-rs/git-utils/src/info.rs | 4 +- codex-rs/hooks/src/engine/discovery.rs | 11 +- .../src/model_provider_info_tests.rs | 2 +- codex-rs/protocol/src/permissions.rs | 87 +++------ codex-rs/protocol/src/protocol.rs | 46 ++--- codex-rs/sandboxing/src/manager_tests.rs | 4 +- .../sandboxing/src/policy_transforms_tests.rs | 13 +- codex-rs/shell-command/src/powershell.rs | 6 +- .../src/unix/escalate_server.rs | 4 +- codex-rs/skills/src/lib.rs | 25 +-- codex-rs/tui/src/app.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 10 +- .../tui/src/chatwidget/tests/exec_flow.rs | 6 +- codex-rs/utils/absolute-path/Cargo.toml | 1 - .../utils/absolute-path/src/absolutize.rs | 167 ++++++++++++++++++ codex-rs/utils/absolute-path/src/lib.rs | 42 +++-- codex-rs/utils/path-utils/src/lib.rs | 2 +- 40 files changed, 361 insertions(+), 315 deletions(-) create mode 100644 codex-rs/utils/absolute-path/src/absolutize.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 3578fd8c63..a05a5af367 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2878,7 +2878,6 @@ name = "codex-utils-absolute-path" version = "0.0.0" dependencies = [ "dirs", - "path-absolutize", "pretty_assertions", "schemars 0.8.22", "serde", diff --git a/codex-rs/app-server/src/fs_watch.rs b/codex-rs/app-server/src/fs_watch.rs index 309bee4a64..c8214c2b8a 100644 --- a/codex-rs/app-server/src/fs_watch.rs +++ b/codex-rs/app-server/src/fs_watch.rs @@ -158,19 +158,7 @@ impl FsWatchManager { let mut changed_paths = event .paths .into_iter() - .filter_map(|path| { - match AbsolutePathBuf::resolve_path_against_base(&path, &watch_root) { - Ok(path) => Some(path), - Err(err) => { - warn!( - "failed to normalize watch event path ({}) for {}: {err}", - path.display(), - watch_root.display() - ); - None - } - } - }) + .map(|path| AbsolutePathBuf::resolve_path_against_base(&path, &watch_root)) .collect::>(); changed_paths.sort_by(|left, right| left.as_path().cmp(right.as_path())); if !changed_paths.is_empty() { diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index 23c9a6c6c2..99e33eb6b9 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -546,7 +546,7 @@ model = "gpt-old" ) .await??; let write: ConfigWriteResponse = to_response(write_resp)?; - let expected_file_path = AbsolutePathBuf::resolve_path_against_base("config.toml", codex_home)?; + let expected_file_path = AbsolutePathBuf::resolve_path_against_base("config.toml", codex_home); assert_eq!(write.status, WriteStatus::Ok); assert_eq!(write.file_path, expected_file_path); @@ -647,7 +647,7 @@ async fn config_batch_write_applies_multiple_edits() -> Result<()> { .await??; let batch_write: ConfigWriteResponse = to_response(batch_resp)?; assert_eq!(batch_write.status, WriteStatus::Ok); - let expected_file_path = AbsolutePathBuf::resolve_path_against_base("config.toml", codex_home)?; + let expected_file_path = AbsolutePathBuf::resolve_path_against_base("config.toml", codex_home); assert_eq!(batch_write.file_path, expected_file_path); let read_id = mcp diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index ab6324efa2..aef0a92d76 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -528,64 +528,60 @@ async fn handle_patch_approval( } = event; let approval_id = call_id.clone(); let guardian_decision = if routes_approval_to_guardian(parent_ctx) { - let maybe_files = changes + let files = changes .keys() - .map(|path| parent_ctx.cwd.join(path).ok()) - .collect::>>(); - if let Some(files) = maybe_files { - let review_cancel = cancel_token.child_token(); - let patch = changes - .iter() - .map(|(path, change)| match change { - codex_protocol::protocol::FileChange::Add { content } => { - format!("*** Add File: {}\n{}", path.display(), content) + .map(|path| parent_ctx.cwd.join(path)) + .collect::>(); + let review_cancel = cancel_token.child_token(); + let patch = changes + .iter() + .map(|(path, change)| match change { + codex_protocol::protocol::FileChange::Add { content } => { + format!("*** Add File: {}\n{}", path.display(), content) + } + codex_protocol::protocol::FileChange::Delete { content } => { + format!("*** Delete File: {}\n{}", path.display(), content) + } + codex_protocol::protocol::FileChange::Update { + unified_diff, + move_path, + } => { + if let Some(move_path) = move_path { + format!( + "*** Update File: {}\n*** Move to: {}\n{}", + path.display(), + move_path.display(), + unified_diff + ) + } else { + format!("*** Update File: {}\n{}", path.display(), unified_diff) } - codex_protocol::protocol::FileChange::Delete { content } => { - format!("*** Delete File: {}\n{}", path.display(), content) - } - codex_protocol::protocol::FileChange::Update { - unified_diff, - move_path, - } => { - if let Some(move_path) = move_path { - format!( - "*** Update File: {}\n*** Move to: {}\n{}", - path.display(), - move_path.display(), - unified_diff - ) - } else { - format!("*** Update File: {}\n{}", path.display(), unified_diff) - } - } - }) - .collect::>() - .join("\n"); - let review_rx = spawn_guardian_review( - Arc::clone(parent_session), - Arc::clone(parent_ctx), - GuardianApprovalRequest::ApplyPatch { - id: approval_id.clone(), - cwd: parent_ctx.cwd.to_path_buf(), - files, - patch, - }, - reason.clone(), - review_cancel.clone(), - ); - Some( - await_approval_with_cancel( - async move { review_rx.await.unwrap_or_default() }, - parent_session, - &approval_id, - cancel_token, - Some(&review_cancel), - ) - .await, + } + }) + .collect::>() + .join("\n"); + let review_rx = spawn_guardian_review( + Arc::clone(parent_session), + Arc::clone(parent_ctx), + GuardianApprovalRequest::ApplyPatch { + id: approval_id.clone(), + cwd: parent_ctx.cwd.to_path_buf(), + files, + patch, + }, + reason.clone(), + review_cancel.clone(), + ); + Some( + await_approval_with_cancel( + async move { review_rx.await.unwrap_or_default() }, + parent_session, + &approval_id, + cancel_token, + Some(&review_cancel), ) - } else { - None - } + .await, + ) } else { None }; diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index 6e11dd825a..29fe9df89c 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -2512,10 +2512,7 @@ async fn session_configuration_apply_rederives_legacy_file_system_policy_on_cwd_ #[tokio::test] async fn session_update_settings_keeps_runtime_cwds_absolute() { let (session, turn_context) = make_session_and_context().await; - let updated_cwd = turn_context - .cwd - .join("project") - .expect("resolve project dir"); + let updated_cwd = turn_context.cwd.join("project"); std::fs::create_dir_all(updated_cwd.as_path()).expect("create project dir"); session diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 84873baf00..3e9626866b 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1449,7 +1449,7 @@ impl Config { let mut additional_writable_roots: Vec = additional_writable_roots .into_iter() .map(|path| AbsolutePathBuf::resolve_path_against_base(path, resolved_cwd.as_path())) - .collect::, _>>()?; + .collect(); let active_project = cfg .get_active_project(resolved_cwd.as_path()) .unwrap_or(ProjectConfig { trust_level: None }); diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rs index f8284d4ae7..826d0139bf 100644 --- a/codex-rs/core/src/config/permissions.rs +++ b/codex-rs/core/src/config/permissions.rs @@ -182,7 +182,7 @@ fn compile_scoped_filesystem_path( let subpath = parse_relative_subpath(subpath)?; let base = parse_absolute_path(path)?; - let path = AbsolutePathBuf::resolve_path_against_base(&subpath, base.as_path())?; + let path = AbsolutePathBuf::resolve_path_against_base(&subpath, base.as_path()); Ok(FileSystemPath::Path { path }) } diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index d2426b1385..80d4b6bdd9 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -265,8 +265,7 @@ impl ConfigService { edits: Vec<(String, JsonValue, MergeStrategy)>, ) -> Result { let allowed_path = - AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, &self.codex_home) - .map_err(|err| ConfigServiceError::io("failed to resolve user config path", err))?; + AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, &self.codex_home); let provided_path = match file_path { Some(path) => AbsolutePathBuf::from_absolute_path(PathBuf::from(path)) .map_err(|err| ConfigServiceError::io("failed to resolve user config path", err))?, diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 8961c00aa9..f40482fd57 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -187,7 +187,7 @@ pub async fn load_config_layers_state( // Add a layer for $CODEX_HOME/config.toml if it exists. Note if the file // exists, but is malformed, then this error should be propagated to the // user. - let user_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home)?; + let user_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home); let user_layer = load_config_toml_for_required_layer(&user_file, |config_toml| { ConfigLayerEntry::new( ConfigLayerSource::User { @@ -809,7 +809,7 @@ async fn load_project_layers( if dot_codex_abs == codex_home_abs || dot_codex_normalized == codex_home_normalized { continue; } - let config_file = dot_codex_abs.join(CONFIG_TOML_FILE)?; + let config_file = dot_codex_abs.join(CONFIG_TOML_FILE); match tokio::fs::read_to_string(&config_file).await { Ok(contents) => { let config: TomlValue = match toml::from_str(&contents) { @@ -945,7 +945,7 @@ foo = "xyzzy" expected_toml_value.insert( "model_instructions_file".to_string(), TomlValue::String( - AbsolutePathBuf::resolve_path_against_base("./some_file.md", base_dir)? + AbsolutePathBuf::resolve_path_against_base("./some_file.md", base_dir) .as_path() .to_string_lossy() .to_string(), diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 629730cbf2..d476b8e6fd 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -78,7 +78,7 @@ async fn cli_overrides_resolve_relative_paths_against_cwd() -> std::io::Result<( .build() .await?; - let expected = AbsolutePathBuf::resolve_path_against_base("run-logs", cwd_path)?; + let expected = AbsolutePathBuf::resolve_path_against_base("run-logs", cwd_path); assert_eq!(config.log_dir, expected.to_path_buf()); Ok(()) } @@ -250,7 +250,6 @@ async fn returns_empty_when_all_layers_missing() { &ConfigLayerEntry { name: super::ConfigLayerSource::User { file: AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, tmp.path()) - .expect("resolve user config.toml path") }, config: TomlValue::Table(toml::map::Map::new()), raw_toml: None, diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index dbfab81d32..98bb815e91 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -494,8 +494,7 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result Vec { let path = match &layer.name { ConfigLayerSource::System { file } => Some(file.as_path().to_path_buf()), ConfigLayerSource::User { file } => Some(file.as_path().to_path_buf()), - ConfigLayerSource::Project { dot_codex_folder } => dot_codex_folder - .join(CONFIG_TOML_FILE) - .ok() - .map(|p| p.as_path().to_path_buf()), + ConfigLayerSource::Project { dot_codex_folder } => Some( + dot_codex_folder + .join(CONFIG_TOML_FILE) + .as_path() + .to_path_buf(), + ), ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => { Some(file.as_path().to_path_buf()) } diff --git a/codex-rs/core/src/plugins/marketplace.rs b/codex-rs/core/src/plugins/marketplace.rs index ee775262aa..0d7c68c1e5 100644 --- a/codex-rs/core/src/plugins/marketplace.rs +++ b/codex-rs/core/src/plugins/marketplace.rs @@ -299,20 +299,18 @@ fn discover_marketplace_paths_from_roots( for root in additional_roots { // Curated marketplaces can now come from an HTTP-downloaded directory that is not a git // checkout, so check the root directly before falling back to repo-root discovery. - if let Ok(path) = root.join(MARKETPLACE_RELATIVE_PATH) - && path.as_path().is_file() - && !paths.contains(&path) - { + let path = root.join(MARKETPLACE_RELATIVE_PATH); + if path.as_path().is_file() && !paths.contains(&path) { paths.push(path); continue; } if let Some(repo_root) = get_git_repo_root(root.as_path()) && let Ok(repo_root) = AbsolutePathBuf::try_from(repo_root) - && let Ok(path) = repo_root.join(MARKETPLACE_RELATIVE_PATH) - && path.as_path().is_file() - && !paths.contains(&path) { - paths.push(path); + let path = repo_root.join(MARKETPLACE_RELATIVE_PATH); + if path.as_path().is_file() && !paths.contains(&path) { + paths.push(path); + } } } @@ -370,12 +368,7 @@ fn resolve_plugin_source_path( // `marketplace.json` lives under `/.agents/plugins/`, but local plugin paths // are resolved relative to ``, not relative to the `plugins/` directory. - marketplace_root_dir(marketplace_path)? - .join(relative_source_path) - .map_err(|err| MarketplaceError::InvalidMarketplaceFile { - path: marketplace_path.to_path_buf(), - message: format!("plugin source path must resolve to an absolute path: {err}"), - }) + Ok(marketplace_root_dir(marketplace_path)?.join(relative_source_path)) } } } diff --git a/codex-rs/core/src/plugins/marketplace_tests.rs b/codex-rs/core/src/plugins/marketplace_tests.rs index d3cf55425e..226ae3ff6e 100644 --- a/codex-rs/core/src/plugins/marketplace_tests.rs +++ b/codex-rs/core/src/plugins/marketplace_tests.rs @@ -756,18 +756,16 @@ fn resolve_marketplace_plugin_rejects_non_relative_local_paths() { ) .unwrap(); - let err = resolve_marketplace_plugin( - &AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json")).unwrap(), - "local-plugin", - Some(Product::Codex), - ) - .unwrap_err(); + let marketplace_path = + AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json")).unwrap(); + let err = resolve_marketplace_plugin(&marketplace_path, "local-plugin", Some(Product::Codex)) + .unwrap_err(); assert_eq!( err.to_string(), format!( "invalid marketplace file `{}`: local plugin source path must start with `./`", - repo_root.join(".agents/plugins/marketplace.json").display() + marketplace_path.display() ) ); } diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 236c25a3c5..e7321695a7 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -288,7 +288,7 @@ pub async fn discover_project_doc_paths( let candidate_filenames = candidate_filenames(config); for d in search_dirs { for name in &candidate_filenames { - let candidate = d.join(name)?; + let candidate = d.join(name); match fs.get_metadata(&candidate).await { Ok(md) if md.is_file => { found.push(candidate); diff --git a/codex-rs/core/src/project_doc_tests.rs b/codex-rs/core/src/project_doc_tests.rs index be9cb44b28..c8caf2ff9a 100644 --- a/codex-rs/core/src/project_doc_tests.rs +++ b/codex-rs/core/src/project_doc_tests.rs @@ -334,8 +334,7 @@ async fn project_root_markers_are_honored_for_agents_discovery() { ) .expect("absolute parent doc path"); let expected_child = AbsolutePathBuf::try_from( - dunce::canonicalize(cfg.cwd.join("AGENTS.md").expect("absolute child doc path")) - .expect("canonical child doc path"), + dunce::canonicalize(cfg.cwd.join("AGENTS.md")).expect("canonical child doc path"), ) .expect("absolute child doc path"); assert_eq!(discovery.len(), 2); diff --git a/codex-rs/core/src/safety_tests.rs b/codex-rs/core/src/safety_tests.rs index 5ebeb64e0e..6e5795e59a 100644 --- a/codex-rs/core/src/safety_tests.rs +++ b/codex-rs/core/src/safety_tests.rs @@ -243,7 +243,7 @@ fn explicit_read_only_subpaths_prevent_auto_approval_for_external_sandbox() { let tmp = TempDir::new().unwrap(); let cwd = tmp.path().to_path_buf(); let blocked_path = cwd.join("docs").join("blocked.txt"); - let docs_absolute = AbsolutePathBuf::resolve_path_against_base("docs", &cwd).unwrap(); + let docs_absolute = AbsolutePathBuf::resolve_path_against_base("docs", &cwd); let action = ApplyPatchAction::new_add_for_test(&blocked_path, "".to_string()); let sandbox_policy = SandboxPolicy::ExternalSandbox { network_access: codex_protocol::protocol::NetworkAccess::Restricted, diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 00b1173aa4..a972566b92 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -56,7 +56,7 @@ fn file_paths_for_action(action: &ApplyPatchAction) -> Vec { } fn to_abs_path(cwd: &Path, path: &Path) -> Option { - AbsolutePathBuf::resolve_path_against_base(path, cwd).ok() + Some(AbsolutePathBuf::resolve_path_against_base(path, cwd)) } fn write_permissions_for_paths( diff --git a/codex-rs/core/src/tools/js_repl/mod_tests.rs b/codex-rs/core/src/tools/js_repl/mod_tests.rs index bbc0f50dcd..bdf6931330 100644 --- a/codex-rs/core/src/tools/js_repl/mod_tests.rs +++ b/codex-rs/core/src/tools/js_repl/mod_tests.rs @@ -1028,7 +1028,7 @@ async fn js_repl_waits_for_unawaited_tool_calls_before_completion() -> anyhow::R let marker = turn .cwd - .join(format!("js-repl-unawaited-marker-{}.txt", Uuid::new_v4()))?; + .join(format!("js-repl-unawaited-marker-{}.txt", Uuid::new_v4())); let marker_json = serde_json::to_string(&marker.to_string_lossy().to_string())?; let result = manager .execute( @@ -1073,10 +1073,10 @@ async fn js_repl_persisted_tool_helpers_work_across_cells() -> anyhow::Result<() let global_marker = turn .cwd - .join(format!("js-repl-global-helper-{}.txt", Uuid::new_v4()))?; + .join(format!("js-repl-global-helper-{}.txt", Uuid::new_v4())); let lexical_marker = turn .cwd - .join(format!("js-repl-lexical-helper-{}.txt", Uuid::new_v4()))?; + .join(format!("js-repl-lexical-helper-{}.txt", Uuid::new_v4())); let global_marker_json = serde_json::to_string(&global_marker.to_string_lossy().to_string())?; let lexical_marker_json = serde_json::to_string(&lexical_marker.to_string_lossy().to_string())?; diff --git a/codex-rs/core/tests/suite/agents_md.rs b/codex-rs/core/tests/suite/agents_md.rs index 7fbcc0703c..ed62c90388 100644 --- a/codex-rs/core/tests/suite/agents_md.rs +++ b/codex-rs/core/tests/suite/agents_md.rs @@ -31,10 +31,8 @@ async fn agents_instructions(mut builder: TestCodexBuilder) -> Result { async fn agents_override_is_preferred_over_agents_md() -> Result<()> { let instructions = agents_instructions(test_codex().with_workspace_setup(|cwd, fs| async move { - let agents_md = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); - let override_md = cwd - .join("AGENTS.override.md") - .expect("absolute AGENTS.override.md path"); + let agents_md = cwd.join("AGENTS.md"); + let override_md = cwd.join("AGENTS.override.md"); fs.write_file(&agents_md, b"base doc".to_vec()).await?; fs.write_file(&override_md, b"override doc".to_vec()) .await?; @@ -62,8 +60,8 @@ async fn configured_fallback_is_used_when_agents_candidate_is_directory() -> Res config.project_doc_fallback_filenames = vec!["WORKFLOW.md".to_string()]; }) .with_workspace_setup(|cwd, fs| async move { - let agents_dir = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); - let fallback = cwd.join("WORKFLOW.md").expect("absolute WORKFLOW.md path"); + let agents_dir = cwd.join("AGENTS.md"); + let fallback = cwd.join("WORKFLOW.md"); fs.create_directory(&agents_dir, CreateDirectoryOptions { recursive: true }) .await?; fs.write_file(&fallback, b"fallback doc".to_vec()).await?; @@ -85,10 +83,7 @@ async fn agents_docs_are_concatenated_from_project_root_to_cwd() -> Result<()> { let instructions = agents_instructions( test_codex() .with_config(|config| { - config.cwd = config - .cwd - .join("nested/workspace") - .expect("absolute nested workspace path"); + config.cwd = config.cwd.join("nested/workspace"); }) .with_workspace_setup(|cwd, fs| async move { let nested = cwd.clone(); @@ -96,13 +91,9 @@ async fn agents_docs_are_concatenated_from_project_root_to_cwd() -> Result<()> { .parent() .and_then(|parent| parent.parent()) .expect("nested workspace should have a project root ancestor"); - let root_agents = root - .join("AGENTS.md") - .expect("absolute root AGENTS.md path"); - let git_marker = root.join(".git").expect("absolute .git path"); - let nested_agents = nested - .join("AGENTS.md") - .expect("absolute nested AGENTS.md path"); + let root_agents = root.join("AGENTS.md"); + let git_marker = root.join(".git"); + let nested_agents = nested.join("AGENTS.md"); fs.create_directory(&nested, CreateDirectoryOptions { recursive: true }) .await?; diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index d47ed7c94c..8f4f2ae755 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -567,7 +567,7 @@ async fn snapshot_rollback_followup_turn_trims_context_updates() -> Result<()> { user_turn(&conversation, TURN_ONE_USER).await; - let override_cwd = config.cwd.join(PRETURN_CONTEXT_DIFF_CWD)?; + let override_cwd = config.cwd.join(PRETURN_CONTEXT_DIFF_CWD); std::fs::create_dir_all(&override_cwd)?; conversation .submit(Op::OverrideTurnContext { diff --git a/codex-rs/core/tests/suite/hierarchical_agents.rs b/codex-rs/core/tests/suite/hierarchical_agents.rs index bddc1a5276..f0960c0724 100644 --- a/codex-rs/core/tests/suite/hierarchical_agents.rs +++ b/codex-rs/core/tests/suite/hierarchical_agents.rs @@ -26,7 +26,7 @@ async fn hierarchical_agents_appends_to_project_doc_in_user_instructions() { .expect("test config should allow feature update"); }) .with_workspace_setup(|cwd, fs| async move { - let agents_md = cwd.join("AGENTS.md").expect("absolute AGENTS.md path"); + let agents_md = cwd.join("AGENTS.md"); fs.write_file(&agents_md, b"be nice".to_vec()).await?; Ok::<(), anyhow::Error>(()) }); diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index f16d3c2b18..b213e305e4 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -85,7 +85,7 @@ fn png_bytes(width: u32, height: u32, rgba: [u8; 4]) -> anyhow::Result> } async fn create_workspace_directory(test: &TestCodex, rel_path: &str) -> anyhow::Result { - let abs_path = test.config.cwd.join(rel_path)?; + let abs_path = test.config.cwd.join(rel_path); test.fs() .create_directory(&abs_path, CreateDirectoryOptions { recursive: true }) .await?; @@ -97,7 +97,7 @@ async fn write_workspace_file( rel_path: &str, contents: Vec, ) -> anyhow::Result { - let abs_path = test.config.cwd.join(rel_path)?; + let abs_path = test.config.cwd.join(rel_path); if let Some(parent) = abs_path.parent() { test.fs() .create_directory(&parent, CreateDirectoryOptions { recursive: true }) @@ -226,7 +226,7 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { let cwd = config.cwd.clone(); let rel_path = "assets/example.png"; - let abs_path = cwd.join(rel_path)?; + let abs_path = cwd.join(rel_path); let original_width = 2304; let original_height = 864; write_workspace_png( @@ -1258,7 +1258,7 @@ async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> { } = &test; let rel_path = "missing/example.png"; - let abs_path = config.cwd.join(rel_path)?; + let abs_path = config.cwd.join(rel_path); let call_id = "view-image-missing"; let arguments = serde_json::json!({ "path": rel_path }).to_string(); diff --git a/codex-rs/git-utils/src/info.rs b/codex-rs/git-utils/src/info.rs index 06e39b5655..048a8cedb6 100644 --- a/codex-rs/git-utils/src/info.rs +++ b/codex-rs/git-utils/src/info.rs @@ -632,9 +632,7 @@ pub fn resolve_root_git_project_for_trust(cwd: &Path) -> Option { } let git_dir_path = canonicalize_or_raw( - AbsolutePathBuf::resolve_path_against_base(git_dir_rel, &repo_root) - .ok()? - .into_path_buf(), + AbsolutePathBuf::resolve_path_against_base(git_dir_rel, &repo_root).into_path_buf(), ); let worktrees_dir = git_dir_path.parent()?; if worktrees_dir.file_name() != Some(OsStr::new("worktrees")) { diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index f39eb77438..465caa376d 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -35,16 +35,7 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) - let Some(folder) = layer.config_folder() else { continue; }; - let source_path = match folder.join("hooks.json") { - Ok(source_path) => source_path, - Err(err) => { - warnings.push(format!( - "failed to resolve hooks config path from {}: {err}", - folder.display() - )); - continue; - } - }; + let source_path = folder.join("hooks.json"); if !source_path.as_path().is_file() { continue; } diff --git a/codex-rs/model-provider-info/src/model_provider_info_tests.rs b/codex-rs/model-provider-info/src/model_provider_info_tests.rs index e456a6a5c2..bdc2e73b1a 100644 --- a/codex-rs/model-provider-info/src/model_provider_info_tests.rs +++ b/codex-rs/model-provider-info/src/model_provider_info_tests.rs @@ -152,7 +152,7 @@ args = ["--format=text"] args: vec!["--format=text".to_string()], timeout_ms: NonZeroU64::new(5_000).unwrap(), refresh_interval_ms: 300_000, - cwd: AbsolutePathBuf::resolve_path_against_base(".", base_dir.path()).unwrap(), + cwd: AbsolutePathBuf::resolve_path_against_base(".", base_dir.path()), }) ); } diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs index 4aa1c7b36f..416d291fd1 100644 --- a/codex-rs/protocol/src/permissions.rs +++ b/codex-rs/protocol/src/permissions.rs @@ -522,7 +522,7 @@ impl FileSystemSandboxPolicy { if suffix.as_os_str().is_empty() { return None; } - root.join(suffix).ok() + Some(root.join(suffix)) }) } } else { @@ -921,7 +921,7 @@ fn resolve_candidate_path(path: &Path, cwd: &Path) -> Option { if path.is_absolute() { AbsolutePathBuf::from_absolute_path(path).ok() } else { - AbsolutePathBuf::resolve_path_against_base(path, cwd).ok() + Some(AbsolutePathBuf::resolve_path_against_base(path, cwd)) } } @@ -1032,9 +1032,10 @@ fn resolve_file_system_special_path( FileSystemSpecialPath::ProjectRoots { subpath } => { let cwd = cwd?; match subpath.as_ref() { - Some(subpath) => { - AbsolutePathBuf::resolve_path_against_base(subpath, cwd.as_path()).ok() - } + Some(subpath) => Some(AbsolutePathBuf::resolve_path_against_base( + subpath, + cwd.as_path(), + )), None => Some(cwd.clone()), } } @@ -1100,10 +1101,7 @@ fn default_read_only_subpaths_for_writable_root( protect_missing_dot_codex: bool, ) -> Vec { let mut subpaths: Vec = Vec::new(); - #[allow(clippy::expect_used)] - let top_level_git = writable_root - .join(".git") - .expect(".git is a valid relative path"); + let top_level_git = writable_root.join(".git"); // This applies to typical repos (directory .git), worktrees/submodules // (file .git with gitdir pointer), and bare repos when the gitdir is the // writable root itself. @@ -1119,8 +1117,7 @@ fn default_read_only_subpaths_for_writable_root( subpaths.push(top_level_git); } - #[allow(clippy::expect_used)] - let top_level_agents = writable_root.join(".agents").expect("valid relative path"); + let top_level_agents = writable_root.join(".agents"); if top_level_agents.as_path().is_dir() { subpaths.push(top_level_agents); } @@ -1129,8 +1126,7 @@ fn default_read_only_subpaths_for_writable_root( // default. For the workspace root itself, protect it even before the // directory exists so first-time creation still goes through the // protected-path approval flow. - #[allow(clippy::expect_used)] - let top_level_codex = writable_root.join(".codex").expect("valid relative path"); + let top_level_codex = writable_root.join(".codex"); if protect_missing_dot_codex || top_level_codex.as_path().is_dir() { subpaths.push(top_level_codex); } @@ -1227,16 +1223,7 @@ fn resolve_gitdir_from_file(dot_git: &AbsolutePathBuf) -> Option path, - Err(err) => { - error!( - "Failed to resolve gitdir path {gitdir_raw} from {path}: {err}", - path = dot_git.as_path().display() - ); - return None; - } - }; + let gitdir_path = AbsolutePathBuf::resolve_path_against_base(gitdir_raw, base); if !gitdir_path.as_path().exists() { error!( "Resolved gitdir path {path} does not exist.", @@ -1302,7 +1289,7 @@ mod tests { cwd.path().canonicalize().expect("canonicalize cwd"), ) .expect("absolute canonical root"); - let expected_dot_codex = expected_root.join(".codex").expect("expected .codex path"); + let expected_dot_codex = expected_root.join(".codex"); let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -1329,7 +1316,7 @@ mod tests { cwd.path().canonicalize().expect("canonicalize cwd"), ) .expect("absolute canonical root"); - let explicit_dot_codex = expected_root.join(".codex").expect("expected .codex path"); + let explicit_dot_codex = expected_root.join(".codex"); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { @@ -1359,10 +1346,7 @@ mod tests { ); assert!( policy.can_write_path_with_cwd( - explicit_dot_codex - .join("config.toml") - .expect("config.toml") - .as_path(), + explicit_dot_codex.join("config.toml").as_path(), cwd.path() ) ); @@ -1451,7 +1435,7 @@ mod tests { let link_root = AbsolutePathBuf::from_absolute_path(&link_root).expect("absolute symlinked root"); - let link_blocked = link_root.join("blocked").expect("symlinked blocked path"); + let link_blocked = link_root.join("blocked"); let expected_root = AbsolutePathBuf::from_absolute_path( real_root.canonicalize().expect("canonicalize real root"), ) @@ -1632,16 +1616,12 @@ mod tests { let link_root = AbsolutePathBuf::from_absolute_path(&link_root).expect("absolute symlinked root"); - let link_private = link_root - .join("linked-private") - .expect("symlinked linked-private path"); + let link_private = link_root.join("linked-private"); let expected_root = AbsolutePathBuf::from_absolute_path( real_root.canonicalize().expect("canonicalize real root"), ) .expect("absolute canonical root"); - let expected_linked_private = expected_root - .join("linked-private") - .expect("expected linked-private path"); + let expected_linked_private = expected_root.join("linked-private"); let unexpected_decoy = AbsolutePathBuf::from_absolute_path(decoy.canonicalize().expect("canonicalize decoy")) .expect("absolute canonical decoy"); @@ -1686,16 +1666,12 @@ mod tests { let link_root = AbsolutePathBuf::from_absolute_path(&link_root).expect("absolute symlinked root"); - let link_private = link_root - .join("linked-private") - .expect("symlinked linked-private path"); + let link_private = link_root.join("linked-private"); let expected_root = AbsolutePathBuf::from_absolute_path( real_root.canonicalize().expect("canonicalize real root"), ) .expect("absolute canonical root"); - let expected_linked_private = expected_root - .join("linked-private") - .expect("expected linked-private path"); + let expected_linked_private = expected_root.join("linked-private"); let unexpected_decoy = AbsolutePathBuf::from_absolute_path(decoy.canonicalize().expect("canonicalize decoy")) .expect("absolute canonical decoy"); @@ -1735,14 +1711,12 @@ mod tests { symlink_dir(&root, &alias).expect("create alias symlink"); let root = AbsolutePathBuf::from_absolute_path(&root).expect("absolute root"); - let alias = root.join("alias-root").expect("alias root path"); + let alias = root.join("alias-root"); let expected_root = AbsolutePathBuf::from_absolute_path( root.as_path().canonicalize().expect("canonicalize root"), ) .expect("absolute canonical root"); - let expected_alias = expected_root - .join("alias-root") - .expect("expected alias path"); + let expected_alias = expected_root.join("alias-root"); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { @@ -1848,13 +1822,10 @@ mod tests { #[test] fn resolve_access_with_cwd_uses_most_specific_entry() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); - let docs_private = AbsolutePathBuf::resolve_path_against_base("docs/private", cwd.path()) - .expect("resolve docs/private"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); + let docs_private = AbsolutePathBuf::resolve_path_against_base("docs/private", cwd.path()); let docs_private_public = - AbsolutePathBuf::resolve_path_against_base("docs/private/public", cwd.path()) - .expect("resolve docs/private/public"); + AbsolutePathBuf::resolve_path_against_base("docs/private/public", cwd.path()); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -1901,8 +1872,7 @@ mod tests { #[test] fn split_only_nested_carveouts_need_direct_runtime_enforcement() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -1933,8 +1903,7 @@ mod tests { #[test] fn root_write_with_read_only_child_is_not_full_disk_write() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -1961,8 +1930,7 @@ mod tests { #[test] fn root_deny_does_not_materialize_as_unreadable_root() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let expected_docs = AbsolutePathBuf::from_absolute_path( cwd.path() .canonicalize() @@ -2025,8 +1993,7 @@ mod tests { #[test] fn same_specificity_write_override_keeps_full_disk_write_access() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 4be5620fc4..1f199b149b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1097,10 +1097,7 @@ fn default_read_only_subpaths_for_writable_root( protect_missing_dot_codex: bool, ) -> Vec { let mut subpaths: Vec = Vec::new(); - #[allow(clippy::expect_used)] - let top_level_git = writable_root - .join(".git") - .expect(".git is a valid relative path"); + let top_level_git = writable_root.join(".git"); // This applies to typical repos (directory .git), worktrees/submodules // (file .git with gitdir pointer), and bare repos when the gitdir is the // writable root itself. @@ -1116,8 +1113,7 @@ fn default_read_only_subpaths_for_writable_root( subpaths.push(top_level_git); } - #[allow(clippy::expect_used)] - let top_level_agents = writable_root.join(".agents").expect("valid relative path"); + let top_level_agents = writable_root.join(".agents"); if top_level_agents.as_path().is_dir() { subpaths.push(top_level_agents); } @@ -1126,8 +1122,7 @@ fn default_read_only_subpaths_for_writable_root( // default. For the workspace root itself, protect it even before the // directory exists so first-time creation still goes through the // protected-path approval flow. - #[allow(clippy::expect_used)] - let top_level_codex = writable_root.join(".codex").expect("valid relative path"); + let top_level_codex = writable_root.join(".codex"); if protect_missing_dot_codex || top_level_codex.as_path().is_dir() { subpaths.push(top_level_codex); } @@ -1187,16 +1182,7 @@ fn resolve_gitdir_from_file(dot_git: &AbsolutePathBuf) -> Option path, - Err(err) => { - error!( - "Failed to resolve gitdir path {gitdir_raw} from {path}: {err}", - path = dot_git.as_path().display() - ); - return None; - } - }; + let gitdir_path = AbsolutePathBuf::resolve_path_against_base(gitdir_raw, base); if !gitdir_path.as_path().exists() { error!( "Resolved gitdir path {path} does not exist.", @@ -4034,8 +4020,7 @@ mod tests { .last() .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok()) .expect("filesystem root"); - let blocked = AbsolutePathBuf::resolve_path_against_base("blocked", cwd.path()) - .expect("resolve blocked"); + let blocked = AbsolutePathBuf::resolve_path_against_base("blocked", cwd.path()); let expected_blocked = AbsolutePathBuf::from_absolute_path( cwd.path() .canonicalize() @@ -4086,8 +4071,7 @@ mod tests { let canonical_cwd = cwd.path().canonicalize().expect("canonicalize cwd"); let cwd_absolute = AbsolutePathBuf::from_absolute_path(&canonical_cwd).expect("absolute tempdir"); - let secret = AbsolutePathBuf::resolve_path_against_base("secret", cwd.path()) - .expect("resolve unreadable path"); + let secret = AbsolutePathBuf::resolve_path_against_base("secret", cwd.path()); let expected_secret = AbsolutePathBuf::from_absolute_path(canonical_cwd.join("secret")) .expect("canonical secret"); let expected_agents = AbsolutePathBuf::from_absolute_path(canonical_cwd.join(".agents")) @@ -4152,10 +4136,8 @@ mod tests { fn restricted_file_system_policy_treats_read_entries_as_read_only_subpaths() { let cwd = TempDir::new().expect("tempdir"); let canonical_cwd = cwd.path().canonicalize().expect("canonicalize cwd"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); - let docs_public = AbsolutePathBuf::resolve_path_against_base("docs/public", cwd.path()) - .expect("resolve docs/public"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); + let docs_public = AbsolutePathBuf::resolve_path_against_base("docs/public", cwd.path()); let expected_docs = AbsolutePathBuf::from_absolute_path(canonical_cwd.join("docs")) .expect("canonical docs"); let expected_docs_public = @@ -4199,8 +4181,7 @@ mod tests { #[test] fn legacy_workspace_write_nested_readable_root_stays_writable() { let cwd = TempDir::new().expect("tempdir"); - let docs = - AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()).expect("resolve docs"); + let docs = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let canonical_cwd = cwd.path().canonicalize().expect("canonicalize cwd"); let expected_dot_codex = AbsolutePathBuf::from_absolute_path(canonical_cwd.join(".codex")) .expect("canonical .codex"); @@ -4257,12 +4238,9 @@ mod tests { #[test] fn legacy_sandbox_policy_semantics_survive_split_bridge() { let cwd = TempDir::new().expect("tempdir"); - let readable_root = AbsolutePathBuf::resolve_path_against_base("readable", cwd.path()) - .expect("resolve readable root"); - let writable_root = AbsolutePathBuf::resolve_path_against_base("writable", cwd.path()) - .expect("resolve writable root"); - let nested_readable_root = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()) - .expect("resolve nested readable root"); + let readable_root = AbsolutePathBuf::resolve_path_against_base("readable", cwd.path()); + let writable_root = AbsolutePathBuf::resolve_path_against_base("writable", cwd.path()); + let nested_readable_root = AbsolutePathBuf::resolve_path_against_base("docs", cwd.path()); let policies = [ SandboxPolicy::DangerFullAccess, SandboxPolicy::ExternalSandbox { diff --git a/codex-rs/sandboxing/src/manager_tests.rs b/codex-rs/sandboxing/src/manager_tests.rs index 6fc34c9637..9c2821eda7 100644 --- a/codex-rs/sandboxing/src/manager_tests.rs +++ b/codex-rs/sandboxing/src/manager_tests.rs @@ -173,8 +173,8 @@ fn transform_additional_permissions_preserves_denied_entries() { canonicalize(temp_dir.path()).expect("canonicalize temp dir"), ) .expect("absolute temp dir"); - let allowed_path = workspace_root.join("allowed").expect("allowed path"); - let denied_path = workspace_root.join("denied").expect("denied path"); + let allowed_path = workspace_root.join("allowed"); + let denied_path = workspace_root.join("denied"); let exec_request = manager .transform(SandboxTransformRequest { command: SandboxCommand { diff --git a/codex-rs/sandboxing/src/policy_transforms_tests.rs b/codex-rs/sandboxing/src/policy_transforms_tests.rs index d287bd243c..10f49d95f3 100644 --- a/codex-rs/sandboxing/src/policy_transforms_tests.rs +++ b/codex-rs/sandboxing/src/policy_transforms_tests.rs @@ -52,8 +52,7 @@ fn root_write_policy_with_carveouts_still_uses_platform_sandbox() { let blocked = AbsolutePathBuf::resolve_path_against_base( "blocked", std::env::current_dir().expect("current dir"), - ) - .expect("blocked path"); + ); let policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -317,8 +316,8 @@ fn merge_file_system_policy_with_additional_permissions_preserves_unreadable_roo canonicalize(temp_dir.path()).expect("canonicalize temp dir"), ) .expect("absolute temp dir"); - let allowed_path = cwd.join("allowed").expect("allowed path"); - let denied_path = cwd.join("denied").expect("denied path"); + let allowed_path = cwd.join("allowed"); + let denied_path = cwd.join("denied"); let merged_policy = merge_file_system_policy_with_additional_permissions( &FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { @@ -361,7 +360,7 @@ fn effective_file_system_sandbox_policy_returns_base_policy_without_additional_p canonicalize(temp_dir.path()).expect("canonicalize temp dir"), ) .expect("absolute temp dir"); - let denied_path = cwd.join("denied").expect("denied path"); + let denied_path = cwd.join("denied"); let base_policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -388,8 +387,8 @@ fn effective_file_system_sandbox_policy_merges_additional_write_roots() { canonicalize(temp_dir.path()).expect("canonicalize temp dir"), ) .expect("absolute temp dir"); - let allowed_path = cwd.join("allowed").expect("allowed path"); - let denied_path = cwd.join("denied").expect("denied path"); + let allowed_path = cwd.join("allowed"); + let denied_path = cwd.join("denied"); let base_policy = FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { diff --git a/codex-rs/shell-command/src/powershell.rs b/codex-rs/shell-command/src/powershell.rs index 4d3b553333..d6ae79245b 100644 --- a/codex-rs/shell-command/src/powershell.rs +++ b/codex-rs/shell-command/src/powershell.rs @@ -112,10 +112,8 @@ pub fn try_find_pwsh_executable_blocking() -> Option { { let candidate = AbsolutePathBuf::resolve_path_against_base("pwsh.exe", &ps_home); - if let Ok(candidate_abs_path) = candidate - && is_powershellish_executable_available(candidate_abs_path.as_path()) - { - return Some(candidate_abs_path); + if is_powershellish_executable_available(candidate.as_path()) { + return Some(candidate); } } diff --git a/codex-rs/shell-escalation/src/unix/escalate_server.rs b/codex-rs/shell-escalation/src/unix/escalate_server.rs index 34b8562160..2f31324ef0 100644 --- a/codex-rs/shell-escalation/src/unix/escalate_server.rs +++ b/codex-rs/shell-escalation/src/unix/escalate_server.rs @@ -274,7 +274,7 @@ async fn handle_escalate_session_with_policy( _ = parent_cancellation_token.cancelled() => return Ok(()), _ = session_cancellation_token.cancelled() => return Ok(()), }; - let program = AbsolutePathBuf::resolve_path_against_base(file, workdir.as_path())?; + let program = AbsolutePathBuf::resolve_path_against_base(file, workdir.as_path()); let decision = tokio::select! { decision = policy.determine_action(&program, &argv, &workdir) => { decision.context("failed to determine escalation action")? @@ -718,7 +718,7 @@ mod tests { let workdir = tmp.path().join("workspace"); std::fs::create_dir(&workdir)?; let workdir = AbsolutePathBuf::try_from(workdir)?; - let expected_file = workdir.join("bin/tool")?; + let expected_file = workdir.join("bin/tool"); let server_task = tokio::spawn(handle_escalate_session_with_policy( server, Arc::new(AssertingEscalationPolicy { diff --git a/codex-rs/skills/src/lib.rs b/codex-rs/skills/src/lib.rs index 99cde06f6f..3ea802f20d 100644 --- a/codex-rs/skills/src/lib.rs +++ b/codex-rs/skills/src/lib.rs @@ -21,7 +21,7 @@ const SYSTEM_SKILLS_MARKER_SALT: &str = "v1"; /// This is typically located at `CODEX_HOME/skills/.system`. pub fn system_cache_root_dir(codex_home: &Path) -> PathBuf { AbsolutePathBuf::try_from(codex_home) - .and_then(|codex_home| system_cache_root_dir_abs(&codex_home)) + .map(|codex_home| system_cache_root_dir_abs(&codex_home)) .map(AbsolutePathBuf::into_path_buf) .unwrap_or_else(|_| { codex_home @@ -30,9 +30,9 @@ pub fn system_cache_root_dir(codex_home: &Path) -> PathBuf { }) } -fn system_cache_root_dir_abs(codex_home: &AbsolutePathBuf) -> std::io::Result { +fn system_cache_root_dir_abs(codex_home: &AbsolutePathBuf) -> AbsolutePathBuf { codex_home - .join(SKILLS_DIR_NAME)? + .join(SKILLS_DIR_NAME) .join(SYSTEM_SKILLS_DIR_NAME) } @@ -47,18 +47,13 @@ fn system_cache_root_dir_abs(codex_home: &AbsolutePathBuf) -> std::io::Result Result<(), SystemSkillsError> { let codex_home = AbsolutePathBuf::try_from(codex_home) .map_err(|source| SystemSkillsError::io("normalize codex home dir", source))?; - let skills_root_dir = codex_home - .join(SKILLS_DIR_NAME) - .map_err(|source| SystemSkillsError::io("resolve skills root dir", source))?; + let skills_root_dir = codex_home.join(SKILLS_DIR_NAME); fs::create_dir_all(skills_root_dir.as_path()) .map_err(|source| SystemSkillsError::io("create skills root dir", source))?; - let dest_system = system_cache_root_dir_abs(&codex_home) - .map_err(|source| SystemSkillsError::io("resolve system skills cache root dir", source))?; + let dest_system = system_cache_root_dir_abs(&codex_home); - let marker_path = dest_system - .join(SYSTEM_SKILLS_MARKER_FILENAME) - .map_err(|source| SystemSkillsError::io("resolve system skills marker path", source))?; + let marker_path = dest_system.join(SYSTEM_SKILLS_MARKER_FILENAME); let expected_fingerprint = embedded_system_skills_fingerprint(); if dest_system.as_path().is_dir() && read_marker(&marker_path).is_ok_and(|marker| marker == expected_fingerprint) @@ -127,18 +122,14 @@ fn write_embedded_dir(dir: &Dir<'_>, dest: &AbsolutePathBuf) -> Result<(), Syste for entry in dir.entries() { match entry { include_dir::DirEntry::Dir(subdir) => { - let subdir_dest = dest.join(subdir.path()).map_err(|source| { - SystemSkillsError::io("resolve system skills subdir", source) - })?; + let subdir_dest = dest.join(subdir.path()); fs::create_dir_all(subdir_dest.as_path()).map_err(|source| { SystemSkillsError::io("create system skills subdir", source) })?; write_embedded_dir(subdir, dest)?; } include_dir::DirEntry::File(file) => { - let path = dest.join(file.path()).map_err(|source| { - SystemSkillsError::io("resolve system skills file", source) - })?; + let path = dest.join(file.path()); if let Some(parent) = path.as_path().parent() { fs::create_dir_all(parent).map_err(|source| { SystemSkillsError::io("create system skills file parent", source) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 668a56876f..dad10fa766 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1024,7 +1024,7 @@ fn normalize_harness_overrides_for_cwd( let mut normalized = Vec::with_capacity(overrides.additional_writable_roots.len()); for root in overrides.additional_writable_roots.drain(..) { - let absolute = AbsolutePathBuf::resolve_path_against_base(root, base_cwd)?; + let absolute = AbsolutePathBuf::resolve_path_against_base(root, base_cwd); normalized.push(absolute.into_path_buf()); } overrides.additional_writable_roots = normalized; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index e8713704d2..86e11b49c4 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -5028,15 +5028,7 @@ impl ChatWidget { self.app_event_tx.send(AppEvent::ForkCurrentSession); } SlashCommand::Init => { - let init_target = match self.config.cwd.join(DEFAULT_PROJECT_DOC_FILENAME) { - Ok(path) => path, - Err(err) => { - self.add_error_message(format!( - "Failed to prepare {DEFAULT_PROJECT_DOC_FILENAME}: {err}", - )); - return; - } - }; + let init_target = self.config.cwd.join(DEFAULT_PROJECT_DOC_FILENAME); if init_target.exists() { let message = format!( "{DEFAULT_PROJECT_DOC_FILENAME} already exists here. Skipping /init to avoid overwriting it." diff --git a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs index 68a5659246..d271fc0076 100644 --- a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs +++ b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs @@ -866,11 +866,7 @@ async fn unified_exec_non_empty_then_empty_snapshots() { #[tokio::test] async fn view_image_tool_call_adds_history_cell() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let image_path = chat - .config - .cwd - .join("example.png") - .expect("absolute image path"); + let image_path = chat.config.cwd.join("example.png"); chat.handle_codex_event(Event { id: "sub-image".into(), diff --git a/codex-rs/utils/absolute-path/Cargo.toml b/codex-rs/utils/absolute-path/Cargo.toml index f4fa8bf789..801bc9c1f0 100644 --- a/codex-rs/utils/absolute-path/Cargo.toml +++ b/codex-rs/utils/absolute-path/Cargo.toml @@ -10,7 +10,6 @@ workspace = true [dependencies] dirs = { workspace = true } -path-absolutize = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } ts-rs = { workspace = true, features = [ diff --git a/codex-rs/utils/absolute-path/src/absolutize.rs b/codex-rs/utils/absolute-path/src/absolutize.rs new file mode 100644 index 0000000000..7965c81f7b --- /dev/null +++ b/codex-rs/utils/absolute-path/src/absolutize.rs @@ -0,0 +1,167 @@ +// Adapted from path-absolutize 3.1.1: +// Copyright (c) 2018 magiclen.org (Ron Li) +// Licensed under the MIT License. +// +// Keep this implementation local so explicit-base normalization can be +// infallible for `AbsolutePathBuf::resolve_path_against_base` and +// `AbsolutePathBuf::join`; only current-working-directory lookup remains +// fallible. + +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +pub(super) fn absolutize(path: &Path) -> std::io::Result { + Ok(absolutize_from(path, &std::env::current_dir()?)) +} + +pub(super) fn absolutize_from(path: &Path, base_path: &Path) -> PathBuf { + normalize_path(&path_with_base(path, base_path)) +} + +fn normalize_path(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + normalized.pop(); + } + Component::Prefix(_) | Component::RootDir | Component::Normal(_) => { + normalized.push(component.as_os_str()); + } + } + } + + if normalized.as_os_str().is_empty() { + PathBuf::from(".") + } else { + normalized + } +} + +#[cfg(not(windows))] +fn path_with_base(path: &Path, base_path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + base_path.join(path) + } +} + +#[cfg(windows)] +fn path_with_base(path: &Path, base_path: &Path) -> PathBuf { + if path.is_absolute() || path.has_root() { + return base_path.join(path); + } + + let mut components = path.components(); + let Some(Component::Prefix(prefix)) = components.next() else { + return base_path.join(path); + }; + + let mut path = PathBuf::new(); + path.push(prefix.as_os_str()); + + if components.clone().next().is_none() { + path.push(std::path::MAIN_SEPARATOR_STR); + return path; + } + + let skip_base_prefix = matches!(base_path.components().next(), Some(Component::Prefix(_))); + for component in base_path + .components() + .skip(usize::from(skip_base_prefix)) + .chain(components) + { + path.push(component.as_os_str()); + } + path +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[cfg(unix)] + #[test] + fn absolute_path_without_dots_is_unchanged() { + assert_eq!( + absolutize_from(Path::new("/path/to/123/456"), Path::new("/base")), + PathBuf::from("/path/to/123/456") + ); + } + + #[cfg(unix)] + #[test] + fn absolute_path_dots_are_removed() { + assert_eq!( + absolutize_from(Path::new("/path/to/./123/../456"), Path::new("/base")), + PathBuf::from("/path/to/456") + ); + } + + #[cfg(unix)] + #[test] + fn relative_path_without_dot_uses_base() { + assert_eq!( + absolutize_from(Path::new("path/to/123/456"), Path::new("/base")), + PathBuf::from("/base/path/to/123/456") + ); + } + + #[cfg(unix)] + #[test] + fn relative_path_with_current_dir_uses_base() { + assert_eq!( + absolutize_from(Path::new("./path/to/123/456"), Path::new("/base")), + PathBuf::from("/base/path/to/123/456") + ); + } + + #[cfg(unix)] + #[test] + fn relative_path_with_parent_dir_uses_base_parent() { + assert_eq!( + absolutize_from(Path::new("../path/to/123/456"), Path::new("/base/cwd")), + PathBuf::from("/base/path/to/123/456") + ); + } + + #[cfg(unix)] + #[test] + fn parent_dir_above_root_stays_at_root() { + assert_eq!( + absolutize_from(Path::new("../../path/to/123/456"), Path::new("/")), + PathBuf::from("/path/to/123/456") + ); + } + + #[cfg(unix)] + #[test] + fn empty_path_uses_base() { + assert_eq!( + absolutize_from(Path::new(""), Path::new("/base/cwd")), + PathBuf::from("/base/cwd") + ); + } + + #[cfg(windows)] + #[test] + fn windows_root_relative_path_uses_base_prefix() { + assert_eq!( + absolutize_from(Path::new(r"\path\to\file"), Path::new(r"C:\base\cwd")), + PathBuf::from(r"C:\path\to\file") + ); + } + + #[cfg(windows)] + #[test] + fn windows_drive_relative_path_uses_path_prefix_and_base_tail() { + assert_eq!( + absolutize_from(Path::new(r"D:path\to\file"), Path::new(r"C:\base\cwd")), + PathBuf::from(r"D:\base\cwd\path\to\file") + ); + } +} diff --git a/codex-rs/utils/absolute-path/src/lib.rs b/codex-rs/utils/absolute-path/src/lib.rs index 0de0f4e023..2b7ca4c307 100644 --- a/codex-rs/utils/absolute-path/src/lib.rs +++ b/codex-rs/utils/absolute-path/src/lib.rs @@ -1,5 +1,4 @@ use dirs::home_dir; -use path_absolutize::Absolutize; use schemars::JsonSchema; use serde::Deserialize; use serde::Deserializer; @@ -11,6 +10,8 @@ use std::path::Path; use std::path::PathBuf; use ts_rs::TS; +mod absolutize; + /// A path that is guaranteed to be absolute and normalized (though it is not /// guaranteed to be canonicalized or exist on the filesystem). /// @@ -43,30 +44,34 @@ impl AbsolutePathBuf { pub fn resolve_path_against_base, B: AsRef>( path: P, base_path: B, - ) -> std::io::Result { + ) -> Self { let expanded = Self::maybe_expand_home_directory(path.as_ref()); - let absolute_path = expanded.absolutize_from(base_path.as_ref())?; - Ok(Self(absolute_path.into_owned())) + Self(absolutize::absolutize_from(&expanded, base_path.as_ref())) } pub fn from_absolute_path>(path: P) -> std::io::Result { let expanded = Self::maybe_expand_home_directory(path.as_ref()); - let absolute_path = expanded.absolutize()?; - Ok(Self(absolute_path.into_owned())) + Ok(Self(absolutize::absolutize(&expanded)?)) } pub fn current_dir() -> std::io::Result { let current_dir = std::env::current_dir()?; - Self::from_absolute_path(current_dir) + Ok(Self(absolutize::absolutize_from( + ¤t_dir, + ¤t_dir, + ))) } /// Construct an absolute path from `path`, resolving relative paths against /// the process current working directory. pub fn relative_to_current_dir>(path: P) -> std::io::Result { - Self::resolve_path_against_base(path, std::env::current_dir()?) + Ok(Self::resolve_path_against_base( + path, + std::env::current_dir()?, + )) } - pub fn join>(&self, path: P) -> std::io::Result { + pub fn join>(&self, path: P) -> Self { Self::resolve_path_against_base(path, &self.0) } @@ -187,9 +192,7 @@ impl<'de> Deserialize<'de> for AbsolutePathBuf { { let path = PathBuf::deserialize(deserializer)?; ABSOLUTE_PATH_BASE.with(|cell| match cell.borrow().as_deref() { - Some(base) => { - Ok(Self::resolve_path_against_base(path, base).map_err(SerdeError::custom)?) - } + Some(base) => Ok(Self::resolve_path_against_base(path, base)), None if path.is_absolute() => { Self::from_absolute_path(path).map_err(SerdeError::custom) } @@ -213,8 +216,7 @@ mod tests { let base_path = base_dir.path(); let absolute_path = absolute_dir.path().join("file.txt"); let abs_path_buf = - AbsolutePathBuf::resolve_path_against_base(absolute_path.clone(), base_path) - .expect("failed to create"); + AbsolutePathBuf::resolve_path_against_base(absolute_path.clone(), base_path); assert_eq!(abs_path_buf.as_path(), absolute_path.as_path()); } @@ -222,8 +224,16 @@ mod tests { fn relative_path_is_resolved_against_base_path() { let temp_dir = tempdir().expect("base dir"); let base_dir = temp_dir.path(); - let abs_path_buf = AbsolutePathBuf::resolve_path_against_base("file.txt", base_dir) - .expect("failed to create"); + let abs_path_buf = AbsolutePathBuf::resolve_path_against_base("file.txt", base_dir); + assert_eq!(abs_path_buf.as_path(), base_dir.join("file.txt").as_path()); + } + + #[test] + fn relative_path_dots_are_normalized_against_base_path() { + let temp_dir = tempdir().expect("base dir"); + let base_dir = temp_dir.path(); + let abs_path_buf = + AbsolutePathBuf::resolve_path_against_base("./nested/../file.txt", base_dir); assert_eq!(abs_path_buf.as_path(), base_dir.join("file.txt").as_path()); } diff --git a/codex-rs/utils/path-utils/src/lib.rs b/codex-rs/utils/path-utils/src/lib.rs index 4e053c0398..7e44e06d13 100644 --- a/codex-rs/utils/path-utils/src/lib.rs +++ b/codex-rs/utils/path-utils/src/lib.rs @@ -84,7 +84,7 @@ pub fn resolve_symlink_write_paths(path: &Path) -> io::Result let next = if target.is_absolute() { AbsolutePathBuf::from_absolute_path(&target) } else if let Some(parent) = current.parent() { - AbsolutePathBuf::resolve_path_against_base(&target, parent) + Ok(AbsolutePathBuf::resolve_path_against_base(&target, parent)) } else { return Ok(SymlinkWritePaths { read_path: None, From b525b5a3a7117c3ce0417b91d870e096c6d07995 Mon Sep 17 00:00:00 2001 From: Romain Huet Date: Tue, 7 Apr 2026 10:55:58 -0700 Subject: [PATCH 22/28] Update README (#16348) Rename ChatGPT Team to ChatGPT Business as the correct plan name in the README. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e44875f21..5cc7fd4953 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Each archive contains a single entry with the platform baked into the name (e.g. ### Using Codex with your ChatGPT plan -Run `codex` and select **Sign in with ChatGPT**. We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Team, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). +Run `codex` and select **Sign in with ChatGPT**. We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Business, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). You can also use Codex with an API key, but this requires [additional setup](https://developers.openai.com/codex/auth#sign-in-with-an-api-key). From 365154d5da051cd689a0816041d3a157a193aa43 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 7 Apr 2026 10:56:08 -0700 Subject: [PATCH 23/28] [codex] Make unified exec tests remote aware (#16977) ## Summary - Convert unified exec integration tests that can run against the remote executor to use the remote-aware test harness. - Create workspace directories through the executor filesystem for remote runs. - Install `python3` and `zsh` in the remote test container so restored Python/zsh-based test commands work in fresh Ubuntu containers. ## Validation - `just fmt` - `cargo test -p codex-core --test all unified_exec_defaults_to_pipe` - `cargo test -p codex-core --test all unified_exec_can_enable_tty` - `cargo test -p codex-core --test all unified_exec` - Remote on `codex-remote`: `source scripts/test-remote-env.sh && cd codex-rs && cargo test -p codex-core --test all unified_exec` - `just fix -p codex-core` --- codex-rs/core/tests/suite/unified_exec.rs | 832 ++++++---------------- scripts/test-remote-env.sh | 4 + 2 files changed, 217 insertions(+), 619 deletions(-) diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 2f72277086..226c5c6af5 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -4,6 +4,7 @@ use std::fs; use anyhow::Context; use anyhow::Result; +use codex_exec_server::CreateDirectoryOptions; use codex_features::Feature; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -35,7 +36,6 @@ use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; use tokio::time::Duration; -use which::which; fn extract_output_text(item: &Value) -> Option<&str> { item.get("output").and_then(|value| match value { @@ -137,6 +137,47 @@ fn collect_tool_outputs(bodies: &[Value]) -> Result Result<()> { + let session_model = test.session_configured.model.clone(); + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: prompt.into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.config.cwd.to_path_buf(), + approval_policy: AskForApproval::Never, + approvals_reviewer: None, + sandbox_policy, + model: session_model, + effort: None, + summary: None, + service_tier: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + Ok(()) +} + +async fn create_workspace_directory( + test: &TestCodex, + rel_path: impl AsRef, +) -> Result { + let abs_path = test.config.cwd.join(rel_path.as_ref())?; + test.fs() + .create_directory(&abs_path, CreateDirectoryOptions { recursive: true }) + .await?; + Ok(abs_path.into_path_buf()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn unified_exec_intercepts_apply_patch_exec_command() -> Result<()> { skip_if_no_network!(Ok(())); @@ -287,12 +328,8 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; + let cwd = test.config.cwd.to_path_buf(); let call_id = "uexec-begin-event"; let args = json!({ @@ -315,29 +352,9 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "emit begin event", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "emit begin event".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - let begin_event = wait_for_event_match(&codex, |msg| match msg { + let begin_event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()), _ => None, }) @@ -345,9 +362,12 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { assert_command(&begin_event.command, "-lc", "/bin/echo hello unified exec"); - assert_eq!(begin_event.cwd, cwd.path()); + assert_eq!(begin_event.cwd, cwd); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; Ok(()) } @@ -367,15 +387,10 @@ async fn unified_exec_resolves_relative_workdir() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let workdir_rel = std::path::PathBuf::from("uexec_relative_workdir"); - std::fs::create_dir_all(cwd.path().join(&workdir_rel))?; + let workdir = create_workspace_directory(&test, &workdir_rel).await?; let call_id = "uexec-workdir-relative"; let args = json!({ @@ -398,41 +413,28 @@ async fn unified_exec_resolves_relative_workdir() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "run relative workdir test", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "run relative workdir test".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - let begin_event = wait_for_event_match(&codex, |msg| match msg { + let begin_event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()), _ => None, }) .await; assert_eq!( - begin_event.cwd, - cwd.path().join(workdir_rel), + begin_event.cwd, workdir, "exec_command cwd should resolve relative workdir against turn cwd", ); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; Ok(()) } @@ -453,15 +455,9 @@ async fn unified_exec_respects_workdir_override() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; - let workdir = cwd.path().join("uexec_workdir_test"); - std::fs::create_dir_all(&workdir)?; + let workdir = create_workspace_directory(&test, "uexec_workdir_test").await?; let call_id = "uexec-workdir"; let args = json!({ @@ -484,29 +480,9 @@ async fn unified_exec_respects_workdir_override() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "run workdir test", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "run workdir test".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - let begin_event = wait_for_event_match(&codex, |msg| match msg { + let begin_event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()), _ => None, }) @@ -517,7 +493,10 @@ async fn unified_exec_respects_workdir_override() -> Result<()> { "exec_command cwd should reflect the requested workdir override" ); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -540,12 +519,7 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-end-event"; let args = json!({ @@ -582,29 +556,9 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "emit end event", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "emit end event".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - let end_event = wait_for_event_match(&codex, |msg| match msg { + let end_event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandEnd(ev) if ev.call_id == call_id => Some(ev.clone()), _ => None, }) @@ -616,7 +570,10 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { "expected aggregated output to contain marker" ); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; Ok(()) } @@ -635,12 +592,7 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-delta-1"; let args = json!({ @@ -662,29 +614,9 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "emit delta", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "emit delta".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - let event = wait_for_event_match(&codex, |msg| match msg { + let event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandEnd(ev) if ev.call_id == call_id => Some(ev.clone()), _ => None, }) @@ -696,7 +628,10 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { "delta chunk missing expected text: {text:?}", ); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; Ok(()) } @@ -715,12 +650,7 @@ async fn unified_exec_full_lifecycle_with_background_end_event() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-full-lifecycle"; // This timing force the long-standing PTY @@ -743,34 +673,19 @@ async fn unified_exec_full_lifecycle_with_background_end_event() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "exercise full unified exec lifecycle".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn( + &test, + "exercise full unified exec lifecycle", + SandboxPolicy::DangerFullAccess, + ) + .await?; let mut begin_event = None; let mut end_event = None; let mut task_completed = false; loop { - let msg = wait_for_event(&codex, |_| true).await; + let msg = wait_for_event(&test.codex, |_| true).await; match msg { EventMsg::ExecCommandBegin(ev) if ev.call_id == call_id => begin_event = Some(ev), EventMsg::ExecCommandEnd(ev) if ev.call_id == call_id => { @@ -830,12 +745,7 @@ async fn unified_exec_emits_terminal_interaction_for_write_stdin() -> Result<()> .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let open_call_id = "uexec-open"; let open_args = json!({ @@ -878,32 +788,12 @@ async fn unified_exec_emits_terminal_interaction_for_write_stdin() -> Result<()> ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "stdin delta".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn(&test, "stdin delta", SandboxPolicy::DangerFullAccess).await?; let mut terminal_interaction = None; loop { - let msg = wait_for_event(&codex, |_| true).await; + let msg = wait_for_event(&test.codex, |_| true).await; match msg { EventMsg::TerminalInteraction(ev) if ev.call_id == open_call_id => { terminal_interaction = Some(ev); @@ -938,12 +828,7 @@ async fn unified_exec_terminal_interaction_captures_delayed_output() -> Result<( .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let open_call_id = "uexec-delayed-open"; let open_args = json!({ @@ -1020,27 +905,12 @@ async fn unified_exec_terminal_interaction_captures_delayed_output() -> Result<( ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "delayed terminal interaction output".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn( + &test, + "delayed terminal interaction output", + SandboxPolicy::DangerFullAccess, + ) + .await?; let mut begin_event = None; let mut end_event = None; @@ -1050,7 +920,7 @@ async fn unified_exec_terminal_interaction_captures_delayed_output() -> Result<( // Consume all events for this turn so we can assert on each stage. loop { - let msg = wait_for_event(&codex, |_| true).await; + let msg = wait_for_event(&test.codex, |_| true).await; match msg { EventMsg::ExecCommandBegin(ev) if ev.call_id == open_call_id => { begin_event = Some(ev); @@ -1137,12 +1007,7 @@ async fn unified_exec_emits_one_begin_and_one_end_event() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let open_call_id = "uexec-open-session"; let open_args = json!({ @@ -1185,33 +1050,18 @@ async fn unified_exec_emits_one_begin_and_one_end_event() -> Result<()> { ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "check poll event behavior".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn( + &test, + "check poll event behavior", + SandboxPolicy::DangerFullAccess, + ) + .await?; let mut begin_events = Vec::new(); let mut end_events = Vec::new(); let mut task_completed = false; loop { - let event_msg = wait_for_event(&codex, |_| true).await; + let event_msg = wait_for_event(&test.codex, |_| true).await; match event_msg { EventMsg::ExecCommandBegin(event) if event.call_id == open_call_id => { begin_events.push(event); @@ -1271,12 +1121,7 @@ async fn exec_command_reports_chunk_and_exit_metadata() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-metadata"; let args = serde_json::json!({ @@ -1298,29 +1143,12 @@ async fn exec_command_reports_chunk_and_exit_metadata() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "run metadata test", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "run metadata test".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -1378,14 +1206,6 @@ async fn unified_exec_defaults_to_pipe() -> Result<()> { skip_if_sandbox!(Ok(())); skip_if_windows!(Ok(())); - let python = match which("python").or_else(|_| which("python3")) { - Ok(path) => path, - Err(_) => { - eprintln!("python not found in PATH, skipping tty default test."); - return Ok(()); - } - }; - let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { @@ -1394,16 +1214,11 @@ async fn unified_exec_defaults_to_pipe() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-default-pipe"; let args = serde_json::json!({ - "cmd": format!("{} -c \"import sys; print(sys.stdin.isatty())\"", python.display()), + "cmd": "python3 -c \"import sys; print(sys.stdin.isatty())\"", "yield_time_ms": 1500, }); @@ -1421,29 +1236,17 @@ async fn unified_exec_defaults_to_pipe() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "check default pipe mode", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "check default pipe mode".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -1472,14 +1275,6 @@ async fn unified_exec_can_enable_tty() -> Result<()> { skip_if_sandbox!(Ok(())); skip_if_windows!(Ok(())); - let python = match which("python").or_else(|_| which("python3")) { - Ok(path) => path, - Err(_) => { - eprintln!("python not found in PATH, skipping tty enable test."); - return Ok(()); - } - }; - let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { @@ -1488,16 +1283,11 @@ async fn unified_exec_can_enable_tty() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-tty-enabled"; let args = serde_json::json!({ - "cmd": format!("{} -c \"import sys; print(sys.stdin.isatty())\"", python.display()), + "cmd": "python3 -c \"import sys; print(sys.stdin.isatty())\"", "yield_time_ms": 1500, "tty": true, }); @@ -1516,29 +1306,12 @@ async fn unified_exec_can_enable_tty() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "check tty enabled", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "check tty enabled".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -1576,12 +1349,7 @@ async fn unified_exec_respects_early_exit_notifications() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec-early-exit"; let args = serde_json::json!({ @@ -1602,29 +1370,17 @@ async fn unified_exec_respects_early_exit_notifications() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "watch early exit timing", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "watch early exit timing".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -1676,12 +1432,7 @@ async fn write_stdin_returns_exit_metadata_and_clears_session() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let start_call_id = "uexec-cat-start"; let send_call_id = "uexec-cat-send"; @@ -1738,29 +1489,17 @@ async fn write_stdin_returns_exit_metadata_and_clears_session() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "test write_stdin exit behavior", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "test write_stdin exit behavior".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -1847,12 +1586,7 @@ async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<() .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let start_call_id = "uexec-end-on-exit-start"; let start_args = serde_json::json!({ @@ -1911,30 +1645,10 @@ async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<() ]; mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "end on exit".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn(&test, "end on exit", SandboxPolicy::DangerFullAccess).await?; // We expect the ExecCommandEnd event to match the initial exec_command call_id. - let end_event = wait_for_event_match(&codex, |msg| match msg { + let end_event = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::ExecCommandEnd(ev) if ev.call_id == start_call_id => Some(ev.clone()), _ => None, }) @@ -1942,7 +1656,10 @@ async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<() assert_eq!(end_event.exit_code, 0); - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; Ok(()) } @@ -2148,12 +1865,7 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let first_call_id = "uexec-start"; let first_args = serde_json::json!({ @@ -2195,29 +1907,12 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "run unified exec", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "run unified exec".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -2269,12 +1964,7 @@ async fn unified_exec_streams_after_lagged_output() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let script = r#"python3 - <<'PY' import sys @@ -2335,30 +2025,15 @@ PY ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "exercise lag handling".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn( + &test, + "exercise lag handling", + SandboxPolicy::DangerFullAccess, + ) + .await?; // This is a worst case scenario for the truncate logic. wait_for_event_with_timeout( - &codex, + &test.codex, |event| matches!(event, EventMsg::TurnComplete(_)), Duration::from_secs(10), ) @@ -2408,12 +2083,7 @@ async fn unified_exec_timeout_and_followup_poll() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let first_call_id = "uexec-timeout"; let first_args = serde_json::json!({ @@ -2454,30 +2124,10 @@ async fn unified_exec_timeout_and_followup_poll() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "check timeout".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; + submit_unified_exec_turn(&test, "check timeout", SandboxPolicy::DangerFullAccess).await?; loop { - let event = codex.next_event().await.expect("event"); + let event = test.codex.next_event().await.expect("event"); if matches!(event.msg, EventMsg::TurnComplete(_)) { break; } @@ -2522,12 +2172,7 @@ async fn unified_exec_formats_large_output_summary() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let script = r#"python3 - <<'PY' import sys @@ -2555,29 +2200,17 @@ PY ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "summarize large output", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "summarize large output".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -2840,12 +2473,7 @@ async fn unified_exec_runs_on_all_platforms() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; let call_id = "uexec"; let args = serde_json::json!({ @@ -2865,29 +2493,17 @@ async fn unified_exec_runs_on_all_platforms() -> Result<()> { ]; let request_log = mount_sse_sequence(&server, responses).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn( + &test, + "summarize large output", + SandboxPolicy::DangerFullAccess, + ) + .await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "summarize large output".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = request_log.requests(); assert!(!requests.is_empty(), "expected at least one POST request"); @@ -2921,12 +2537,7 @@ async fn unified_exec_prunes_exited_sessions_first() -> Result<()> { .enable(Feature::UnifiedExec) .expect("test config should allow feature update"); }); - let TestCodex { - codex, - cwd, - session_configured, - .. - } = builder.build(&server).await?; + let test = builder.build_remote_aware(&server).await?; const MAX_SESSIONS_FOR_TEST: i32 = 64; const FILLER_SESSIONS: i32 = MAX_SESSIONS_FOR_TEST - 1; @@ -3005,29 +2616,12 @@ async fn unified_exec_prunes_exited_sessions_first() -> Result<()> { let response_mock = mount_sse_sequence(&server, vec![first_response, completion_response]).await; - let session_model = session_configured.model.clone(); + submit_unified_exec_turn(&test, "fill session cache", SandboxPolicy::DangerFullAccess).await?; - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "fill session cache".into(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - approvals_reviewer: None, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: None, - service_tier: None, - collaboration_mode: None, - personality: None, - }) - .await?; - - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let requests = response_mock.requests(); assert!( diff --git a/scripts/test-remote-env.sh b/scripts/test-remote-env.sh index 60fb447832..833be978c3 100755 --- a/scripts/test-remote-env.sh +++ b/scripts/test-remote-env.sh @@ -49,6 +49,10 @@ setup_remote_env() { docker rm -f "${container_name}" >/dev/null 2>&1 || true docker run -d --name "${container_name}" ubuntu:24.04 sleep infinity >/dev/null + if ! docker exec "${container_name}" sh -lc "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 zsh"; then + docker rm -f "${container_name}" >/dev/null 2>&1 || true + return 1 + fi export CODEX_TEST_REMOTE_ENV="${container_name}" } From 252d79f5eb0bba6d7b5603055fb476c02470a55c Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Tue, 7 Apr 2026 11:10:21 -0700 Subject: [PATCH 24/28] [mcp] Support MCP Apps part 2 - Add meta to mcp tool call result. (#16465) - [x] Add meta to mcp tool call result. --- .../schema/json/ServerNotification.json | 1 + .../codex_app_server_protocol.schemas.json | 1 + .../codex_app_server_protocol.v2.schemas.json | 1 + .../json/v2/ItemCompletedNotification.json | 1 + .../json/v2/ItemStartedNotification.json | 1 + .../schema/json/v2/ReviewStartResponse.json | 1 + .../schema/json/v2/ThreadForkResponse.json | 1 + .../schema/json/v2/ThreadListResponse.json | 1 + .../json/v2/ThreadMetadataUpdateResponse.json | 1 + .../schema/json/v2/ThreadReadResponse.json | 1 + .../schema/json/v2/ThreadResumeResponse.json | 1 + .../json/v2/ThreadRollbackResponse.json | 1 + .../schema/json/v2/ThreadStartResponse.json | 1 + .../json/v2/ThreadStartedNotification.json | 1 + .../json/v2/ThreadUnarchiveResponse.json | 1 + .../json/v2/TurnCompletedNotification.json | 1 + .../schema/json/v2/TurnStartResponse.json | 1 + .../json/v2/TurnStartedNotification.json | 1 + .../schema/typescript/v2/McpToolCallResult.ts | 2 +- .../src/protocol/thread_history.rs | 63 +++++++++++++++++++ .../app-server-protocol/src/protocol/v2.rs | 3 + .../app-server/src/bespoke_event_handling.rs | 8 ++- .../tests/event_processor_with_json_output.rs | 2 + 23 files changed, 94 insertions(+), 2 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 116844171b..d7619354fc 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1736,6 +1736,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 80f2b226b7..09f0daefdc 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -9184,6 +9184,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index eb4e9d7b18..620495f8bf 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -6007,6 +6007,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json index 3964107865..2883670c88 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json @@ -294,6 +294,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json index abb8aee5dc..c2e71ccba9 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json @@ -294,6 +294,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json index 4bdeebf573..a7fe2e8d60 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -430,6 +430,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index a79ac103c7..9b1870198a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -518,6 +518,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index e8211b2521..426f34ce35 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index 08c4696bb3..c869a79749 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index f6d67d5c0c..9569860c38 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 1697435049..5143545ec1 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -518,6 +518,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index e664490df9..502dd3961f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 98e022c751..c07b4d8258 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -518,6 +518,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index f640c40969..ff87af2069 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index 1c10ea3b84..daf821c374 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -456,6 +456,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json index fc1deb675f..82c2b3c76c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -430,6 +430,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json index 5b79f4df11..ebb2065cb8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -430,6 +430,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json index ccbe93e9c2..8b7c2bc410 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -430,6 +430,7 @@ }, "McpToolCallResult": { "properties": { + "_meta": true, "content": { "items": true, "type": "array" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/McpToolCallResult.ts b/codex-rs/app-server-protocol/schema/typescript/v2/McpToolCallResult.ts index f493a86094..916a5f5bb3 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/McpToolCallResult.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/McpToolCallResult.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { JsonValue } from "../serde_json/JsonValue"; -export type McpToolCallResult = { content: Array, structuredContent: JsonValue | null, }; +export type McpToolCallResult = { content: Array, structuredContent: JsonValue | null, _meta: JsonValue | null, }; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index 10d55bb231..27d393629b 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -520,6 +520,7 @@ impl ThreadHistoryBuilder { Some(McpToolCallResult { content: value.content.clone(), structured_content: value.structured_content.clone(), + meta: value.meta.clone(), }), None, ), @@ -1167,6 +1168,7 @@ mod tests { use codex_protocol::items::TurnItem as CoreTurnItem; use codex_protocol::items::UserMessageItem as CoreUserMessageItem; use codex_protocol::items::build_hook_prompt_message; + use codex_protocol::mcp::CallToolResult; use codex_protocol::models::MessagePhase as CoreMessagePhase; use codex_protocol::models::WebSearchAction as CoreWebSearchAction; use codex_protocol::parse_command::ParsedCommand; @@ -1861,6 +1863,67 @@ mod tests { ); } + #[test] + fn reconstructs_mcp_tool_result_meta_from_persisted_completion_events() { + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".into(), + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::McpToolCallEnd(McpToolCallEndEvent { + call_id: "mcp-1".into(), + invocation: McpInvocation { + server: "docs".into(), + tool: "lookup".into(), + arguments: Some(serde_json::json!({"id":"123"})), + }, + duration: Duration::from_millis(8), + result: Ok(CallToolResult { + content: vec![serde_json::json!({ + "type": "text", + "text": "result" + })], + structured_content: Some(serde_json::json!({"id":"123"})), + is_error: Some(false), + meta: Some(serde_json::json!({ + "ui/resourceUri": "ui://widget/lookup.html" + })), + }), + }), + ]; + + let items = events + .into_iter() + .map(RolloutItem::EventMsg) + .collect::>(); + let turns = build_turns_from_rollout_items(&items); + assert_eq!(turns.len(), 1); + assert_eq!( + turns[0].items[0], + ThreadItem::McpToolCall { + id: "mcp-1".into(), + server: "docs".into(), + tool: "lookup".into(), + status: McpToolCallStatus::Completed, + arguments: serde_json::json!({"id":"123"}), + result: Some(McpToolCallResult { + content: vec![serde_json::json!({ + "type": "text", + "text": "result" + })], + structured_content: Some(serde_json::json!({"id":"123"})), + meta: Some(serde_json::json!({ + "ui/resourceUri": "ui://widget/lookup.html" + })), + }), + error: None, + duration_ms: Some(8), + } + ); + } + #[test] fn reconstructs_dynamic_tool_items_from_request_and_response_events() { let events = vec![ diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 3562d9cda6..296baa1fe9 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -5048,6 +5048,9 @@ pub struct McpToolCallResult { // representations). Using `JsonValue` keeps the payload wire-shaped and easy to export. pub content: Vec, pub structured_content: Option, + #[serde(rename = "_meta")] + #[ts(rename = "_meta")] + pub meta: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 141ee78bdb..f5c60fe9dc 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -2843,6 +2843,7 @@ async fn construct_mcp_tool_call_end_notification( Some(McpToolCallResult { content: value.content.clone(), structured_content: value.structured_content.clone(), + meta: value.meta.clone(), }), None, ), @@ -4233,7 +4234,9 @@ mod tests { content: content.clone(), is_error: Some(false), structured_content: None, - meta: None, + meta: Some(serde_json::json!({ + "ui/resourceUri": "ui://widget/list-resources.html" + })), }; let end_event = McpToolCallEndEvent { @@ -4268,6 +4271,9 @@ mod tests { result: Some(McpToolCallResult { content, structured_content: None, + meta: Some(serde_json::json!({ + "ui/resourceUri": "ui://widget/list-resources.html" + })), }), error: None, duration_ms: Some(0), diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index a6b25b66b8..bb29366561 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -482,6 +482,7 @@ fn mcp_tool_call_begin_and_end_emit_item_events() { result: Some(McpToolCallResult { content: Vec::new(), structured_content: None, + meta: None, }), error: None, duration_ms: Some(1_000), @@ -613,6 +614,7 @@ fn mcp_tool_call_defaults_arguments_and_preserves_structured_content() { "text": "done", })], structured_content: Some(json!({ "status": "ok" })), + meta: None, }), error: None, duration_ms: Some(10), From 8a13f82204c2692794aab96a1d03f1158fe8cbfe Mon Sep 17 00:00:00 2001 From: Ruslan Nigmatullin Date: Tue, 7 Apr 2026 11:22:28 -0700 Subject: [PATCH 25/28] app-server: Move watch_id to request of fs/watch (#17026) It's easier for clients to maintain watchers if they define the watch id, so move it into the request. It's not used yet, so should be a safe change. --- .../schema/json/ClientRequest.json | 9 +- .../schema/json/ServerNotification.json | 2 +- .../codex_app_server_protocol.schemas.json | 42 +++---- .../codex_app_server_protocol.v2.schemas.json | 42 +++---- .../schema/json/v2/FsChangedNotification.json | 2 +- .../schema/json/v2/FsUnwatchParams.json | 2 +- .../schema/json/v2/FsWatchParams.json | 7 +- .../schema/json/v2/FsWatchResponse.json | 9 +- .../typescript/v2/FsChangedNotification.ts | 2 +- .../schema/typescript/v2/FsUnwatchParams.ts | 2 +- .../schema/typescript/v2/FsWatchParams.ts | 4 + .../schema/typescript/v2/FsWatchResponse.ts | 6 +- .../src/protocol/common.rs | 2 + .../app-server-protocol/src/protocol/v2.rs | 10 +- codex-rs/app-server/README.md | 4 +- codex-rs/app-server/src/fs_watch.rs | 114 +++++++++++++----- codex-rs/app-server/tests/suite/v2/fs.rs | 25 ++-- 17 files changed, 171 insertions(+), 113 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 9f1c46d800..5039a0bfe7 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -800,7 +800,7 @@ "description": "Stop filesystem watch notifications for a prior `fs/watch`.", "properties": { "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, @@ -819,10 +819,15 @@ } ], "description": "Absolute file or directory path to watch." + }, + "watchId": { + "description": "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", + "type": "string" } }, "required": [ - "path" + "path", + "watchId" ], "type": "object" }, diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index d7619354fc..d550f523ce 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1013,7 +1013,7 @@ "type": "array" }, "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 09f0daefdc..da21699875 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -7511,7 +7511,7 @@ "type": "array" }, "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, @@ -7781,7 +7781,7 @@ "description": "Stop filesystem watch notifications for a prior `fs/watch`.", "properties": { "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, @@ -7808,25 +7808,6 @@ } ], "description": "Absolute file or directory path to watch." - } - }, - "required": [ - "path" - ], - "title": "FsWatchParams", - "type": "object" - }, - "FsWatchResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "description": "Created watch handle returned by `fs/watch`.", - "properties": { - "path": { - "allOf": [ - { - "$ref": "#/definitions/v2/AbsolutePathBuf" - } - ], - "description": "Canonicalized path associated with the watch." }, "watchId": { "description": "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", @@ -7837,6 +7818,25 @@ "path", "watchId" ], + "title": "FsWatchParams", + "type": "object" + }, + "FsWatchResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Successful response for `fs/watch`.", + "properties": { + "path": { + "allOf": [ + { + "$ref": "#/definitions/v2/AbsolutePathBuf" + } + ], + "description": "Canonicalized path associated with the watch." + } + }, + "required": [ + "path" + ], "title": "FsWatchResponse", "type": "object" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 620495f8bf..a66c34e14d 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -4179,7 +4179,7 @@ "type": "array" }, "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, @@ -4449,7 +4449,7 @@ "description": "Stop filesystem watch notifications for a prior `fs/watch`.", "properties": { "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, @@ -4476,25 +4476,6 @@ } ], "description": "Absolute file or directory path to watch." - } - }, - "required": [ - "path" - ], - "title": "FsWatchParams", - "type": "object" - }, - "FsWatchResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "description": "Created watch handle returned by `fs/watch`.", - "properties": { - "path": { - "allOf": [ - { - "$ref": "#/definitions/AbsolutePathBuf" - } - ], - "description": "Canonicalized path associated with the watch." }, "watchId": { "description": "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", @@ -4505,6 +4486,25 @@ "path", "watchId" ], + "title": "FsWatchParams", + "type": "object" + }, + "FsWatchResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Successful response for `fs/watch`.", + "properties": { + "path": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "Canonicalized path associated with the watch." + } + }, + "required": [ + "path" + ], "title": "FsWatchResponse", "type": "object" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/FsChangedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/FsChangedNotification.json index ab26588ecb..cfb9f4e5ba 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FsChangedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FsChangedNotification.json @@ -16,7 +16,7 @@ "type": "array" }, "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/FsUnwatchParams.json b/codex-rs/app-server-protocol/schema/json/v2/FsUnwatchParams.json index 4b988d97aa..f46800e997 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FsUnwatchParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FsUnwatchParams.json @@ -3,7 +3,7 @@ "description": "Stop filesystem watch notifications for a prior `fs/watch`.", "properties": { "watchId": { - "description": "Watch identifier returned by `fs/watch`.", + "description": "Watch identifier previously provided to `fs/watch`.", "type": "string" } }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/FsWatchParams.json b/codex-rs/app-server-protocol/schema/json/v2/FsWatchParams.json index cf80c7b101..29a1ceea14 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FsWatchParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FsWatchParams.json @@ -15,10 +15,15 @@ } ], "description": "Absolute file or directory path to watch." + }, + "watchId": { + "description": "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", + "type": "string" } }, "required": [ - "path" + "path", + "watchId" ], "title": "FsWatchParams", "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/v2/FsWatchResponse.json b/codex-rs/app-server-protocol/schema/json/v2/FsWatchResponse.json index b516636a09..abc7d466bb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FsWatchResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FsWatchResponse.json @@ -6,7 +6,7 @@ "type": "string" } }, - "description": "Created watch handle returned by `fs/watch`.", + "description": "Successful response for `fs/watch`.", "properties": { "path": { "allOf": [ @@ -15,15 +15,10 @@ } ], "description": "Canonicalized path associated with the watch." - }, - "watchId": { - "description": "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", - "type": "string" } }, "required": [ - "path", - "watchId" + "path" ], "title": "FsWatchResponse", "type": "object" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FsChangedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FsChangedNotification.ts index 2e9bd0d6ec..fc0fa9cf6d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FsChangedNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FsChangedNotification.ts @@ -8,7 +8,7 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf"; */ export type FsChangedNotification = { /** - * Watch identifier returned by `fs/watch`. + * Watch identifier previously provided to `fs/watch`. */ watchId: string, /** diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FsUnwatchParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FsUnwatchParams.ts index b21befdb5c..34b70a9307 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FsUnwatchParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FsUnwatchParams.ts @@ -7,6 +7,6 @@ */ export type FsUnwatchParams = { /** - * Watch identifier returned by `fs/watch`. + * Watch identifier previously provided to `fs/watch`. */ watchId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchParams.ts index d6d956b288..60755538cb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchParams.ts @@ -7,6 +7,10 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf"; * Start filesystem watch notifications for an absolute path. */ export type FsWatchParams = { +/** + * Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`. + */ +watchId: string, /** * Absolute file or directory path to watch. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchResponse.ts index 1927272821..b640306d82 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FsWatchResponse.ts @@ -4,13 +4,9 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf"; /** - * Created watch handle returned by `fs/watch`. + * Successful response for `fs/watch`. */ export type FsWatchResponse = { -/** - * Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`. - */ -watchId: string, /** * Canonicalized path associated with the watch. */ diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 8fbff67893..3ac96fa0eb 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -1635,6 +1635,7 @@ mod tests { let request = ClientRequest::FsWatch { request_id: RequestId::Integer(10), params: v2::FsWatchParams { + watch_id: "watch-git".to_string(), path: absolute_path("tmp/repo/.git"), }, }; @@ -1643,6 +1644,7 @@ mod tests { "method": "fs/watch", "id": 10, "params": { + "watchId": "watch-git", "path": absolute_path_string("tmp/repo/.git") } }), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 296baa1fe9..e0d22bfa24 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2349,17 +2349,17 @@ pub struct FsCopyResponse {} #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct FsWatchParams { + /// Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`. + pub watch_id: String, /// Absolute file or directory path to watch. pub path: AbsolutePathBuf, } -/// Created watch handle returned by `fs/watch`. +/// Successful response for `fs/watch`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct FsWatchResponse { - /// Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`. - pub watch_id: String, /// Canonicalized path associated with the watch. pub path: AbsolutePathBuf, } @@ -2369,7 +2369,7 @@ pub struct FsWatchResponse { #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct FsUnwatchParams { - /// Watch identifier returned by `fs/watch`. + /// Watch identifier previously provided to `fs/watch`. pub watch_id: String, } @@ -2384,7 +2384,7 @@ pub struct FsUnwatchResponse {} #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct FsChangedNotification { - /// Watch identifier returned by `fs/watch`. + /// Watch identifier previously provided to `fs/watch`. pub watch_id: String, /// File or directory paths associated with this event. pub changed_paths: Vec, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 6fedd73d98..3aff647766 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -169,7 +169,7 @@ Example with notification opt-out: - `fs/readDirectory` — list direct child entries for an absolute directory path; each entry contains `fileName`, `isDirectory`, and `isFile`, and `fileName` is just the child name, not a path. - `fs/remove` — remove an absolute file or directory tree; `recursive` and `force` default to `true`. - `fs/copy` — copy between absolute paths; directory copies require `recursive: true`. -- `fs/watch` — subscribe this connection to filesystem change notifications for an absolute file or directory path; returns a `watchId` and canonicalized `path`. +- `fs/watch` — subscribe this connection to filesystem change notifications for an absolute file or directory path and caller-provided `watchId`; returns the canonicalized `path`. - `fs/unwatch` — stop sending notifications for a prior `fs/watch`; returns `{}`. - `fs/changed` — notification emitted when watched paths change, including the `watchId` and `changedPaths`. - `model/list` — list available models (set `includeHidden: true` to include entries with `hidden: true`), with reasoning effort options, optional legacy `upgrade` model ids, optional `upgradeInfo` metadata (`model`, `upgradeCopy`, `modelLink`, `migrationMarkdown`), and optional `availabilityNux` metadata. @@ -816,10 +816,10 @@ All filesystem paths in this section must be absolute. ```json { "method": "fs/watch", "id": 44, "params": { + "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1", "path": "/Users/me/project/.git/HEAD" } } { "id": 44, "result": { - "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1", "path": "/Users/me/project/.git/HEAD" } } { "method": "fs/changed", "params": { diff --git a/codex-rs/app-server/src/fs_watch.rs b/codex-rs/app-server/src/fs_watch.rs index c8214c2b8a..3a5b226248 100644 --- a/codex-rs/app-server/src/fs_watch.rs +++ b/codex-rs/app-server/src/fs_watch.rs @@ -1,3 +1,4 @@ +use crate::fs_api::invalid_request; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::OutgoingMessageSender; use codex_app_server_protocol::FsChangedNotification; @@ -16,6 +17,7 @@ use codex_core::file_watcher::WatchRegistration; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::collections::HashSet; +use std::collections::hash_map::Entry; use std::hash::Hash; use std::path::PathBuf; use std::sync::Arc; @@ -26,7 +28,6 @@ use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::time::Instant; use tracing::warn; -use uuid::Uuid; const FS_CHANGED_NOTIFICATION_DEBOUNCE: Duration = Duration::from_millis(200); @@ -120,7 +121,11 @@ impl FsWatchManager { connection_id: ConnectionId, params: FsWatchParams, ) -> Result { - let watch_id = Uuid::now_v7().to_string(); + let watch_id = params.watch_id; + let watch_key = WatchKey { + connection_id, + watch_id: watch_id.clone(), + }; let outgoing = self.outgoing.clone(); let (subscriber, rx) = self.file_watcher.add_subscriber(); let watch_root = params.path.to_path_buf().clone(); @@ -130,17 +135,20 @@ impl FsWatchManager { }]); let (terminate_tx, terminate_rx) = oneshot::channel(); - self.state.lock().await.entries.insert( - WatchKey { - connection_id, - watch_id: watch_id.clone(), - }, - WatchEntry { - terminate_tx, - _subscriber: subscriber, - _registration: registration, - }, - ); + match self.state.lock().await.entries.entry(watch_key) { + Entry::Occupied(_) => { + return Err(invalid_request(format!( + "watchId already exists: {watch_id}" + ))); + } + Entry::Vacant(entry) => { + entry.insert(WatchEntry { + terminate_tx, + _subscriber: subscriber, + _registration: registration, + }); + } + } let task_watch_id = watch_id.clone(); tokio::spawn(async move { @@ -175,10 +183,7 @@ impl FsWatchManager { } }); - Ok(FsWatchResponse { - watch_id, - path: params.path, - }) + Ok(FsWatchResponse { path: params.path }) } pub(crate) async fn unwatch( @@ -216,7 +221,6 @@ mod tests { use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use tempfile::TempDir; - use uuid::Version; fn absolute_path(path: PathBuf) -> AbsolutePathBuf { assert!( @@ -237,28 +241,33 @@ mod tests { } #[tokio::test] - async fn watch_returns_a_v7_id_and_tracks_the_owner_scoped_entry() { + async fn watch_uses_client_id_and_tracks_the_owner_scoped_entry() { let temp_dir = TempDir::new().expect("temp dir"); let head_path = temp_dir.path().join("HEAD"); std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD"); let manager = manager_with_noop_watcher(); let path = absolute_path(head_path); + let watch_id = "watch-head".to_string(); let response = manager - .watch(ConnectionId(1), FsWatchParams { path: path.clone() }) + .watch( + ConnectionId(1), + FsWatchParams { + watch_id: watch_id.clone(), + path: path.clone(), + }, + ) .await .expect("watch should succeed"); assert_eq!(response.path, path); - let watch_id = Uuid::parse_str(&response.watch_id).expect("watch id should be a UUID"); - assert_eq!(watch_id.get_version(), Some(Version::SortRand)); let state = manager.state.lock().await; assert_eq!( state.entries.keys().cloned().collect::>(), HashSet::from([WatchKey { connection_id: ConnectionId(1), - watch_id: response.watch_id, + watch_id, }]) ); } @@ -270,10 +279,11 @@ mod tests { std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD"); let manager = manager_with_noop_watcher(); - let response = manager + manager .watch( ConnectionId(1), FsWatchParams { + watch_id: "watch-head".to_string(), path: absolute_path(head_path), }, ) @@ -281,14 +291,14 @@ mod tests { .expect("watch should succeed"); let watch_key = WatchKey { connection_id: ConnectionId(1), - watch_id: response.watch_id.clone(), + watch_id: "watch-head".to_string(), }; manager .unwatch( ConnectionId(2), FsUnwatchParams { - watch_id: response.watch_id.clone(), + watch_id: "watch-head".to_string(), }, ) .await @@ -299,7 +309,7 @@ mod tests { .unwatch( ConnectionId(1), FsUnwatchParams { - watch_id: response.watch_id, + watch_id: "watch-head".to_string(), }, ) .await @@ -307,6 +317,41 @@ mod tests { assert!(!manager.state.lock().await.entries.contains_key(&watch_key)); } + #[tokio::test] + async fn watch_rejects_duplicate_id_for_the_same_connection() { + let temp_dir = TempDir::new().expect("temp dir"); + let head_path = temp_dir.path().join("HEAD"); + let fetch_head_path = temp_dir.path().join("FETCH_HEAD"); + std::fs::write(&head_path, "ref: refs/heads/main\n").expect("write HEAD"); + std::fs::write(&fetch_head_path, "old-fetch\n").expect("write FETCH_HEAD"); + + let manager = manager_with_noop_watcher(); + manager + .watch( + ConnectionId(1), + FsWatchParams { + watch_id: "watch-head".to_string(), + path: absolute_path(head_path), + }, + ) + .await + .expect("first watch should succeed"); + + let error = manager + .watch( + ConnectionId(1), + FsWatchParams { + watch_id: "watch-head".to_string(), + path: absolute_path(fetch_head_path), + }, + ) + .await + .expect_err("duplicate watch should fail"); + + assert_eq!(error.message, "watchId already exists: watch-head"); + assert_eq!(manager.state.lock().await.entries.len(), 1); + } + #[tokio::test] async fn connection_closed_removes_only_that_connections_watches() { let temp_dir = TempDir::new().expect("temp dir"); @@ -318,28 +363,31 @@ mod tests { std::fs::write(&packed_refs_path, "refs\n").expect("write packed-refs"); let manager = manager_with_noop_watcher(); - let response_1 = manager + let response = manager .watch( ConnectionId(1), FsWatchParams { - path: absolute_path(head_path), + watch_id: "watch-head".to_string(), + path: absolute_path(head_path.clone()), }, ) .await .expect("first watch should succeed"); - let response_2 = manager + manager .watch( ConnectionId(1), FsWatchParams { + watch_id: "watch-fetch-head".to_string(), path: absolute_path(fetch_head_path), }, ) .await .expect("second watch should succeed"); - let response_3 = manager + manager .watch( ConnectionId(2), FsWatchParams { + watch_id: "watch-packed-refs".to_string(), path: absolute_path(packed_refs_path), }, ) @@ -359,9 +407,9 @@ mod tests { .collect::>(), HashSet::from([WatchKey { connection_id: ConnectionId(2), - watch_id: response_3.watch_id, + watch_id: "watch-packed-refs".to_string(), }]) ); - assert_ne!(response_1.watch_id, response_2.watch_id); + assert_eq!(response.path, absolute_path(head_path)); } } diff --git a/codex-rs/app-server/tests/suite/v2/fs.rs b/codex-rs/app-server/tests/suite/v2/fs.rs index e113904809..3fd5d62c89 100644 --- a/codex-rs/app-server/tests/suite/v2/fs.rs +++ b/codex-rs/app-server/tests/suite/v2/fs.rs @@ -21,8 +21,6 @@ use std::path::PathBuf; use tempfile::TempDir; use tokio::time::Duration; use tokio::time::timeout; -use uuid::Uuid; -use uuid::Version; #[cfg(unix)] use std::os::unix::fs::symlink; @@ -628,8 +626,10 @@ async fn fs_watch_directory_reports_changed_child_paths_and_unwatch_stops_notifi std::fs::write(&fetch_head, "old\n")?; let mut mcp = initialized_mcp(&codex_home).await?; + let watch_id = "watch-git-dir".to_string(); let watch_request_id = mcp .send_fs_watch_request(codex_app_server_protocol::FsWatchParams { + watch_id: watch_id.clone(), path: absolute_path(git_dir.clone()), }) .await?; @@ -641,8 +641,6 @@ async fn fs_watch_directory_reports_changed_child_paths_and_unwatch_stops_notifi .await??, )?; assert_eq!(watch_response.path, absolute_path(git_dir.clone())); - let watch_id = Uuid::parse_str(&watch_response.watch_id)?; - assert_eq!(watch_id.get_version(), Some(Version::SortRand)); std::fs::write(&fetch_head, "updated\n")?; @@ -650,7 +648,7 @@ async fn fs_watch_directory_reports_changed_child_paths_and_unwatch_stops_notifi // Keep validating notification shape when the backend does emit, but do not // fail the whole suite if no OS event arrives. if let Some(changed) = maybe_fs_changed_notification(&mut mcp).await? { - assert_eq!(changed.watch_id, watch_response.watch_id.clone()); + assert_eq!(changed.watch_id, watch_id.clone()); assert_eq!( changed.changed_paths, vec![absolute_path(fetch_head.clone())] @@ -665,9 +663,7 @@ async fn fs_watch_directory_reports_changed_child_paths_and_unwatch_stops_notifi {} let unwatch_request_id = mcp - .send_fs_unwatch_request(FsUnwatchParams { - watch_id: watch_response.watch_id, - }) + .send_fs_unwatch_request(FsUnwatchParams { watch_id }) .await?; timeout( DEFAULT_READ_TIMEOUT, @@ -698,8 +694,10 @@ async fn fs_watch_file_reports_atomic_replace_events() -> Result<()> { std::fs::write(&head_path, "ref: refs/heads/main\n")?; let mut mcp = initialized_mcp(&codex_home).await?; + let watch_id = "watch-head".to_string(); let watch_request_id = mcp .send_fs_watch_request(codex_app_server_protocol::FsWatchParams { + watch_id: watch_id.clone(), path: absolute_path(head_path.clone()), }) .await?; @@ -718,7 +716,7 @@ async fn fs_watch_file_reports_atomic_replace_events() -> Result<()> { assert_eq!( changed, FsChangedNotification { - watch_id: watch_response.watch_id, + watch_id, changed_paths: vec![absolute_path(head_path.clone())], } ); @@ -735,8 +733,10 @@ async fn fs_watch_allows_missing_file_targets() -> Result<()> { std::fs::create_dir_all(&git_dir)?; let mut mcp = initialized_mcp(&codex_home).await?; + let watch_id = "watch-fetch-head".to_string(); let watch_request_id = mcp .send_fs_watch_request(codex_app_server_protocol::FsWatchParams { + watch_id: watch_id.clone(), path: absolute_path(fetch_head.clone()), }) .await?; @@ -755,7 +755,7 @@ async fn fs_watch_allows_missing_file_targets() -> Result<()> { assert_eq!( changed, FsChangedNotification { - watch_id: watch_response.watch_id, + watch_id, changed_paths: vec![absolute_path(fetch_head.clone())], } ); @@ -770,7 +770,10 @@ async fn fs_watch_rejects_relative_paths() -> Result<()> { let mut mcp = initialized_mcp(&codex_home).await?; let watch_id = mcp - .send_raw_request("fs/watch", Some(json!({ "path": "relative-path" }))) + .send_raw_request( + "fs/watch", + Some(json!({ "watchId": "watch-relative", "path": "relative-path" })), + ) .await?; expect_error_message( &mut mcp, From 470b3592e60519aaeacb435446a44f6b7e4a553b Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 7 Apr 2026 11:33:35 -0700 Subject: [PATCH 26/28] Add full-ci branch trigger (#16980) Allow branches to trigger full ci (helpful to run remote tests) --- .github/workflows/rust-ci-full.yml | 1 + codex-rs/core/src/plugins/startup_sync_tests.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/rust-ci-full.yml b/.github/workflows/rust-ci-full.yml index 146e57524c..97fa33283e 100644 --- a/.github/workflows/rust-ci-full.yml +++ b/.github/workflows/rust-ci-full.yml @@ -3,6 +3,7 @@ on: push: branches: - main + - "**full-ci**" workflow_dispatch: # CI builds in debug (dev) for faster signal. diff --git a/codex-rs/core/src/plugins/startup_sync_tests.rs b/codex-rs/core/src/plugins/startup_sync_tests.rs index cd0b91f4db..74dd0d0fdb 100644 --- a/codex-rs/core/src/plugins/startup_sync_tests.rs +++ b/codex-rs/core/src/plugins/startup_sync_tests.rs @@ -34,6 +34,7 @@ fn has_plugins_clone_dirs(codex_home: &Path) -> bool { }) } +#[cfg(unix)] fn write_executable_script(path: &Path, contents: &str) { #[cfg(unix)] use std::os::unix::fs::PermissionsExt; From 59af4a730cda33974053afecf62e6cae00c269a4 Mon Sep 17 00:00:00 2001 From: Ruslan Nigmatullin Date: Tue, 7 Apr 2026 11:36:17 -0700 Subject: [PATCH 27/28] app-server: Allow enabling remote control in runtime (#16973) Refresh the feature flag on writes to the config. --- codex-rs/app-server/src/in_process.rs | 1 + codex-rs/app-server/src/lib.rs | 28 ++-- codex-rs/app-server/src/message_processor.rs | 30 +++- .../src/message_processor/tracing_tests.rs | 1 + codex-rs/app-server/src/transport/mod.rs | 1 + .../src/transport/remote_control/mod.rs | 43 +++++- .../src/transport/remote_control/tests.rs | 117 ++++++++++++--- .../src/transport/remote_control/websocket.rs | 133 +++++++++++++----- 8 files changed, 285 insertions(+), 69 deletions(-) diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 5d8cf052c5..7bddd8a714 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -398,6 +398,7 @@ fn start_uninitialized(args: InProcessStartArgs) -> InProcessClientHandle { session_source: args.session_source, auth_manager, rpc_transport: AppServerRpcTransport::InProcess, + remote_control_handle: None, }); let mut thread_created_rx = processor.thread_created_receiver(); let mut session = ConnectionSessionState::default(); diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 5e02cdb948..a837d9c754 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -564,25 +564,26 @@ pub async fn run_main_with_transport( let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); - if config.features.enabled(Feature::RemoteControl) { - let accept_handle = start_remote_control( - config.chatgpt_base_url.clone(), - state_db.clone(), - auth_manager.clone(), - transport_event_tx.clone(), - transport_shutdown_token.clone(), - app_server_client_name_rx, - ) - .await?; - transport_accept_handles.push(accept_handle); - } - if transport_accept_handles.is_empty() { + let remote_control_enabled = config.features.enabled(Feature::RemoteControl); + if transport_accept_handles.is_empty() && !remote_control_enabled { return Err(std::io::Error::new( ErrorKind::InvalidInput, "no transport configured; use --listen or enable remote control", )); } + let (remote_control_accept_handle, remote_control_handle) = start_remote_control( + config.chatgpt_base_url.clone(), + state_db.clone(), + auth_manager.clone(), + transport_event_tx.clone(), + transport_shutdown_token.clone(), + app_server_client_name_rx, + remote_control_enabled, + ) + .await?; + transport_accept_handles.push(remote_control_accept_handle); + let outbound_handle = tokio::spawn(async move { let mut outbound_connections = HashMap::::new(); loop { @@ -659,6 +660,7 @@ pub async fn run_main_with_transport( session_source, auth_manager, rpc_transport: analytics_rpc_transport(transport), + remote_control_handle: Some(remote_control_handle), }); let mut thread_created_rx = processor.thread_created_receiver(); let mut running_turn_count_rx = processor.subscribe_running_assistant_turn_count(); diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 15df5a2a54..fbc1bd6d10 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -19,6 +19,7 @@ use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::RequestContext; use crate::transport::AppServerTransport; +use crate::transport::RemoteControlHandle; use async_trait::async_trait; use codex_analytics::AnalyticsEventsClient; use codex_analytics::AppServerRpcTransport; @@ -170,6 +171,7 @@ pub(crate) struct MessageProcessor { config: Arc, config_warnings: Arc>, rpc_transport: AppServerRpcTransport, + remote_control_handle: Option, } #[derive(Clone, Debug, Default)] @@ -195,6 +197,7 @@ pub(crate) struct MessageProcessorArgs { pub(crate) session_source: SessionSource, pub(crate) auth_manager: Arc, pub(crate) rpc_transport: AppServerRpcTransport, + pub(crate) remote_control_handle: Option, } impl MessageProcessor { @@ -215,6 +218,7 @@ impl MessageProcessor { session_source, auth_manager, rpc_transport, + remote_control_handle, } = args; auth_manager.set_external_auth(Arc::new(ExternalAuthRefreshBridge { outgoing: outgoing.clone(), @@ -285,6 +289,7 @@ impl MessageProcessor { config, config_warnings: Arc::new(config_warnings), rpc_transport, + remote_control_handle, } } @@ -969,13 +974,36 @@ impl MessageProcessor { ) { match result { Ok(response) => { - self.codex_message_processor.handle_config_mutation(); + self.handle_config_mutation().await; self.outgoing.send_response(request_id, response).await; } Err(error) => self.outgoing.send_error(request_id, error).await, } } + async fn handle_config_mutation(&self) { + self.codex_message_processor.handle_config_mutation(); + let Some(remote_control_handle) = &self.remote_control_handle else { + return; + }; + + match self + .config_api + .load_latest_config(/*fallback_cwd*/ None) + .await + { + Ok(config) => { + remote_control_handle.set_enabled(config.features.enabled(Feature::RemoteControl)); + } + Err(error) => { + tracing::warn!( + "failed to load config for remote control enablement refresh after config mutation: {}", + error.message + ); + } + } + } + async fn handle_config_requirements_read(&self, request_id: ConnectionRequestId) { match self.config_api.config_requirements_read().await { Ok(response) => self.outgoing.send_response(request_id, response).await, diff --git a/codex-rs/app-server/src/message_processor/tracing_tests.rs b/codex-rs/app-server/src/message_processor/tracing_tests.rs index 2e8781606f..ef88364a3a 100644 --- a/codex-rs/app-server/src/message_processor/tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor/tracing_tests.rs @@ -251,6 +251,7 @@ fn build_test_processor( session_source: SessionSource::VSCode, auth_manager, rpc_transport: AppServerRpcTransport::Stdio, + remote_control_handle: None, }); (processor, outgoing_rx) } diff --git a/codex-rs/app-server/src/transport/mod.rs b/codex-rs/app-server/src/transport/mod.rs index 7e1512a794..92383cb78f 100644 --- a/codex-rs/app-server/src/transport/mod.rs +++ b/codex-rs/app-server/src/transport/mod.rs @@ -33,6 +33,7 @@ mod remote_control; mod stdio; mod websocket; +pub(crate) use remote_control::RemoteControlHandle; pub(crate) use remote_control::start_remote_control; pub(crate) use stdio::start_stdio_connection; pub(crate) use websocket::start_websocket_acceptor; diff --git a/codex-rs/app-server/src/transport/remote_control/mod.rs b/codex-rs/app-server/src/transport/remote_control/mod.rs index 6d9d65e8a3..1ea89bb643 100644 --- a/codex-rs/app-server/src/transport/remote_control/mod.rs +++ b/codex-rs/app-server/src/transport/remote_control/mod.rs @@ -19,6 +19,7 @@ use std::io; use std::sync::Arc; use tokio::sync::mpsc; use tokio::sync::oneshot; +use tokio::sync::watch; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; @@ -29,6 +30,21 @@ pub(super) struct QueuedServerEnvelope { pub(super) write_complete_tx: Option>, } +#[derive(Clone)] +pub(crate) struct RemoteControlHandle { + enabled_tx: Arc>, +} + +impl RemoteControlHandle { + pub(crate) fn set_enabled(&self, enabled: bool) { + self.enabled_tx.send_if_modified(|state| { + let changed = *state != enabled; + *state = enabled; + changed + }); + } +} + pub(crate) async fn start_remote_control( remote_control_url: String, state_db: Option>, @@ -36,21 +52,38 @@ pub(crate) async fn start_remote_control( transport_event_tx: mpsc::Sender, shutdown_token: CancellationToken, app_server_client_name_rx: Option>, -) -> io::Result> { - let remote_control_target = normalize_remote_control_url(&remote_control_url)?; - validate_remote_control_auth(&auth_manager).await?; + initial_enabled: bool, +) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> { + let remote_control_target = if initial_enabled { + Some(normalize_remote_control_url(&remote_control_url)?) + } else { + None + }; + if initial_enabled { + validate_remote_control_auth(&auth_manager).await?; + } - Ok(tokio::spawn(async move { + let (enabled_tx, enabled_rx) = watch::channel(initial_enabled); + let join_handle = tokio::spawn(async move { RemoteControlWebsocket::new( + remote_control_url, remote_control_target, state_db, auth_manager, transport_event_tx, shutdown_token, + enabled_rx, ) .run(app_server_client_name_rx) .await; - })) + }); + + Ok(( + join_handle, + RemoteControlHandle { + enabled_tx: Arc::new(enabled_tx), + }, + )) } pub(crate) async fn validate_remote_control_auth( diff --git a/codex-rs/app-server/src/transport/remote_control/tests.rs b/codex-rs/app-server/src/transport/remote_control/tests.rs index b403fac484..9d430ccfb3 100644 --- a/codex-rs/app-server/src/transport/remote_control/tests.rs +++ b/codex-rs/app-server/src/transport/remote_control/tests.rs @@ -125,13 +125,14 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages() let (transport_event_tx, mut transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(remote_control_state_runtime(&codex_home).await), remote_control_auth_manager(), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -376,7 +377,7 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages() ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -389,13 +390,14 @@ async fn remote_control_transport_reconnects_after_disconnect() { let (transport_event_tx, mut transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(remote_control_state_runtime(&codex_home).await), remote_control_auth_manager(), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -452,7 +454,84 @@ async fn remote_control_transport_reconnects_after_disconnect() { } shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; +} + +#[tokio::test] +async fn remote_control_start_allows_remote_control_invalid_url_when_disabled() { + let (transport_event_tx, _transport_event_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let shutdown_token = CancellationToken::new(); + let (remote_task, _remote_handle) = start_remote_control( + "https://internal.example.com/backend-api/".to_string(), + /*state_db*/ None, + remote_control_auth_manager(), + transport_event_tx, + shutdown_token.clone(), + /*app_server_client_name_rx*/ None, + /*initial_enabled*/ false, + ) + .await + .expect("disabled remote control should not validate the URL at startup"); + + shutdown_token.cancel(); + timeout(Duration::from_secs(1), remote_task) + .await + .expect("remote control task should stop") + .expect("remote control task should join"); +} + +#[tokio::test] +async fn remote_control_handle_set_enabled_stops_and_restarts_connections() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let remote_control_url = remote_control_url_for_listener(&listener); + let codex_home = TempDir::new().expect("temp dir should create"); + let (transport_event_tx, _transport_event_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let shutdown_token = CancellationToken::new(); + let (remote_task, remote_handle) = start_remote_control( + remote_control_url, + Some(remote_control_state_runtime(&codex_home).await), + remote_control_auth_manager(), + transport_event_tx, + shutdown_token.clone(), + /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, + ) + .await + .expect("remote control should start"); + + let enroll_request = accept_http_request(&listener).await; + assert_eq!( + enroll_request.request_line, + "POST /backend-api/wham/remote/control/server/enroll HTTP/1.1" + ); + respond_with_json( + enroll_request.stream, + json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + ) + .await; + let mut first_websocket = accept_remote_control_connection(&listener).await; + + remote_handle.set_enabled(/*enabled*/ false); + timeout(Duration::from_secs(1), first_websocket.next()) + .await + .expect("disabling remote control should close the websocket"); + timeout(Duration::from_millis(100), listener.accept()) + .await + .expect_err("disabled remote control should not reconnect"); + + remote_handle.set_enabled(/*enabled*/ true); + let mut second_websocket = accept_remote_control_connection(&listener).await; + second_websocket + .close(None) + .await + .expect("second websocket should close"); + + shutdown_token.cancel(); + let _ = remote_task.await; } #[tokio::test] @@ -465,13 +544,14 @@ async fn remote_control_transport_clears_outgoing_buffer_when_backend_acks() { let (transport_event_tx, mut transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(remote_control_state_runtime(&codex_home).await), remote_control_auth_manager(), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -617,7 +697,7 @@ async fn remote_control_transport_clears_outgoing_buffer_when_backend_acks() { ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -631,13 +711,14 @@ async fn remote_control_http_mode_enrolls_before_connecting() { mpsc::channel::(CHANNEL_CAPACITY); let expected_server_name = gethostname().to_string_lossy().trim().to_string(); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(remote_control_state_runtime(&codex_home).await), remote_control_auth_manager(), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -815,7 +896,7 @@ async fn remote_control_http_mode_enrolls_before_connecting() { ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -847,13 +928,14 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling let (transport_event_tx, _transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(state_db.clone()), remote_control_auth_manager_with_home(&codex_home), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -879,7 +961,7 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -913,13 +995,14 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() { mpsc::channel::(CHANNEL_CAPACITY); let (app_server_client_name_tx, app_server_client_name_rx) = oneshot::channel::(); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(state_db.clone()), remote_control_auth_manager_with_home(&codex_home), transport_event_tx, shutdown_token.clone(), Some(app_server_client_name_rx), + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -936,7 +1019,7 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() { ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -969,13 +1052,14 @@ async fn remote_control_waits_for_account_id_before_enrolling() { let (transport_event_tx, _transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(state_db.clone()), auth_manager, transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start before account id is available"); @@ -1012,7 +1096,7 @@ async fn remote_control_waits_for_account_id_before_enrolling() { ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[tokio::test] @@ -1051,13 +1135,14 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() let (transport_event_tx, _transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); - let remote_handle = start_remote_control( + let (remote_task, _remote_handle) = start_remote_control( remote_control_url, Some(state_db.clone()), remote_control_auth_manager_with_home(&codex_home), transport_event_tx, shutdown_token.clone(), /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, ) .await .expect("remote control should start"); @@ -1104,7 +1189,7 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() ); shutdown_token.cancel(); - let _ = remote_handle.await; + let _ = remote_task.await; } #[derive(Debug)] diff --git a/codex-rs/app-server/src/transport/remote_control/websocket.rs b/codex-rs/app-server/src/transport/remote_control/websocket.rs index 3f42a7bbbe..a0387ef6c3 100644 --- a/codex-rs/app-server/src/transport/remote_control/websocket.rs +++ b/codex-rs/app-server/src/transport/remote_control/websocket.rs @@ -111,7 +111,8 @@ struct WebsocketState { } pub(crate) struct RemoteControlWebsocket { - remote_control_target: RemoteControlTarget, + remote_control_url: String, + remote_control_target: Option, state_db: Option>, auth_manager: Arc, shutdown_token: CancellationToken, @@ -122,15 +123,24 @@ pub(crate) struct RemoteControlWebsocket { state: Arc>, server_event_rx: Arc>>, used_rx: watch::Receiver, + enabled_rx: watch::Receiver, +} + +enum ConnectOutcome { + Connected(Box>>), + Disabled, + Shutdown, } impl RemoteControlWebsocket { pub(crate) fn new( - remote_control_target: RemoteControlTarget, + remote_control_url: String, + remote_control_target: Option, state_db: Option>, auth_manager: Arc, transport_event_tx: mpsc::Sender, shutdown_token: CancellationToken, + enabled_rx: watch::Receiver, ) -> Self { let shutdown_token = shutdown_token.child_token(); let (server_event_tx, server_event_rx) = mpsc::channel(super::CHANNEL_CAPACITY); @@ -140,6 +150,7 @@ impl RemoteControlWebsocket { let auth_recovery = auth_manager.unauthorized_recovery(); Self { + remote_control_url, remote_control_target, state_db, auth_manager, @@ -155,6 +166,7 @@ impl RemoteControlWebsocket { })), server_event_rx: Arc::new(Mutex::new(server_event_rx)), used_rx, + enabled_rx, } } @@ -174,13 +186,18 @@ impl RemoteControlWebsocket { }; loop { + if !self.wait_until_enabled().await { + break; + } + let shutdown_token = self.shutdown_token.child_token(); let websocket_connection = match self .connect(&shutdown_token, app_server_client_name.as_deref()) .await { - Some(websocket_connection) => websocket_connection, - None => break, + ConnectOutcome::Connected(websocket_connection) => *websocket_connection, + ConnectOutcome::Disabled => continue, + ConnectOutcome::Shutdown => break, }; self.run_connection(websocket_connection, shutdown_token) @@ -208,50 +225,93 @@ impl RemoteControlWebsocket { } } + async fn wait_until_enabled(&mut self) -> bool { + tokio::select! { + _ = self.shutdown_token.cancelled() => false, + enabled = self.enabled_rx.wait_for(|enabled| *enabled) => enabled.is_ok(), + } + } + async fn connect( &mut self, shutdown_token: &CancellationToken, app_server_client_name: Option<&str>, - ) -> Option>> { + ) -> ConnectOutcome { + let remote_control_target = match self.remote_control_target.as_ref() { + Some(remote_control_target) => remote_control_target.clone(), + None => match super::protocol::normalize_remote_control_url(&self.remote_control_url) { + Ok(remote_control_target) => { + self.remote_control_target = Some(remote_control_target.clone()); + remote_control_target + } + Err(err) => { + warn!("remote control is enabled but the URL is invalid: {err}"); + tokio::select! { + _ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown, + changed = self.enabled_rx.wait_for(|enabled| !*enabled) => { + if changed.is_err() { + return ConnectOutcome::Shutdown; + } + return ConnectOutcome::Disabled; + } + } + } + }, + }; + loop { let subscribe_cursor = self.state.lock().await.subscribe_cursor.clone(); - tokio::select! { - _ = shutdown_token.cancelled() => return None, + let connect_result = tokio::select! { + _ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown, + changed = self.enabled_rx.wait_for(|enabled| !*enabled) => { + if changed.is_err() { + return ConnectOutcome::Shutdown; + } + return ConnectOutcome::Disabled; + } connect_result = connect_remote_control_websocket( - &self.remote_control_target, + &remote_control_target, self.state_db.as_deref(), &self.auth_manager, &mut self.auth_recovery, &mut self.enrollment, subscribe_cursor.as_deref(), app_server_client_name, - ) => { - match connect_result { - Ok((websocket_connection, response)) => { - self.reconnect_attempt = 0; - self.auth_recovery = self.auth_manager.unauthorized_recovery(); - info!( - "connected to app-server remote control websocket: {}, {}", - self.remote_control_target.websocket_url, - format_headers(response.headers()) - ); - return Some(websocket_connection); - } - Err(err) => { - let reconnect_delay = if err.kind() == ErrorKind::WouldBlock { - info!("{err}"); - REMOTE_CONTROL_ACCOUNT_ID_RETRY_INTERVAL - } else { - warn!("{err}"); - let reconnect_delay = backoff(self.reconnect_attempt); - self.reconnect_attempt += 1; - reconnect_delay - }; - tokio::select! { - _ = shutdown_token.cancelled() => return None, - _ = tokio::time::sleep(reconnect_delay) => {} + ) => connect_result, + }; + + match connect_result { + Ok((websocket_connection, response)) => { + self.reconnect_attempt = 0; + self.auth_recovery = self.auth_manager.unauthorized_recovery(); + info!( + "connected to app-server remote control websocket: {}, {}", + remote_control_target.websocket_url, + format_headers(response.headers()) + ); + return ConnectOutcome::Connected(Box::new(websocket_connection)); + } + Err(err) => { + let reconnect_delay = if err.kind() == ErrorKind::WouldBlock { + REMOTE_CONTROL_ACCOUNT_ID_RETRY_INTERVAL + } else { + warn!( + "failed to connect to app-server remote control websocket: {}, err: {}", + remote_control_target.websocket_url, err + ); + let reconnect_delay = backoff(self.reconnect_attempt); + self.reconnect_attempt += 1; + reconnect_delay + }; + tokio::select! { + _ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown, + changed = self.enabled_rx.wait_for(|enabled| !*enabled) => { + if changed.is_err() { + return ConnectOutcome::Shutdown; } + return ConnectOutcome::Disabled; } + _ = tokio::time::sleep(reconnect_delay) => {} } } } @@ -282,8 +342,10 @@ impl RemoteControlWebsocket { shutdown_token.clone(), )); + let mut enabled_rx = self.enabled_rx.clone(); tokio::select! { _ = shutdown_token.cancelled() => {} + _ = enabled_rx.wait_for(|enabled| !*enabled) => shutdown_token.cancel(), _ = join_set.join_next() => shutdown_token.cancel(), } @@ -1124,15 +1186,18 @@ mod tests { let (transport_event_tx, transport_event_rx) = mpsc::channel(1); drop(transport_event_rx); let shutdown_token = CancellationToken::new(); + let (_enabled_tx, enabled_rx) = watch::channel(true); let websocket_task = tokio::spawn({ let shutdown_token = shutdown_token.clone(); async move { RemoteControlWebsocket::new( - remote_control_target, + remote_control_url, + Some(remote_control_target), /*state_db*/ None, remote_control_auth_manager(), transport_event_tx, shutdown_token, + enabled_rx, ) .run(/*app_server_client_name_rx*/ None) .await From 8614f92fc433fff20b1bf745be8b23cfb01d3d98 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 7 Apr 2026 12:01:06 -0700 Subject: [PATCH 28/28] [codex] Fix unified exec test build (#17032) ## Summary - Remove the stale `?` after `AbsolutePathBuf::join` in the unified exec integration test helper. ## Root Cause - `AbsolutePathBuf::join` was made infallible, but `core/tests/suite/unified_exec.rs` still treated it as a `Result`, which broke the Windows test build for the `all` integration test target. ## Validation - `just fmt` - `cargo test -p codex-core --test all unified_exec_resolves_relative_workdir` --- codex-rs/core/tests/suite/unified_exec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 226c5c6af5..a165db0451 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -171,7 +171,7 @@ async fn create_workspace_directory( test: &TestCodex, rel_path: impl AsRef, ) -> Result { - let abs_path = test.config.cwd.join(rel_path.as_ref())?; + let abs_path = test.config.cwd.join(rel_path.as_ref()); test.fs() .create_directory(&abs_path, CreateDirectoryOptions { recursive: true }) .await?;