From 83c4934e45d22dab962c55817fdbdc134e98dca6 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 23 Jun 2026 00:31:56 -0700 Subject: [PATCH 01/11] Remove redundant Codex Apps cache guard (#29575) ## Why Codex Apps cache writes are already restricted to Codex Apps call paths: startup invokes the helper only from the Codex Apps branch, and hard refresh operates on the reserved Codex Apps server directly. Rechecking the server name inside the cache helper duplicates that classification and leaves the helper with an argument that cannot change valid behavior. ## What changed - Remove the redundant server-name check and parameter from the cache writer. - Rename the helper to `write_codex_apps_tools_cache` to reflect its narrower contract. - Update production and test callsites to use the simplified API. --- codex-rs/codex-mcp/src/codex_apps.rs | 8 +------- codex-rs/codex-mcp/src/connection_manager.rs | 5 ++--- codex-rs/codex-mcp/src/connection_manager_tests.rs | 12 +++--------- codex-rs/codex-mcp/src/rmcp_client.rs | 5 ++--- 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/codex-rs/codex-mcp/src/codex_apps.rs b/codex-rs/codex-mcp/src/codex_apps.rs index 53b546b8a0..437e750de8 100644 --- a/codex-rs/codex-mcp/src/codex_apps.rs +++ b/codex-rs/codex-mcp/src/codex_apps.rs @@ -8,7 +8,6 @@ use std::path::PathBuf; use std::time::Instant; -use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::runtime::emit_duration; use crate::tools::MCP_TOOLS_CACHE_WRITE_DURATION_METRIC; use crate::tools::ToolInfo; @@ -125,16 +124,11 @@ pub(crate) fn normalize_codex_apps_callable_namespace( } } -pub(crate) fn write_cached_codex_apps_tools_if_needed( - server_name: &str, +pub(crate) fn write_codex_apps_tools_cache( cache_context: Option<&CodexAppsToolsCacheContext>, server_info: &McpServerInfo, tools: &[ToolInfo], ) { - if server_name != CODEX_APPS_MCP_SERVER_NAME { - return; - } - if let Some(cache_context) = cache_context { let cache_write_start = Instant::now(); write_cached_codex_apps_tools(cache_context, tools); diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index a881e865d2..be27843071 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -16,7 +16,7 @@ use std::time::Instant; use crate::McpAuthStatusEntry; use crate::codex_apps::CodexAppsToolsCacheContext; use crate::codex_apps::CodexAppsToolsCacheKey; -use crate::codex_apps::write_cached_codex_apps_tools_if_needed; +use crate::codex_apps::write_codex_apps_tools_cache; use crate::elicitation::ElicitationRequestManager; use crate::elicitation::ElicitationReviewerHandle; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; @@ -521,8 +521,7 @@ impl McpConnectionManager { &[], ); - write_cached_codex_apps_tools_if_needed( - CODEX_APPS_MCP_SERVER_NAME, + write_codex_apps_tools_cache( managed_client.codex_apps_tools_cache_context.as_ref(), &managed_client.server_info, &tools, diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index 05b3917027..4556973928 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -5,7 +5,7 @@ use crate::codex_apps::load_startup_cached_codex_apps_server_info; use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot; use crate::codex_apps::read_cached_codex_apps_tools; use crate::codex_apps::write_cached_codex_apps_tools; -use crate::codex_apps::write_cached_codex_apps_tools_if_needed; +use crate::codex_apps::write_codex_apps_tools_cache; use crate::declared_openai_file_input_param_names; use crate::elicitation::ElicitationRequestManager; use crate::elicitation::elicitation_is_rejected_by_policy; @@ -704,12 +704,7 @@ fn startup_cached_codex_apps_tools_loads_from_disk_cache() { "calendar_search", )]; let server_info = create_test_server_info("Codex Apps"); - write_cached_codex_apps_tools_if_needed( - CODEX_APPS_MCP_SERVER_NAME, - Some(&cache_context), - &server_info, - &cached_tools, - ); + write_codex_apps_tools_cache(Some(&cache_context), &server_info, &cached_tools); let startup_tools = load_startup_cached_codex_apps_tools_snapshot(Some(&cache_context)) .expect("expected startup snapshot to load from cache"); @@ -758,8 +753,7 @@ fn codex_apps_server_info_cache_survives_legacy_tools_cache_write() { Some("user-one"), ); let server_info = create_test_server_info("Codex Apps"); - write_cached_codex_apps_tools_if_needed( - CODEX_APPS_MCP_SERVER_NAME, + write_codex_apps_tools_cache( Some(&cache_context), &server_info, &[create_test_tool( diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index f8173b6003..f9cc6a5e81 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -25,7 +25,7 @@ use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot; use crate::codex_apps::normalize_codex_apps_callable_name; use crate::codex_apps::normalize_codex_apps_callable_namespace; use crate::codex_apps::normalize_codex_apps_tool_title; -use crate::codex_apps::write_cached_codex_apps_tools_if_needed; +use crate::codex_apps::write_codex_apps_tools_cache; use crate::elicitation::ElicitationRequestManager; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::ToolPluginProvenance; @@ -581,8 +581,7 @@ async fn start_server_task( ); let server_info = mcp_server_info_from_implementation(initialize_result.server_info); let codex_apps_tools_cache_context = if is_codex_apps_mcp_server { - write_cached_codex_apps_tools_if_needed( - &server_name, + write_codex_apps_tools_cache( codex_apps_tools_cache_context.as_ref(), &server_info, &tools, From 266dcbfe5b1972c027a4c04728e45949ccc1e820 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 23 Jun 2026 00:53:17 -0700 Subject: [PATCH 02/11] Group Codex Apps client setup (#29583) ## Why `McpConnectionManager::new` classified the Codex Apps server twice: once to create its tools cache context and again to select its runtime authentication provider. Keeping those decisions separate makes it harder to see that they belong to the same server-specific setup path. ## What changed - Group Codex Apps cache and authentication setup under one explicit branch. - Keep regular MCP server setup in the corresponding `else` branch. - Limit environment bearer-token inspection to the Codex Apps path where it affects runtime authentication. --- codex-rs/codex-mcp/src/connection_manager.rs | 77 ++++++++++++++------ 1 file changed, 55 insertions(+), 22 deletions(-) diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index be27843071..3057161117 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -7,6 +7,7 @@ //! `codex-core`. use std::collections::HashMap; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::Ordering; @@ -40,6 +41,7 @@ use anyhow::Context; use anyhow::Result; use anyhow::anyhow; use async_channel::Sender; +use codex_api::SharedAuthProvider; use codex_config::Constrained; use codex_config::McpServerTransportConfig; use codex_config::types::AuthKeyringBackendKind; @@ -171,29 +173,16 @@ impl McpConnectionManager { }, ) .await; - let codex_apps_tools_cache_context = if server_name == CODEX_APPS_MCP_SERVER_NAME { - Some(CodexAppsToolsCacheContext { - codex_home: codex_home.clone(), - user_key: codex_apps_tools_cache_key.clone(), - }) - } else { - None - }; - let uses_env_bearer_token = - server - .configured_config() - .is_some_and(|config| match &config.transport { - McpServerTransportConfig::StreamableHttp { - bearer_token_env_var, - .. - } => bearer_token_env_var.is_some(), - McpServerTransportConfig::Stdio { .. } => false, - }); - let runtime_auth_provider = - if server_name == CODEX_APPS_MCP_SERVER_NAME && !uses_env_bearer_token { - codex_apps_auth_provider.clone() + let (codex_apps_tools_cache_context, runtime_auth_provider) = + if server_name == CODEX_APPS_MCP_SERVER_NAME { + codex_apps_cache_context_and_auth_provider( + &server, + &codex_home, + &codex_apps_tools_cache_key, + codex_apps_auth_provider.clone(), + ) } else { - None + regular_mcp_cache_context_and_auth_provider() }; let async_managed_client = AsyncManagedClient::new( server_name.clone(), @@ -856,6 +845,50 @@ impl Drop for McpConnectionManager { } } +/// Creates the host-owned state used only by the Codex Apps server. +/// +/// The tools cache is scoped to the authenticated user. Runtime authentication is supplied only +/// when the server is not already configured to read a bearer token from the environment. +fn codex_apps_cache_context_and_auth_provider( + server: &EffectiveMcpServer, + codex_home: &Path, + codex_apps_tools_cache_key: &CodexAppsToolsCacheKey, + codex_apps_auth_provider: Option, +) -> ( + Option, + Option, +) { + let uses_env_bearer_token = + server + .configured_config() + .is_some_and(|config| match &config.transport { + McpServerTransportConfig::StreamableHttp { + bearer_token_env_var, + .. + } => bearer_token_env_var.is_some(), + McpServerTransportConfig::Stdio { .. } => false, + }); + ( + Some(CodexAppsToolsCacheContext { + codex_home: codex_home.to_path_buf(), + user_key: codex_apps_tools_cache_key.clone(), + }), + if uses_env_bearer_token { + None + } else { + codex_apps_auth_provider + }, + ) +} + +/// Keeps regular MCP servers isolated from the host-owned Codex Apps cache and auth provider. +fn regular_mcp_cache_context_and_auth_provider() -> ( + Option, + Option, +) { + (None, None) +} + async fn emit_update( submit_id: &str, tx_event: &Sender, From d2484697b1f9ce33d1d818ccad859ca3a4d721c6 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 09:17:52 +0100 Subject: [PATCH 03/11] Allow codex sandbox to consume MCP sandbox state (#29358) ## Summary - let `codex sandbox` accept the JSON value from `codex/sandbox-state-meta` - require the payload `permissionProfile` instead of falling back to ambient permissions - reuse the existing macOS, Linux, and Windows launch paths, treating external sandbox state conservatively as read-only - let opaque forwarders add runtime read roots and disable direct network access without decoding the payload Builds on #29113, which is now on `main`. ## Tests - `just test -p codex-cli debug_sandbox::tests` - `cargo build -p codex-rmcp-client --bin test_stdio_server` - `just test -p codex-core stdio_mcp_tool_call_includes_sandbox_state_meta` - `just test -p codex-mcp` - `just fmt` --- codex-rs/cli/src/debug_sandbox.rs | 122 +++++++++++++++++++++-- codex-rs/cli/src/lib.rs | 37 ++++++- codex-rs/codex-mcp/src/runtime.rs | 5 +- codex-rs/core/src/mcp_tool_call.rs | 2 +- codex-rs/core/tests/suite/rmcp_client.rs | 14 ++- 5 files changed, 162 insertions(+), 18 deletions(-) diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 5e5bcb6c4e..dd2d646aa6 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -6,6 +6,7 @@ mod seatbelt; use std::path::PathBuf; use std::process::Stdio; +use anyhow::Context as _; use codex_config::LoaderOverrides; use codex_core::config::Config; use codex_core::config::ConfigBuilder; @@ -16,6 +17,8 @@ use codex_core::exec_env::create_env; use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_protocol::config_types::SandboxMode; +use codex_protocol::models::PermissionProfile; +use codex_protocol::models::SandboxEnforcement; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_sandboxing::landlock::allow_network_for_proxy; use codex_sandboxing::landlock::create_linux_sandbox_command_args_for_permission_profile; @@ -45,6 +48,7 @@ pub async fn run_command_under_seatbelt( loader_overrides: LoaderOverrides, ) -> anyhow::Result<()> { let SeatbeltCommand { + sandbox_state, permissions_profile, config_profile: _, cwd, @@ -60,6 +64,7 @@ pub async fn run_command_under_seatbelt( ); run_command_under_sandbox( DebugSandboxConfigOptions { + sandbox_state, permissions_profile, cwd, managed_requirements_mode, @@ -90,6 +95,7 @@ pub async fn run_command_under_landlock( loader_overrides: LoaderOverrides, ) -> anyhow::Result<()> { let LandlockCommand { + sandbox_state, permissions_profile, config_profile: _, cwd, @@ -103,6 +109,7 @@ pub async fn run_command_under_landlock( ); run_command_under_sandbox( DebugSandboxConfigOptions { + sandbox_state, permissions_profile, cwd, managed_requirements_mode, @@ -124,6 +131,7 @@ pub async fn run_command_under_windows_sandbox( loader_overrides: LoaderOverrides, ) -> anyhow::Result<()> { let WindowsCommand { + sandbox_state, permissions_profile, config_profile: _, cwd, @@ -137,6 +145,7 @@ pub async fn run_command_under_windows_sandbox( ); run_command_under_sandbox( DebugSandboxConfigOptions { + sandbox_state, permissions_profile, cwd, managed_requirements_mode, @@ -161,6 +170,7 @@ enum SandboxType { #[derive(Debug)] struct DebugSandboxConfigOptions { + sandbox_state: crate::SandboxStateArgs, permissions_profile: Option, cwd: Option, managed_requirements_mode: ManagedRequirementsMode, @@ -187,7 +197,7 @@ impl ManagedRequirementsMode { } async fn run_command_under_sandbox( - config_options: DebugSandboxConfigOptions, + mut config_options: DebugSandboxConfigOptions, command: Vec, config_overrides: CliConfigOverrides, codex_linux_sandbox_exe: Option, @@ -196,6 +206,34 @@ async fn run_command_under_sandbox( #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] allow_unix_sockets: &[AbsolutePathBuf], ) -> anyhow::Result<()> { + let sandbox_state = config_options + .sandbox_state + .sandbox_state_json + .as_deref() + .map(serde_json::from_str::) + .transpose() + .map_err(|err| anyhow::anyhow!("invalid --sandbox-state-json value: {err}"))?; + let sandbox_state_readable_root = config_options + .sandbox_state + .sandbox_state_readable_root + .clone(); + let sandbox_state_disable_network = config_options.sandbox_state.sandbox_state_disable_network; + let codex_linux_sandbox_exe = match sandbox_state.as_ref() { + Some(state) => { + config_options.cwd = Some( + state + .sandbox_cwd + .to_abs_path() + .context("sandbox state cwd is not native to this host")? + .to_path_buf(), + ); + state + .codex_linux_sandbox_exe + .clone() + .or(codex_linux_sandbox_exe) + } + None => codex_linux_sandbox_exe, + }; let config = load_debug_sandbox_config( config_overrides .parse_overrides() @@ -220,12 +258,75 @@ async fn run_command_under_sandbox( &config.permissions.shell_environment_policy, /*thread_id*/ None, ); + let mut permission_profile = match sandbox_state.as_ref() { + Some(state) => match &state.permission_profile { + PermissionProfile::External { .. } => { + // `External` only says that the producer relies on an outer sandbox; it does not + // include filesystem permissions we can recreate here. The consumer may not share + // that sandbox, so use a locally enforceable read-only profile instead of spawning + // without a sandbox. + PermissionProfile::read_only() + } + permission_profile => permission_profile.clone(), + }, + None => config.permissions.effective_permission_profile(), + }; + if matches!(permission_profile, PermissionProfile::Disabled) && sandbox_state_disable_network { + anyhow::bail!( + "--sandbox-state-disable-network cannot be applied to a disabled permission profile" + ); + } + if !matches!(permission_profile, PermissionProfile::Disabled) + && (!sandbox_state_readable_root.is_empty() || sandbox_state_disable_network) + { + let file_system = permission_profile + .file_system_sandbox_policy() + .with_additional_readable_roots(&cwd, &sandbox_state_readable_root); + let network = if sandbox_state_disable_network { + NetworkSandboxPolicy::Restricted + } else { + permission_profile.network_sandbox_policy() + }; + permission_profile = PermissionProfile::from_runtime_permissions(&file_system, network); + } + let use_legacy_landlock = sandbox_state.as_ref().map_or_else( + || config.features.use_legacy_landlock(), + |state| state.use_legacy_landlock, + ); + + match permission_profile.enforcement() { + SandboxEnforcement::Managed => {} + SandboxEnforcement::Disabled | SandboxEnforcement::External => { + let (program, args) = command + .split_first() + .context("sandbox command must not be empty")?; + let mut child = spawn_debug_sandbox_child( + PathBuf::from(program), + args.to_vec(), + /*arg0*/ None, + cwd.to_path_buf(), + permission_profile.network_sandbox_policy(), + env, + |_| {}, + ) + .await?; + handle_exit_status(child.wait().await?); + } + } // Special-case Windows sandbox: execute and exit the process to emulate inherited stdio. if let SandboxType::Windows = sandbox_type { #[cfg(target_os = "windows")] { - run_command_under_windows_session(&config, command, cwd, workspace_roots, env).await; + run_command_under_windows_session( + &config, + &permission_profile, + command, + cwd, + workspace_roots, + env, + ) + .await; } #[cfg(not(target_os = "windows"))] { @@ -244,7 +345,7 @@ async fn run_command_under_sandbox( let network_proxy = match config.permissions.network.as_ref() { Some(spec) => Some( spec.start_proxy( - config.permissions.permission_profile(), + &permission_profile, /*policy_decider*/ None, /*blocked_request_observer*/ None, managed_network_requirements_enabled, @@ -266,7 +367,7 @@ async fn run_command_under_sandbox( None => None, }; let runtime_permission_profile = with_managed_mitm_ca_readable_root( - config.permissions.effective_permission_profile(), + permission_profile, managed_mitm_ca_trust_bundle_path.as_ref(), sandbox_policy_cwd.as_path(), ); @@ -308,7 +409,6 @@ async fn run_command_under_sandbox( let codex_linux_sandbox_exe = config .codex_linux_sandbox_exe .expect("codex-linux-sandbox executable not found"); - let use_legacy_landlock = config.features.use_legacy_landlock(); let network_sandbox_policy = runtime_permission_profile.network_sandbox_policy(); let args = create_linux_sandbox_command_args_for_permission_profile( command, @@ -364,6 +464,7 @@ async fn run_command_under_sandbox( #[cfg(target_os = "windows")] async fn run_command_under_windows_session( config: &Config, + permission_profile: &PermissionProfile, command: Vec, cwd: AbsolutePathBuf, workspace_roots: Vec, @@ -374,10 +475,9 @@ async fn run_command_under_windows_session( use codex_windows_sandbox::WindowsSandboxSessionRequest; use codex_windows_sandbox::spawn_windows_sandbox_session_for_level; - let permission_profile = config.permissions.effective_permission_profile(); let empty_paths: &[AbsolutePathBuf] = &[]; let spawned = spawn_windows_sandbox_session_for_level(WindowsSandboxSessionRequest { - permission_profile: &permission_profile, + permission_profile, workspace_roots: workspace_roots.as_slice(), codex_home: config.codex_home.as_path(), command, @@ -464,6 +564,7 @@ async fn load_debug_sandbox_config_with_codex_home( strict_config: bool, ) -> anyhow::Result { let DebugSandboxConfigOptions { + sandbox_state: _, permissions_profile, cwd, managed_requirements_mode, @@ -649,6 +750,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: None, cwd: None, managed_requirements_mode: ManagedRequirementsMode::Include, @@ -717,6 +819,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: None, cwd: None, managed_requirements_mode: ManagedRequirementsMode::Include, @@ -774,6 +877,7 @@ mod tests { cli_overrides, /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: None, cwd: None, managed_requirements_mode: ManagedRequirementsMode::Include, @@ -832,6 +936,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: None, cwd: None, managed_requirements_mode: ManagedRequirementsMode::Include, @@ -859,6 +964,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: Some(":workspace".to_string()), cwd: None, managed_requirements_mode: ManagedRequirementsMode::Ignore, @@ -898,6 +1004,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: Some("limited-read-test".to_string()), cwd: None, managed_requirements_mode: ManagedRequirementsMode::Ignore, @@ -937,6 +1044,7 @@ mod tests { Vec::new(), /*codex_linux_sandbox_exe*/ None, DebugSandboxConfigOptions { + sandbox_state: Default::default(), permissions_profile: Some(":workspace".to_string()), cwd: Some(cwd.path().to_path_buf()), managed_requirements_mode: ManagedRequirementsMode::Ignore, diff --git a/codex-rs/cli/src/lib.rs b/codex-rs/cli/src/lib.rs index 4e63df187e..1c0a2e7e02 100644 --- a/codex-rs/cli/src/lib.rs +++ b/codex-rs/cli/src/lib.rs @@ -2,6 +2,7 @@ pub(crate) mod debug_sandbox; mod exit_status; pub(crate) mod login; +use clap::Args; use clap::Parser; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_cli::CliConfigOverrides; @@ -21,10 +22,36 @@ 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, Default, Args)] +pub struct SandboxStateArgs { + /// JSON value from `codex/sandbox-state-meta` to apply directly. + #[arg( + long = "sandbox-state-json", + value_name = "JSON", + conflicts_with_all = ["permissions_profile", "cwd", "include_managed_config"] + )] + pub sandbox_state_json: Option, + + /// Add a readable root to the supplied sandbox state. Repeat for multiple roots. + #[arg( + long, + requires = "sandbox_state_json", + value_parser = parse_absolute_path + )] + pub sandbox_state_readable_root: Vec, + + /// Disable direct network access in the supplied sandbox state. + #[arg(long, requires = "sandbox_state_json", default_value_t = false)] + pub sandbox_state_disable_network: bool, +} + // These command structs share common sandbox options, but remain separate // because each host backend has a slightly different option surface. #[derive(Debug, Parser)] pub struct SeatbeltCommand { + #[command(flatten)] + pub sandbox_state: SandboxStateArgs, + /// Named permissions profile to apply from the active configuration stack. #[arg(long = "permissions-profile", short = 'P', value_name = "NAME")] pub permissions_profile: Option, @@ -51,7 +78,7 @@ pub struct SeatbeltCommand { pub include_managed_config: bool, /// Allow the sandboxed command to bind/connect AF_UNIX sockets rooted at this path. Relative paths are resolved against the current directory. Repeat to allow multiple paths. - #[arg(long = "allow-unix-socket", value_parser = parse_allow_unix_socket_path)] + #[arg(long = "allow-unix-socket", value_parser = parse_absolute_path)] pub allow_unix_sockets: Vec, /// While the command runs, capture macOS sandbox denials via `log stream` and print them after exit @@ -66,13 +93,16 @@ pub struct SeatbeltCommand { pub command: Vec, } -fn parse_allow_unix_socket_path(raw: &str) -> Result { +fn parse_absolute_path(raw: &str) -> Result { AbsolutePathBuf::relative_to_current_dir(raw) .map_err(|err| format!("invalid path {raw}: {err}")) } #[derive(Debug, Parser)] pub struct LandlockCommand { + #[command(flatten)] + pub sandbox_state: SandboxStateArgs, + /// Named permissions profile to apply from the active configuration stack. #[arg(long = "permissions-profile", short = 'P', value_name = "NAME")] pub permissions_profile: Option, @@ -108,6 +138,9 @@ pub struct LandlockCommand { #[derive(Debug, Parser)] pub struct WindowsCommand { + #[command(flatten)] + pub sandbox_state: SandboxStateArgs, + /// Named permissions profile to apply from the active configuration stack. #[arg(long = "permissions-profile", short = 'P', value_name = "NAME")] pub permissions_profile: Option, diff --git a/codex-rs/codex-mcp/src/runtime.rs b/codex-rs/codex-mcp/src/runtime.rs index e52048349c..e48bdc7f29 100644 --- a/codex-rs/codex-mcp/src/runtime.rs +++ b/codex-rs/codex-mcp/src/runtime.rs @@ -17,11 +17,10 @@ use codex_utils_path_uri::PathUri; use serde::Deserialize; use serde::Serialize; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SandboxState { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub permission_profile: Option, + pub permission_profile: PermissionProfile, pub codex_linux_sandbox_exe: Option, pub sandbox_cwd: PathUri, #[serde(default)] diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 56d6e678a0..0cb0c11a2a 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -744,7 +744,7 @@ async fn augment_mcp_tool_request_meta_with_sandbox_state( }; let permission_profile = turn_context.permission_profile(); let sandbox_state = serde_json::to_value(SandboxState { - permission_profile: Some(permission_profile), + permission_profile, codex_linux_sandbox_exe: turn_context.config.codex_linux_sandbox_exe.clone(), sandbox_cwd, use_legacy_landlock: turn_context.config.features.use_legacy_landlock(), diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 78fa73ce50..8000ed1c00 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -26,6 +26,7 @@ use codex_exec_server::Environment; use codex_exec_server::HttpRequestParams; use codex_login::CodexAuth; use codex_mcp::MCP_SANDBOX_STATE_META_CAPABILITY; +use codex_mcp::SandboxState; use codex_models_manager::manager::RefreshStrategy; use codex_utils_path_uri::LegacyAppPathString; @@ -933,13 +934,16 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()> let sandbox_meta = meta .get(MCP_SANDBOX_STATE_META_CAPABILITY) .expect("sandbox state metadata should be present"); - assert_eq!(sandbox_meta.get("sandboxPolicy"), None); - let expected_sandbox_cwd = PathUri::from_abs_path(&fixture.config.cwd).to_string(); + let sandbox_state: SandboxState = serde_json::from_value(sandbox_meta.clone())?; assert_eq!( - sandbox_meta.get("sandboxCwd").and_then(Value::as_str), - Some(expected_sandbox_cwd.as_str()) + sandbox_state, + SandboxState { + permission_profile: PermissionProfile::read_only(), + codex_linux_sandbox_exe: fixture.config.codex_linux_sandbox_exe.clone(), + sandbox_cwd: PathUri::from_abs_path(&fixture.config.cwd), + use_legacy_landlock: false, + } ); - assert_eq!(sandbox_meta.get("useLegacyLandlock"), Some(&json!(false))); server.verify().await; From 63f8f547c0b95800f3c61ee172a2a833b75faf3f Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 11:18:25 +0100 Subject: [PATCH 04/11] Stop persisting bridged log events (#29599) ## Why The 0.142.0 persistent-log filter disables target=log, but bridged log records are filtered using their original dependency target before tracing-log emits them as target=log. This allowed high-volume dependency TRACE events to keep reaching SQLite. This is a follow-up to #28224. ## What changed - Reject bridged target=log events inside the SQLite sink before formatting or queueing them. --- codex-rs/state/src/log_db.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 55de2a3077..2cf0f5d9af 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -199,6 +199,13 @@ where fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) { let metadata = event.metadata(); + // `tracing-log` checks filters with the original log target before + // dispatching an event whose tracing target is `log`, so the outer + // target filter cannot reliably reject these bridged events. + if metadata.target() == "log" { + return; + } + // The SDK emits DEBUG timer meta-events every second per process; these // were over 30% of retained logs in measured high-fanout Codex environments. if metadata.target() == "opentelemetry_sdk" From 55bc38a22bc6b75f51ca7d3a4bd3e634979af479 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 12:45:42 +0100 Subject: [PATCH 05/11] Fix Codex Apps auth elicitation hang (#29615) ## Summary - Require the reserved Codex Apps MCP server name to be present in the connection manager before treating it as host-owned. - Update auth elicitation tests to model an installed host-owned Codex Apps server without sending startup events to the test session. ## Why PR #29518 replaced the old host-owned flag with a name-only check. That made non-host-owned tests with the reserved codex_apps name enter auth elicitation and wait forever for a response. --- codex-rs/codex-mcp/src/connection_manager.rs | 2 +- .../codex-mcp/src/connection_manager_tests.rs | 35 +++++++++++++++++++ codex-rs/core/src/mcp_tool_call_tests.rs | 16 +++++++-- 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index 3057161117..53e9efc6d7 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -391,7 +391,7 @@ impl McpConnectionManager { } pub fn is_host_owned_codex_apps_server(&self, server_name: &str) -> bool { - server_name == CODEX_APPS_MCP_SERVER_NAME + server_name == CODEX_APPS_MCP_SERVER_NAME && self.server_metadata.contains_key(server_name) } pub fn set_approval_policy(&self, approval_policy: &Constrained) { diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index 4556973928..887a9b3d46 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -1177,6 +1177,41 @@ fn server_metadata_preserves_tool_approval_policy() { ); } +#[test] +fn host_owned_codex_apps_requires_server_metadata() { + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let permission_profile = Constrained::allow_any(PermissionProfile::default()); + let manager = McpConnectionManager::new_uninitialized( + &approval_policy, + &permission_profile, + /*prefix_mcp_tool_names*/ true, + ); + + assert!(!manager.is_host_owned_codex_apps_server(CODEX_APPS_MCP_SERVER_NAME)); +} + +#[test] +fn host_owned_codex_apps_matches_reserved_name_with_server_metadata() { + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let permission_profile = Constrained::allow_any(PermissionProfile::default()); + let mut manager = McpConnectionManager::new_uninitialized( + &approval_policy, + &permission_profile, + /*prefix_mcp_tool_names*/ true, + ); + let server = EffectiveMcpServer::configured(crate::codex_apps_mcp_server_config( + "https://chatgpt.com", + /*apps_mcp_product_sku*/ None, + )); + manager.server_metadata.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + McpServerMetadata::from(&server), + ); + + assert!(manager.is_host_owned_codex_apps_server(CODEX_APPS_MCP_SERVER_NAME)); + assert!(!manager.is_host_owned_codex_apps_server("docs")); +} + #[tokio::test] async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() { let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 2a951bfe55..f8b94de5aa 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1335,15 +1335,25 @@ fn codex_apps_auth_failure_metadata() -> McpToolApprovalMetadata { async fn install_host_owned_codex_apps_manager(session: &Session, turn_context: &TurnContext) { let auth = session.services.auth_manager.auth().await; + let startup_cancellation_token = CancellationToken::new(); + startup_cancellation_token.cancel(); + let (tx_event, _rx_event) = async_channel::unbounded(); + let mcp_servers = HashMap::from([( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + codex_mcp::EffectiveMcpServer::configured(codex_mcp::codex_apps_mcp_server_config( + "https://chatgpt.com", + /*apps_mcp_product_sku*/ None, + )), + )]); let manager = codex_mcp::McpConnectionManager::new( - &HashMap::new(), + &mcp_servers, turn_context.config.mcp_oauth_credentials_store_mode, turn_context.config.auth_keyring_backend_kind(), HashMap::new(), &turn_context.approval_policy, turn_context.sub_id.clone(), - session.get_tx_event(), - CancellationToken::new(), + tx_event, + startup_cancellation_token, turn_context.permission_profile(), codex_mcp::McpRuntimeContext::new( session.services.turn_environments.environment_manager(), From 49614a0391d83eec442ffeca1d4aa0fdeb119818 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 13:15:20 +0100 Subject: [PATCH 06/11] Namespace multi-agent v2 tools under collaboration (#29067) ## Summary Multi-agent v2 tools now use the fixed `collaboration` namespace when namespace tools are available. This keeps the model-visible hint and the actual tool surface aligned around `functions.collaboration.*`, without exposing an unshipped namespace knob to users. The PR also removes the old `features.multi_agent_v2.tool_namespace` config/schema surface, updates the MAv2 test fixtures for namespaced calls, and fixes stale `TurnContext.features` references that were breaking `codex-core` builds. ## Changes - Expose MAv2 tools under `collaboration` instead of relying on a configurable namespace. - Remove `tool_namespace` from MAv2 TOML config, resolved config, validation, schema, and tests. - Update tool-planning and integration fixtures to assert or emit namespaced MAv2 tool calls. - Read feature state through `TurnContext.config.features` in the multi-agent mode context paths. ## Testing - `just write-config-schema` - `just test -p codex-features` --- .../app-server/tests/suite/v2/turn_start.rs | 8 ++- codex-rs/core/src/config/mod.rs | 5 +- codex-rs/core/src/tools/spec_plan_tests.rs | 66 ++++++++++++++----- codex-rs/core/tests/suite/agent_execution.rs | 17 ++++- .../tests/suite/model_runtime_selectors.rs | 12 +++- codex-rs/core/tests/suite/pending_input.rs | 5 +- codex-rs/core/tests/suite/rollout_budget.rs | 11 +++- .../tests/suite/subagent_notifications.rs | 53 +++++++++++---- 8 files changed, 138 insertions(+), 39 deletions(-) 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 dd211a5d89..622e4284ef 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -100,6 +100,7 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const TEST_ORIGINATOR: &str = "codex_vscode"; const LOCAL_PRAGMATIC_TEMPLATE: &str = "You are a deeply pragmatic, effective software engineer."; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; const INVALID_REQUEST_ERROR_CODE: i64 = -32600; const TINY_PNG_BYTES: &[u8] = &[ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, @@ -3650,7 +3651,12 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> { |req: &wiremock::Request| body_contains(req, PARENT_PROMPT), responses::sse(vec![ responses::ev_response_created("resp-parent-1"), - responses::ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + responses::ev_function_call_with_namespace( + SPAWN_CALL_ID, + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &spawn_args, + ), responses::ev_completed("resp-parent-1"), ]), ) diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 953d0af1a1..81d2870c11 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -246,7 +246,8 @@ Payload: ``` You may also see them addressed as to=/root/..., which indicates your identity is /root/... "#; -const DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT: &str = r#"Note that collaboration tools cannot be called from inside `functions.exec`. Call `spawn_agent`, `send_message`, `followup_task`, `wait_agent`, `interrupt_agent`, and `list_agents` only as direct tool calls using the recipient shown in their tool definitions, such as `to=functions.spawn_agent` without a configured namespace or `to=functions.agents.spawn_agent` with `tool_namespace = "agents"`, since they are intentionally absent from the `functions.exec` `tools.*` namespace. Available tools in `functions.exec` are explicitly described with a `tools` namespace in the developer message. +const DEFAULT_MULTI_AGENT_V2_TOOL_NAMESPACE: &str = "collaboration"; +const DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT: &str = r#"Note that collaboration tools cannot be called from inside `functions.exec`. Call `spawn_agent`, `send_message`, `followup_task`, `wait_agent`, `interrupt_agent`, and `list_agents` only as direct tool calls using the recipient shown in their tool definitions, such as `to=functions.collaboration.spawn_agent`, since they are intentionally absent from the `functions.exec` `tools.*` namespace. Available tools in `functions.exec` are explicitly described with a `tools` namespace in the developer message. All agents share the same directory. In detail: - All agents have access to the same container and filesystem as you. @@ -1157,7 +1158,7 @@ impl MultiAgentV2Config { DEFAULT_MULTI_AGENT_V2_SUBAGENT_USAGE_HINT_TEXT, max_concurrent_threads_per_session, )), - tool_namespace: None, + tool_namespace: Some(DEFAULT_MULTI_AGENT_V2_TOOL_NAMESPACE.to_string()), hide_spawn_agent_metadata: true, non_code_mode_only: true, } diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index 5d70fb8f17..3fe33b141b 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -39,6 +39,8 @@ use crate::tools::router::ToolRouterParams; use crate::tools::router::ToolSuggestCandidates; use crate::tools::router::ToolSuggestPresentation; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; + #[derive(Default)] struct ToolPlanInputs { mcp_tools: Option>, @@ -1151,19 +1153,48 @@ async fn multi_agent_feature_selects_one_agent_tool_family() { }); }) .await; - v2.assert_visible_contains(&[ + v2.assert_visible_contains(&[MULTI_AGENT_V2_NAMESPACE]); + v2.assert_visible_lacks(&[ "spawn_agent", "send_message", "followup_task", "wait_agent", "interrupt_agent", "list_agents", + "send_input", + "resume_agent", + "assign_task", + "close_agent", ]); - v2.assert_visible_lacks(&["send_input", "resume_agent", "assign_task", "close_agent"]); - let spawn_agent_description = match v2.visible_spec("spawn_agent") { - ToolSpec::Function(tool) => tool.description.as_str(), - other => panic!("expected spawn_agent function spec, got {other:?}"), + for tool_name in [ + "spawn_agent", + "send_message", + "followup_task", + "wait_agent", + "interrupt_agent", + "list_agents", + ] { + assert!( + v2.namespace_function_names(MULTI_AGENT_V2_NAMESPACE) + .iter() + .any(|name| name == tool_name), + "expected {tool_name} in {MULTI_AGENT_V2_NAMESPACE} namespace" + ); + } + let ToolSpec::Namespace(namespace) = v2.visible_spec(MULTI_AGENT_V2_NAMESPACE) else { + panic!("expected {MULTI_AGENT_V2_NAMESPACE} namespace"); }; + let Some(ResponsesApiNamespaceTool::Function(spawn_agent)) = + namespace.tools.iter().find(|tool| { + matches!( + tool, + ResponsesApiNamespaceTool::Function(tool) if tool.name == "spawn_agent" + ) + }) + else { + panic!("expected spawn_agent in {MULTI_AGENT_V2_NAMESPACE} namespace"); + }; + let spawn_agent_description = spawn_agent.description.as_str(); assert!(!spawn_agent_description.contains("max_concurrent_threads_per_session")); assert!(spawn_agent_description.contains( "Note that passing `fork_turns=\"none\"` will not pass any surrounding context to the spawned subagent" @@ -1183,9 +1214,11 @@ async fn multi_agent_feature_selects_one_agent_tool_family() { }); }) .await; - direct_model_only.assert_visible_contains(&["spawn_agent", "send_message", "wait_agent"]); + direct_model_only.assert_visible_contains(&[MULTI_AGENT_V2_NAMESPACE]); + direct_model_only.assert_visible_lacks(&["spawn_agent", "send_message", "wait_agent"]); assert_eq!( - direct_model_only.exposure("spawn_agent"), + direct_model_only + .exposure(&ToolName::namespaced(MULTI_AGENT_V2_NAMESPACE, "spawn_agent").to_string()), ToolExposure::DirectModelOnly ); } @@ -1196,9 +1229,17 @@ async fn multi_agent_v2_message_schemas_are_encrypted() { set_feature(turn, Feature::MultiAgentV2, /*enabled*/ true); }) .await; + let ToolSpec::Namespace(namespace) = plan.visible_spec(MULTI_AGENT_V2_NAMESPACE) else { + panic!("expected {MULTI_AGENT_V2_NAMESPACE} namespace"); + }; for tool_name in ["spawn_agent", "send_message", "followup_task"] { - let ToolSpec::Function(tool) = plan.visible_spec(tool_name) else { - panic!("expected {tool_name} function spec"); + let Some(ResponsesApiNamespaceTool::Function(tool)) = namespace.tools.iter().find(|tool| { + matches!( + tool, + ResponsesApiNamespaceTool::Function(tool) if tool.name == tool_name + ) + }) else { + panic!("expected {tool_name} in {MULTI_AGENT_V2_NAMESPACE} namespace"); }; let properties = tool .parameters @@ -1464,12 +1505,7 @@ async fn hosted_tools_follow_provider_auth_model_and_config_gates() { codex_code_mode::WAIT_TOOL_NAME, "request_user_input", // Multi-agent v2 tools. - "spawn_agent", - "send_message", - "followup_task", - "wait_agent", - "interrupt_agent", - "list_agents", + MULTI_AGENT_V2_NAMESPACE, // Hosted Responses tools. "web_search", "image_generation", diff --git a/codex-rs/core/tests/suite/agent_execution.rs b/codex-rs/core/tests/suite/agent_execution.rs index f073d70089..69db20cc57 100644 --- a/codex-rs/core/tests/suite/agent_execution.rs +++ b/codex-rs/core/tests/suite/agent_execution.rs @@ -2,7 +2,7 @@ use anyhow::Result; use codex_features::Feature; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_function_call_with_namespace; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::sse; @@ -15,6 +15,7 @@ use std::time::Duration; const FIRST_PROMPT: &str = "spawn the first worker"; const FIRST_TASK: &str = "first worker task"; const SECOND_TASK: &str = "second worker task"; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; fn body_contains(request: &wiremock::Request, text: &str) -> bool { serde_json::from_slice::(&request.body) @@ -47,7 +48,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()> |request: &wiremock::Request| body_contains(request, FIRST_PROMPT), sse(vec![ ev_response_created("first-response"), - ev_function_call("first-call", "spawn_agent", &first_args), + ev_function_call_with_namespace( + "first-call", + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &first_args, + ), ev_completed("first-response"), ]), ) @@ -63,7 +69,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()> }, sse(vec![ ev_response_created("first-worker-response"), - ev_function_call("second-call", "spawn_agent", &second_args), + ev_function_call_with_namespace( + "second-call", + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &second_args, + ), ev_completed("first-worker-response"), ]), ) diff --git a/codex-rs/core/tests/suite/model_runtime_selectors.rs b/codex-rs/core/tests/suite/model_runtime_selectors.rs index d893e389d3..0c6a87605d 100644 --- a/codex-rs/core/tests/suite/model_runtime_selectors.rs +++ b/codex-rs/core/tests/suite/model_runtime_selectors.rs @@ -37,6 +37,7 @@ use tokio::time::sleep; const CHILD_MODEL: &str = "test-multi-agent-child"; const ROOT_MODEL: &str = "test-multi-agent-root"; const ROOT_PROMPT: &str = "spawn a child"; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; const UNSUPPORTED_CODE_MODE_WARNING: &str = "does not advertise Code Mode support"; struct RemoteModelResponse { @@ -335,7 +336,7 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> { .expect("test config should allow feature update"); }) .await?; - assert!(tool_names(&v2_body).contains(&"send_message".to_string())); + assert!(tool_names(&v2_body).contains(&MULTI_AGENT_V2_NAMESPACE.to_string())); let mut disabled_model = remote_model("test-multi-agent-disabled"); disabled_model.multi_agent_version = Some(MultiAgentVersion::Disabled); @@ -349,7 +350,12 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> { let disabled_tools = tool_names(&disabled_body); assert!(disabled_tools.iter().all(|name| !matches!( name.as_str(), - "multi_agent_v1" | "spawn_agent" | "send_message" | "wait_agent" | "list_agents" + "multi_agent_v1" + | MULTI_AGENT_V2_NAMESPACE + | "spawn_agent" + | "send_message" + | "wait_agent" + | "list_agents" ))); Ok(()) @@ -432,7 +438,7 @@ async fn remote_multi_agent_selector_uses_model_selected_before_first_turn() -> .expect("expected response request") .body_json(), ) - .contains(&"send_message".to_string()), + .contains(&MULTI_AGENT_V2_NAMESPACE.to_string()), ), (1, Some(MultiAgentVersion::V2), true) ); diff --git a/codex-rs/core/tests/suite/pending_input.rs b/codex-rs/core/tests/suite/pending_input.rs index 269beae638..17e00513fe 100644 --- a/codex-rs/core/tests/suite/pending_input.rs +++ b/codex-rs/core/tests/suite/pending_input.rs @@ -20,6 +20,7 @@ use core_test_support::responses; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_completed_with_tokens; use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_function_call_with_namespace; use core_test_support::responses::ev_message_item_added; use core_test_support::responses::ev_output_text_delta; use core_test_support::responses::ev_reasoning_item; @@ -290,11 +291,13 @@ async fn steer_interrupts_wait_agent_and_is_sent_in_follow_up_request() { const WAIT_CALL_ID: &str = "wait-call"; const INITIAL_PROMPT: &str = "wait for an agent"; const STEER_PROMPT: &str = "stop waiting and continue"; + const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; let first_chunks = vec![ chunk(ev_response_created("resp-1")), - chunk(ev_function_call( + chunk(ev_function_call_with_namespace( WAIT_CALL_ID, + MULTI_AGENT_V2_NAMESPACE, "wait_agent", r#"{"timeout_ms":10000}"#, )), diff --git a/codex-rs/core/tests/suite/rollout_budget.rs b/codex-rs/core/tests/suite/rollout_budget.rs index c051f01af2..6aa211bcc2 100644 --- a/codex-rs/core/tests/suite/rollout_budget.rs +++ b/codex-rs/core/tests/suite/rollout_budget.rs @@ -10,7 +10,7 @@ use core_test_support::responses::ResponsesRequest; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_completed_with_tokens; -use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_function_call_with_namespace; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::mount_sse_sequence; @@ -25,6 +25,8 @@ use std::time::Duration; use test_case::test_case; use tokio::time::timeout; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; + fn rollout_budget() -> RolloutBudgetConfig { RolloutBudgetConfig { limit_tokens: 100, @@ -130,7 +132,12 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> { |request: &wiremock::Request| wire_request_contains(request, ROOT_PROMPT), sse(vec![ ev_response_created("root-1"), - ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + ev_function_call_with_namespace( + SPAWN_CALL_ID, + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &spawn_args, + ), ev_completed_with_tokens("root-1", /*total_tokens*/ 10), ]), ) diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index c49e474965..53f9a97bc7 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -17,7 +17,6 @@ use core_test_support::hooks::trust_discovered_hooks; use core_test_support::responses::ResponsesRequest; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_function_call_with_namespace; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_tool_search_call; @@ -48,6 +47,7 @@ use wiremock::MockServer; const SPAWN_CALL_ID: &str = "spawn-call-1"; const MULTI_AGENT_V1_NAMESPACE: &str = "multi_agent_v1"; +const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration"; const TURN_0_FORK_PROMPT: &str = "seed fork context"; const TURN_1_PROMPT: &str = "spawn a child and continue"; const TURN_2_NO_WAIT_PROMPT: &str = "follow up without wait"; @@ -63,6 +63,23 @@ const SUBAGENT_STOP_CONTINUATION: &str = "continue only the child"; const INTERNAL_SUBAGENT_PROMPT: &str = "internal subagent: review"; fn body_contains(req: &wiremock::Request, text: &str) -> bool { + decoded_body(req) + .and_then(|body| String::from_utf8(body).ok()) + .is_some_and(|body| body.contains(text)) +} + +fn request_has_input_type(req: &wiremock::Request, ty: &str) -> bool { + decoded_body(req) + .and_then(|body| serde_json::from_slice::(&body).ok()) + .and_then(|body| body.get("input").and_then(Value::as_array).cloned()) + .is_some_and(|items| { + items + .iter() + .any(|item| item.get("type").and_then(Value::as_str) == Some(ty)) + }) +} + +fn decoded_body(req: &wiremock::Request) -> Option> { let is_zstd = req .headers .get("content-encoding") @@ -72,14 +89,11 @@ fn body_contains(req: &wiremock::Request, text: &str) -> bool { .split(',') .any(|entry| entry.trim().eq_ignore_ascii_case("zstd")) }); - let bytes = if is_zstd { + if is_zstd { zstd::stream::decode_all(std::io::Cursor::new(&req.body)).ok() } else { Some(req.body.clone()) - }; - bytes - .and_then(|body| String::from_utf8(body).ok()) - .is_some_and(|body| body.contains(text)) + } } fn has_subagent_notification(req: &ResponsesRequest) -> bool { @@ -1040,14 +1054,19 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result |req: &wiremock::Request| body_contains(req, TURN_1_PROMPT), sse(vec![ ev_response_created("resp-parent-1"), - ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + ev_function_call_with_namespace( + SPAWN_CALL_ID, + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &spawn_args, + ), ev_completed("resp-parent-1"), ]), ) .await; let child_request_log = mount_sse_once_match( &server, - |req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""), + |req: &wiremock::Request| request_has_input_type(req, "agent_message"), sse(vec![ ev_response_created("resp-child-1"), ev_completed("resp-child-1"), @@ -1057,7 +1076,7 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result mount_sse_once_match( &server, |req: &wiremock::Request| { - body_contains(req, SPAWN_CALL_ID) && !body_contains(req, "\"type\":\"agent_message\"") + body_contains(req, SPAWN_CALL_ID) && !request_has_input_type(req, "agent_message") }, sse(vec![ ev_response_created("resp-parent-2"), @@ -1129,7 +1148,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message( |req: &wiremock::Request| body_contains(req, TURN_1_PROMPT), sse(vec![ ev_response_created("resp-parent-1"), - ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + ev_function_call_with_namespace( + SPAWN_CALL_ID, + MULTI_AGENT_V2_NAMESPACE, + "spawn_agent", + &spawn_args, + ), ev_completed("resp-parent-1"), ]), ) @@ -1144,7 +1168,7 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message( }; let child_request = mount_response_once_match( &server, - |req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""), + |req: &wiremock::Request| request_has_input_type(req, "agent_message"), sse_response(sse(child_events)).set_delay(Duration::from_secs(1)), ) .await; @@ -1183,7 +1207,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message( }, sse(vec![ ev_response_created("resp-parent-3"), - ev_function_call("wait-agent-call", "wait_agent", "{}"), + ev_function_call_with_namespace( + "wait-agent-call", + MULTI_AGENT_V2_NAMESPACE, + "wait_agent", + "{}", + ), ev_completed("resp-parent-3"), ]), ) From 414782450952a196bbb64b1605a458c2531c47b6 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 14:59:39 +0100 Subject: [PATCH 07/11] path-uri: add lexical containment (#29614) ## Why Executor-owned paths must stay portable while the orchestrator reasons about them. Converting a Windows or remote path to the orchestrator host's native path just to check containment breaks that boundary. ## What changed - Add lexical containment to `PathUri`. - Compare URI authorities and complete path segments, so `plugin-other` is not treated as a child of `plugin`. - Fail closed for encoded path separators and opaque fallback URIs. For example: ```text file:///C:/plugins/foo/assets/icon.svg is below file:///C:/plugins/foo file:///C:/plugins/foo2/icon.svg is not below file:///C:/plugins/foo ``` This is the shared foundation for keeping executor-owned plugin resources URI-native without consulting the orchestrator filesystem. --- codex-rs/utils/path-uri/src/lib.rs | 40 +++++++++++++++++++ codex-rs/utils/path-uri/src/tests.rs | 59 ++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/codex-rs/utils/path-uri/src/lib.rs b/codex-rs/utils/path-uri/src/lib.rs index 6c92c5e1df..9794e7c709 100644 --- a/codex-rs/utils/path-uri/src/lib.rs +++ b/codex-rs/utils/path-uri/src/lib.rs @@ -247,6 +247,33 @@ impl PathUri { std::iter::successors(Some(self.clone()), Self::parent) } + /// Returns true when this URI is lexically equal to or below `base`. + /// + /// Containment is computed using URI authority and path-segment boundaries, + /// without consulting the host filesystem. Percent-encoded path separators + /// fail closed because native path conversion may interpret them as segment + /// boundaries. Opaque fallback URIs created by [`Self::from_abs_path`] only + /// contain themselves. + pub fn starts_with(&self, base: &Self) -> bool { + if self == base { + return true; + } + if decode_bad_path_uri(&self.0).is_some() || decode_bad_path_uri(&base.0).is_some() { + return false; + } + if self.0.host_str() != base.0.host_str() { + return false; + } + + let Some(path_segments) = containment_path_segments(&self.0) else { + return false; + }; + let Some(base_segments) = containment_path_segments(&base.0) else { + return false; + }; + path_segments.starts_with(&base_segments) + } + /// Lexically resolves native absolute or relative path text against this URI. /// /// Path text is interpreted using the POSIX or Windows convention inferred @@ -542,6 +569,19 @@ fn is_windows_drive_uri_segment(segment: &str) -> bool { matches!(segment.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic()) } +fn containment_path_segments(url: &Url) -> Option> { + let segments = url + .path_segments()? + .filter(|segment| !segment.is_empty()) + .collect::>(); + (!segments.iter().any(|segment| { + urlencoding::decode_binary(segment.as_bytes()) + .iter() + .any(|byte| matches!(*byte, b'/' | b'\\')) + })) + .then_some(segments) +} + fn infer_opaque_path_convention(path_bytes: &[u8]) -> Option { if path_bytes.starts_with(b"/") { return Some(PathConvention::Posix); diff --git a/codex-rs/utils/path-uri/src/tests.rs b/codex-rs/utils/path-uri/src/tests.rs index 0e45baaa12..c52c3f9e6a 100644 --- a/codex-rs/utils/path-uri/src/tests.rs +++ b/codex-rs/utils/path-uri/src/tests.rs @@ -283,9 +283,16 @@ fn structurally_valid_bad_path_uri_with_invalid_native_payload_fails_conversion( fn bad_path_uris_are_opaque_to_lexical_operations() { let uri = PathUri::parse("file:///%00/bad/path/YQ") .expect("canonical base64 fallback URI should parse"); + let other = PathUri::parse("file:///%00/bad/path/Yg") + .expect("canonical base64 fallback URI should parse"); + let root = PathUri::parse("file:///").expect("valid root URI"); assert_eq!(uri.basename(), None); assert_eq!(uri.parent(), None); + assert!(uri.starts_with(&uri)); + assert!(!uri.starts_with(&root)); + assert!(!uri.starts_with(&other)); + assert!(!other.starts_with(&uri)); assert_eq!(uri.join(""), Ok(uri.clone())); assert_eq!( uri.join("child"), @@ -698,6 +705,58 @@ fn join_uses_the_base_uri_path_convention() { } } +#[test] +fn starts_with_uses_uri_segment_boundaries() { + for (path, base, expected) in [ + ("file:///workspace/plugin", "file:///", true), + ("file:///workspace/plugin", "file:///workspace/plugin", true), + ( + "file:///workspace/plugin/assets/icon.svg", + "file:///workspace/plugin", + true, + ), + ( + "file:///workspace/plugin-other/icon.svg", + "file:///workspace/plugin", + false, + ), + ( + "file:///C:/plugins/foo/assets/icon.svg", + "file:///C:/plugins/foo", + true, + ), + ( + "file:///C:/plugins/foo2/assets/icon.svg", + "file:///C:/plugins/foo", + false, + ), + ( + "file://server/share/plugins/foo/icon.svg", + "file://server/share/plugins/foo", + true, + ), + ( + "file://other/share/plugins/foo/icon.svg", + "file://server/share/plugins/foo", + false, + ), + ( + "file:///workspace/plugin/%2F..%2Foutside", + "file:///workspace/plugin", + false, + ), + ( + "file:///workspace/plugin/%5C..%5Coutside", + "file:///workspace/plugin", + false, + ), + ] { + let path = PathUri::parse(path).expect("valid path URI"); + let base = PathUri::parse(base).expect("valid base URI"); + assert_eq!(path.starts_with(&base), expected); + } +} + #[test] fn to_url_returns_the_validated_url() { let uri = PathUri::parse("file://localhost/workspace/a%20file.rs").expect("valid file URI"); From 330ae6a516009e127db01843f5049497d3c46805 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Tue, 23 Jun 2026 10:23:25 -0400 Subject: [PATCH 08/11] Share resumed rollout history (#28426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Resuming a persisted thread currently deep-clones its complete rollout history several times. `InitialHistory` is retained for the app-server response, copied into thread persistence, and copied again by read-only accessors. These copies scale with the complete rollout rather than the bounded model context and add measurable latency for large sessions. This change stores resumed rollout history in `Arc>`. Rollout loading wraps the parsed vector once, while app-server response construction, session initialization, and thread persistence share it through inexpensive `Arc` clones. Read-only history access now returns a borrowed slice, and fork paths use `Arc::unwrap_or_clone` where they genuinely need mutable ownership. Rollout reconstruction also consumes its temporary context instead of cloning the reconstructed model history. The serialized representation remains unchanged. In an artificial 123 MB rollout benchmark, sharing resumed history reduced cold resume latency by roughly 9–10%. The affected crates compile with their test targets, all 80 thread-store tests pass, and the Bazel dependency lock remains valid. --- codex-rs/Cargo.toml | 2 +- .../request_processors/thread_processor.rs | 40 +++++++++---------- .../src/request_processors/turn_processor.rs | 2 +- codex-rs/core/src/agent/control/spawn.rs | 4 +- .../src/session/rollout_reconstruction.rs | 2 +- .../session/rollout_reconstruction_tests.rs | 28 +++++++------ codex-rs/core/src/session/tests.rs | 22 +++++----- codex-rs/core/src/thread_manager.rs | 21 +++++----- codex-rs/core/src/thread_manager_tests.rs | 14 +++---- codex-rs/core/tests/suite/fork_thread.rs | 4 +- codex-rs/core/tests/suite/resume_warning.rs | 6 ++- codex-rs/protocol/src/protocol.rs | 11 ++--- codex-rs/rollout/src/recorder.rs | 2 +- codex-rs/thread-store/src/in_memory.rs | 4 +- codex-rs/thread-store/src/live_thread.rs | 8 ++-- .../thread-store/src/thread_metadata_sync.rs | 14 +++++-- codex-rs/thread-store/src/types.rs | 3 +- 17 files changed, 102 insertions(+), 85 deletions(-) diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 9591f78afa..3290c4ea99 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -380,7 +380,7 @@ schemars = "0.8.22" seccompiler = "0.5.0" semver = "1.0" sentry = "0.46.0" -serde = "1" +serde = { version = "1", features = ["rc"] } serde_ignored = "0.1.14" serde_json = "1" serde_path_to_error = "0.1.20" diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index a3e4b49ce8..a59bb530d1 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -2604,8 +2604,8 @@ impl ThreadRequestProcessor { self.resume_thread_from_history(history.as_slice()) .await .map(|thread_history| (thread_history, None)) - } else if let Some(stored_thread) = stored_thread_from_running_probe { - self.stored_thread_to_initial_history(&stored_thread) + } else if let Some(mut stored_thread) = stored_thread_from_running_probe { + self.stored_thread_to_initial_history(&mut stored_thread) .await .map(|thread_history| (thread_history, Some(*stored_thread))) } else { @@ -2758,7 +2758,7 @@ impl ThreadRequestProcessor { let token_usage_thread = include_turns.then(|| thread.clone()); let mut initial_turns_page = if let Some(params) = initial_turns_page.as_ref() { match build_thread_resume_initial_turns_page( - &response_history.get_rollout_items(), + response_history.get_rollout_items(), thread.status.clone(), /*has_live_running_thread*/ false, /*active_turn*/ None, @@ -2803,7 +2803,7 @@ impl ThreadRequestProcessor { // rebuilding history only to attribute a replayed usage update. if let Some(token_usage_thread) = token_usage_thread { let token_usage_turn_id = latest_token_usage_turn_id_from_rollout_items( - &response_history.get_rollout_items(), + response_history.get_rollout_items(), token_usage_thread.turns.as_slice(), ); // The client needs restored usage before it starts another turn. @@ -2901,7 +2901,7 @@ impl ThreadRequestProcessor { } }; - if let Some((existing_thread_id, existing_thread, source_thread)) = running_thread { + if let Some((existing_thread_id, existing_thread, mut source_thread)) = running_thread { let existing_thread_rollout_path = existing_thread.rollout_path(); let active_path = existing_thread_rollout_path .as_ref() @@ -2963,8 +2963,8 @@ impl ThreadRequestProcessor { should_redact_thread_resume_payloads(app_server_client_name.as_deref()); let history_items = source_thread .history - .as_ref() - .map(|history| history.items.clone()) + .take() + .map(|history| history.items) .ok_or_else(|| { internal_error(format!( "thread {existing_thread_id} did not include persisted history" @@ -2988,10 +2988,8 @@ impl ThreadRequestProcessor { ) .await?; - let mut summary_source_thread = source_thread; - summary_source_thread.history = None; let mut thread_summary = self.stored_thread_to_api_thread( - summary_source_thread, + source_thread, config_snapshot.model_provider_id.as_str(), /*include_turns*/ false, ); @@ -3060,11 +3058,11 @@ impl ThreadRequestProcessor { thread_id: &str, path: Option<&PathBuf>, ) -> Result<(InitialHistory, StoredThread), JSONRPCErrorError> { - let stored_thread = self + let mut stored_thread = self .read_stored_thread_for_resume(thread_id, path, /*include_history*/ true) .await?; let history = self - .stored_thread_to_initial_history(&stored_thread) + .stored_thread_to_initial_history(&mut stored_thread) .await?; Ok((history, stored_thread)) } @@ -3112,13 +3110,13 @@ impl ThreadRequestProcessor { #[tracing::instrument(level = "trace", skip_all)] async fn stored_thread_to_initial_history( &self, - stored_thread: &StoredThread, + stored_thread: &mut StoredThread, ) -> Result { let thread_id = stored_thread.thread_id; let history = stored_thread .history - .as_ref() - .map(|history| history.items.clone()) + .take() + .map(|history| history.items) .ok_or_else(|| { internal_error(format!( "thread {thread_id} did not include persisted history" @@ -3126,7 +3124,7 @@ impl ThreadRequestProcessor { })?; Ok(InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history, + history: Arc::new(history), rollout_path: stored_thread.rollout_path.clone(), })) } @@ -3255,7 +3253,7 @@ impl ThreadRequestProcessor { let history_items = thread_history.get_rollout_items(); populate_thread_turns_from_history( &mut thread, - &history_items, + history_items, /*active_turn*/ None, ); } @@ -3313,7 +3311,7 @@ impl ThreadRequestProcessor { "`permissions` cannot be combined with `sandbox`", )); } - let source_thread = self + let mut source_thread = self .read_stored_thread_for_resume(&thread_id, path.as_ref(), /*include_history*/ true) .await?; let source_thread_id = source_thread.thread_id; @@ -3323,8 +3321,8 @@ impl ThreadRequestProcessor { .and_then(codex_core::util::normalize_thread_name); let history_items = source_thread .history - .as_ref() - .map(|history| history.items.clone()) + .take() + .map(|history| Arc::new(history.items)) .ok_or_else(|| { internal_error(format!( "thread {source_thread_id} did not include persisted history" @@ -3391,7 +3389,7 @@ impl ThreadRequestProcessor { config, InitialHistory::Resumed(ResumedHistory { conversation_id: source_thread_id, - history: history_items.clone(), + history: Arc::clone(&history_items), rollout_path: source_thread.rollout_path.clone(), }), thread_source.map(Into::into), diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index 4b6e0fda3a..e0d79a0c3b 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -1237,7 +1237,7 @@ impl TurnRequestProcessor { config.clone(), InitialHistory::Resumed(ResumedHistory { conversation_id: parent_thread_id, - history: parent_history.items, + history: Arc::new(parent_history.items), rollout_path: parent_thread.rollout_path(), }), /*thread_source*/ None, diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 37a3a8105e..e208b418d3 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -143,7 +143,7 @@ impl AgentControl { .items; let initial_history = InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history, + history: Arc::new(history), rollout_path: stored_thread.rollout_path, }); if initial_history.get_multi_agent_version() != Some(MultiAgentVersion::V2) { @@ -626,7 +626,7 @@ impl AgentControl { .items; let initial_history = InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history, + history: Arc::new(history), rollout_path: stored_thread.rollout_path, }); let parent_thread_id = stored_thread.parent_thread_id; diff --git a/codex-rs/core/src/session/rollout_reconstruction.rs b/codex-rs/core/src/session/rollout_reconstruction.rs index bf534c1e8a..6989ff80d0 100644 --- a/codex-rs/core/src/session/rollout_reconstruction.rs +++ b/codex-rs/core/src/session/rollout_reconstruction.rs @@ -355,7 +355,7 @@ impl Session { id: None, }); RolloutReconstruction { - history: history.raw_items().to_vec(), + history: history.into_raw_items(), previous_turn_settings, reference_context_item, window_number: window.number, diff --git a/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/codex-rs/core/src/session/rollout_reconstruction_tests.rs index b28bd37c79..828c078586 100644 --- a/codex-rs/core/src/session/rollout_reconstruction_tests.rs +++ b/codex-rs/core/src/session/rollout_reconstruction_tests.rs @@ -69,7 +69,9 @@ async fn record_initial_history_reconstructs_typed_inter_agent_message() { session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: vec![RolloutItem::InterAgentCommunication(communication.clone())], + history: Arc::new(vec![RolloutItem::InterAgentCommunication( + communication.clone(), + )]), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -112,7 +114,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -189,7 +191,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -757,7 +759,7 @@ async fn record_initial_history_resumed_rollback_skips_only_user_turns() { session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -841,7 +843,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -871,7 +873,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_seed_referenc session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -898,7 +900,7 @@ async fn record_initial_history_resumed_does_not_seed_reference_context_item_aft session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1070,7 +1072,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1215,7 +1217,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1338,7 +1340,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1454,7 +1456,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1505,7 +1507,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_ session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1633,7 +1635,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 52bde2cc4a..a76cacabf2 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1697,7 +1697,7 @@ async fn record_initial_history_reconstructs_resumed_transcript() { session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1862,7 +1862,7 @@ async fn prepares_resumed_history_before_installing_it() { session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: vec![RolloutItem::ResponseItem(resumed_item)], + history: Arc::new(vec![RolloutItem::ResponseItem(resumed_item)]), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -1905,7 +1905,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() { resolve_multi_agent_version( &InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: Vec::new(), + history: Arc::new(Vec::new()), rollout_path: None, }), /*inherited_multi_agent_version*/ None, @@ -1916,7 +1916,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() { resolve_multi_agent_version( &InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: Vec::new(), + history: Arc::new(Vec::new()), rollout_path: None, }), Some(MultiAgentVersion::V2), @@ -1927,10 +1927,10 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() { resolve_multi_agent_version( &InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: vec![session_meta_item( + history: Arc::new(vec![session_meta_item( thread_id, Some(MultiAgentVersion::Disabled) - )], + )]), rollout_path: None, }), Some(MultiAgentVersion::V2), @@ -1991,7 +1991,7 @@ async fn resumed_history_injects_initial_context_on_first_context_update_only() session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -2085,7 +2085,7 @@ async fn record_initial_history_seeds_token_info_from_rollout() { session .record_initial_history(InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: rollout_items, + history: Arc::new(rollout_items), rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")), })) .await; @@ -5508,7 +5508,7 @@ async fn resumed_root_session_uses_thread_id_as_session_id() { let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx( InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: Vec::new(), + history: Arc::new(Vec::new()), rollout_path: None, }), SessionSource::Exec, @@ -5543,7 +5543,7 @@ async fn resumed_subagent_session_restores_persisted_session_id() { let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx( InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: vec![RolloutItem::SessionMeta(SessionMetaLine { + history: Arc::new(vec![RolloutItem::SessionMeta(SessionMetaLine { meta: SessionMeta { session_id: parent_session_id, id: thread_id, @@ -5551,7 +5551,7 @@ async fn resumed_subagent_session_restores_persisted_session_id() { ..SessionMeta::default() }, git: None, - })], + })]), rollout_path: None, }), session_source, diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index deba2864b6..816df89c39 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -1602,7 +1602,7 @@ fn stored_thread_to_initial_history( })?; Ok(InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, - history: history.items, + history: Arc::new(history.items), rollout_path: rollout_path.or(stored_thread.rollout_path), })) } @@ -1639,7 +1639,7 @@ fn truncate_before_nth_user_message( n: usize, snapshot_state: &SnapshotTurnState, ) -> InitialHistory { - let items: Vec = history.get_rollout_items(); + let items = history.get_rollout_items().to_vec(); let user_positions = truncation::user_message_positions_in_rollout(&items); let rolled = if snapshot_state.ends_mid_turn && n >= user_positions.len() { if let Some(cut_idx) = snapshot_state @@ -1671,7 +1671,7 @@ struct SnapshotTurnState { fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState { let rollout_items = history.get_rollout_items(); let mut builder = ThreadHistoryBuilder::new(); - for item in &rollout_items { + for item in rollout_items { builder.handle_rollout_item(item); } let active_turn_id = builder.active_turn_id_if_explicit(); @@ -1695,7 +1695,7 @@ fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState { }; } - let Some(last_user_position) = truncation::user_message_positions_in_rollout(&rollout_items) + let Some(last_user_position) = truncation::user_message_positions_in_rollout(rollout_items) .last() .copied() else { @@ -1736,7 +1736,9 @@ fn fork_history_from_snapshot( InitialHistory::New => InitialHistory::New, InitialHistory::Cleared => InitialHistory::Cleared, InitialHistory::Forked(history) => InitialHistory::Forked(history), - InitialHistory::Resumed(resumed) => InitialHistory::Forked(resumed.history), + InitialHistory::Resumed(resumed) => { + InitialHistory::Forked(Arc::unwrap_or_clone(resumed.history)) + } }; if snapshot_state.ends_mid_turn { append_interrupted_boundary( @@ -1782,12 +1784,13 @@ fn append_interrupted_boundary( history.push(aborted_event); InitialHistory::Forked(history) } - InitialHistory::Resumed(mut resumed) => { + InitialHistory::Resumed(resumed) => { + let mut history = Arc::unwrap_or_clone(resumed.history); if let Some(marker) = interrupted_turn_history_marker(interrupted_marker) { - resumed.history.push(RolloutItem::ResponseItem(marker)); + history.push(RolloutItem::ResponseItem(marker)); } - resumed.history.push(aborted_event); - InitialHistory::Forked(resumed.history) + history.push(aborted_event); + InitialHistory::Forked(history) } } } diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index afb103b883..6375bd914c 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -116,7 +116,7 @@ fn truncates_before_requested_user_message() { RolloutItem::ResponseItem(items[2].clone()), ]; assert_eq!( - serde_json::to_value(&got_items).unwrap(), + serde_json::to_value(got_items).unwrap(), serde_json::to_value(&expected_items).unwrap() ); @@ -256,7 +256,7 @@ async fn ignores_session_prefix_messages_when_truncating() { ]; assert_eq!( - serde_json::to_value(&got_items).unwrap(), + serde_json::to_value(got_items).unwrap(), serde_json::to_value(&expected).unwrap() ); } @@ -963,7 +963,7 @@ async fn rollout_path_resume_and_fork_read_history_through_thread_store() { config.clone(), InitialHistory::Resumed(ResumedHistory { conversation_id: source.thread_id, - history: vec![RolloutItem::ResponseItem(user_msg("hello"))], + history: Arc::new(vec![RolloutItem::ResponseItem(user_msg("hello"))]), rollout_path: Some(rollout_path.clone()), }), auth_manager.clone(), @@ -1315,7 +1315,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor assert!(!snapshot_turn_state(&history).ends_mid_turn); let rollout_items: Vec<_> = history .get_rollout_items() - .into_iter() + .iter() .filter(|item| !matches!(item, RolloutItem::SessionMeta(_))) .collect(); let interrupted_marker_json = serde_json::to_value(RolloutItem::ResponseItem( @@ -1435,7 +1435,7 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { .expect("read forked rollout history"); let rollout_items: Vec<_> = history .get_rollout_items() - .into_iter() + .iter() .filter(|item| !matches!(item, RolloutItem::SessionMeta(_))) .collect(); @@ -1522,7 +1522,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ let forked_rollout_items: Vec<_> = history .get_rollout_items() - .into_iter() + .iter() .filter(|item| !matches!(item, RolloutItem::SessionMeta(_))) .collect(); let interrupted_marker_json = serde_json::to_value(RolloutItem::ResponseItem( @@ -1560,7 +1560,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ .expect("read re-forked rollout history"); let reforked_rollout_items: Vec<_> = reforked_history .get_rollout_items() - .into_iter() + .iter() .filter(|item| !matches!(item, RolloutItem::SessionMeta(_))) .collect(); diff --git a/codex-rs/core/tests/suite/fork_thread.rs b/codex-rs/core/tests/suite/fork_thread.rs index d51ba7d2f6..cc1d4e9177 100644 --- a/codex-rs/core/tests/suite/fork_thread.rs +++ b/codex-rs/core/tests/suite/fork_thread.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use codex_core::ForkSnapshot; use codex_core::NewThread; use codex_core::parse_turn_item; @@ -196,7 +198,7 @@ async fn fork_thread_from_history_does_not_require_source_rollout_path() { test.config.clone(), InitialHistory::Resumed(ResumedHistory { conversation_id: test.session_configured.thread_id, - history: source_items.clone(), + history: Arc::new(source_items.clone()), rollout_path: None, }), /*thread_source*/ None, diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 073e6d8b49..50395b2ecb 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -1,5 +1,7 @@ #![allow(clippy::unwrap_used)] +use std::sync::Arc; + use codex_core::NewThread; use codex_login::CodexAuth; use codex_protocol::ThreadId; @@ -51,7 +53,7 @@ fn resume_history( InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: vec![ + history: Arc::new(vec![ RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { turn_id: turn_id.clone(), trace_id: None, @@ -75,7 +77,7 @@ fn resume_history( duration_ms: None, time_to_first_token_ms: None, })), - ], + ]), rollout_path: Some(rollout_path.to_path_buf()), }) } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index e1fe605462..8a678281d2 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -10,6 +10,7 @@ use std::ops::Mul; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; +use std::sync::Arc; use std::time::Duration; use strum_macros::EnumIter; @@ -2460,7 +2461,7 @@ pub struct ConversationPathResponseEvent { #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ResumedHistory { pub conversation_id: ThreadId, - pub history: Vec, + pub history: Arc>, pub rollout_path: Option, } @@ -2505,11 +2506,11 @@ impl InitialHistory { } } - pub fn get_rollout_items(&self) -> Vec { + pub fn get_rollout_items(&self) -> &[RolloutItem] { match self { - InitialHistory::New | InitialHistory::Cleared => Vec::new(), - InitialHistory::Resumed(resumed) => resumed.history.clone(), - InitialHistory::Forked(items) => items.clone(), + InitialHistory::New | InitialHistory::Cleared => &[], + InitialHistory::Resumed(resumed) => &resumed.history, + InitialHistory::Forked(items) => items, } } diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index 084acb0d73..3229f5450a 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -947,7 +947,7 @@ impl RolloutRecorder { info!("Resumed rollout successfully from {path:?}"); Ok(InitialHistory::Resumed(ResumedHistory { conversation_id, - history: items, + history: Arc::new(items), rollout_path: Some(compression::plain_rollout_path(path)), })) } diff --git a/codex-rs/thread-store/src/in_memory.rs b/codex-rs/thread-store/src/in_memory.rs index a93e3644c0..84e0484f78 100644 --- a/codex-rs/thread-store/src/in_memory.rs +++ b/codex-rs/thread-store/src/in_memory.rs @@ -266,7 +266,9 @@ impl InMemoryThreadStore { let mut state = self.state.lock().await; state.calls.resume_thread += 1; if let Some(history) = params.history { - state.histories.insert(params.thread_id, history); + state + .histories + .insert(params.thread_id, Arc::unwrap_or_clone(history)); } else { state.histories.entry(params.thread_id).or_default(); } diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index 6b94807511..da3d092da5 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -100,12 +100,13 @@ impl LiveThread { pub async fn resume( thread_store: Arc, - mut params: ResumeThreadParams, + params: ResumeThreadParams, ) -> ThreadStoreResult { let thread_id = params.thread_id; let should_load_history = params.history.is_none(); let include_archived = params.include_archived; - thread_store.resume_thread(params.clone()).await?; + let mut metadata_sync = ThreadMetadataSync::for_resume(¶ms); + thread_store.resume_thread(params).await?; if should_load_history { match thread_store .load_history(LoadThreadHistoryParams { @@ -114,7 +115,7 @@ impl LiveThread { }) .await { - Ok(history) => params.history = Some(history.items), + Ok(history) => metadata_sync.record_resume_history(&history.items), Err(err) => { if let Err(discard_err) = thread_store.discard_thread(thread_id).await { warn!( @@ -125,7 +126,6 @@ impl LiveThread { } } } - let metadata_sync = ThreadMetadataSync::for_resume(¶ms); Ok(Self { thread_id, thread_store, diff --git a/codex-rs/thread-store/src/thread_metadata_sync.rs b/codex-rs/thread-store/src/thread_metadata_sync.rs index 7940f1c80f..852f679126 100644 --- a/codex-rs/thread-store/src/thread_metadata_sync.rs +++ b/codex-rs/thread-store/src/thread_metadata_sync.rs @@ -1,3 +1,5 @@ +#[cfg(test)] +use std::sync::Arc; use std::time::Duration; use std::time::Instant; @@ -108,13 +110,17 @@ impl ThreadMetadataSync { defer_resume_update_until_append: false, }; if let Some(history) = params.history.as_deref() { - let update = sync.observe_resume_history(history); - sync.merge_pending_update(update); - sync.defer_resume_update_until_append = sync.pending_update.is_some(); + sync.record_resume_history(history); } sync } + pub(crate) fn record_resume_history(&mut self, history: &[RolloutItem]) { + let update = self.observe_resume_history(history); + self.merge_pending_update(update); + self.defer_resume_update_until_append = self.pending_update.is_some(); + } + pub(crate) fn take_pending_update(&self) -> Option { self.pending_update .clone() @@ -555,7 +561,7 @@ mod tests { ResumeThreadParams { thread_id, rollout_path: None, - history: Some(history), + history: Some(Arc::new(history)), include_archived: false, metadata: ThreadPersistenceMetadata { cwd: None, diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index 74412bb9cd..2a82e42511 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; +use std::sync::Arc; use chrono::DateTime; use chrono::Utc; @@ -96,7 +97,7 @@ pub struct ResumeThreadParams { /// Known local rollout path when the caller resumed from a specific file. pub rollout_path: Option, /// Known replay history for the resumed thread, if already loaded by the caller. - pub history: Option>, + pub history: Option>>, /// Whether archived threads may be reopened. pub include_archived: bool, /// Metadata for future writes appended to the resumed live thread. From bbe100689073815876d330e56a200217a96a9e35 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 15:25:28 +0100 Subject: [PATCH 09/11] Update rmcp to 1.8.0 (#29634) ## Summary - Update `rmcp` and `rmcp-macros` from 1.7.0 to 1.8.0. - Adapt to the new shared `peer_info` return type. - Box OAuth status discovery at the MCP boundary to keep the expanded future type from overflowing Rust's trait recursion limit. This brings in custom OAuth HTTP client support from [modelcontextprotocol/rust-sdk#908](https://github.com/modelcontextprotocol/rust-sdk/pull/908). --- MODULE.bazel.lock | 4 ++-- codex-rs/Cargo.lock | 12 ++++++------ codex-rs/Cargo.toml | 2 +- codex-rs/codex-mcp/src/mcp/auth.rs | 2 ++ codex-rs/rmcp-client/src/rmcp_client.rs | 2 +- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 7cc8d83419..8ae5bef17c 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1449,8 +1449,8 @@ "resolv-conf_0.7.6": "{\"dependencies\":[],\"features\":{\"system\":[]}}", "rfc6979_0.4.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"reset\"],\"name\":\"hmac\",\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"}],\"features\":{}}", "ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}", - "rmcp-macros_1.7.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"local\":[]}}", - "rmcp_1.7.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"http1\",\"tokio\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"default_features\":false,\"features\":[\"serde\",\"now\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"name\":\"hyper\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"server\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"jsonwebtoken\",\"optional\":true,\"req\":\"^10\"},{\"default_features\":false,\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.13.2\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^1.7.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"which\",\"optional\":true,\"req\":\"^8\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"auth-client-credentials-jwt\":[\"auth\",\"dep:jsonwebtoken\",\"uuid\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"local\":[\"rmcp-macros?/local\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-client-unix-socket\":[\"transport-streamable-http-client\",\"dep:hyper\",\"dep:hyper-util\",\"dep:http-body-util\",\"dep:http\",\"dep:bytes\",\"tokio/net\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"],\"which-command\":[\"transport-child-process\",\"dep:which\"]}}", + "rmcp-macros_1.8.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"local\":[]}}", + "rmcp_1.8.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"http1\",\"tokio\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"default_features\":false,\"features\":[\"serde\",\"now\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"name\":\"hyper\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"server\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"jsonwebtoken\",\"optional\":true,\"req\":\"^10\"},{\"default_features\":false,\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.13.2\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^1.8.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"which\",\"optional\":true,\"req\":\"^8\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"auth-client-credentials-jwt\":[\"auth\",\"dep:jsonwebtoken\",\"uuid\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"local\":[\"rmcp-macros?/local\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-client-unix-socket\":[\"transport-streamable-http-client\",\"dep:hyper\",\"dep:hyper-util\",\"dep:http-body-util\",\"dep:http\",\"dep:bytes\",\"tokio/net\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"],\"which-command\":[\"transport-child-process\",\"dep:which\"]}}", "rtrb_0.3.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"crossbeam-utils\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "rust-embed-impl_8.11.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"rust-embed-utils\",\"req\":\"^8.11.0\"},{\"name\":\"shellexpand\",\"optional\":true,\"req\":\"^3\"},{\"default_features\":false,\"features\":[\"derive\",\"parsing\",\"proc-macro\",\"printing\"],\"name\":\"syn\",\"req\":\"^2\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"compression\":[],\"debug-embed\":[],\"deterministic-timestamps\":[],\"include-exclude\":[\"rust-embed-utils/include-exclude\"],\"interpolate-folder-path\":[\"shellexpand\"],\"mime-guess\":[\"rust-embed-utils/mime-guess\"]}}", "rust-embed-utils_8.11.0": "{\"dependencies\":[{\"name\":\"globset\",\"optional\":true,\"req\":\"^0.4.8\"},{\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0.4\"},{\"name\":\"sha2\",\"req\":\"^0.10.5\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"debug-embed\":[],\"include-exclude\":[\"globset\"],\"mime-guess\":[\"mime_guess\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 65d581db6f..d892aea620 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -9449,7 +9449,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http 1.4.0", @@ -10535,7 +10535,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "itertools 0.14.0", "log", "multimap", @@ -11455,9 +11455,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0810a9f717d9828f475fe1f629f4c305c8464b7f496c3a854b58d29e65f4058e" +checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59" dependencies = [ "async-trait", "base64 0.22.1", @@ -11490,9 +11490,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aefac48c364756e97f04c0401ba3231e8607882c7c1d92da0437dc16307904d" +checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5" dependencies = [ "darling 0.23.0", "proc-macro2", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 3290c4ea99..17c2d1561b 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -368,7 +368,7 @@ rcgen = { version = "0.14.7", default-features = false, features = [ regex = "1.12.3" regex-lite = "0.1.8" reqwest = { version = "0.12", features = ["cookies"] } -rmcp = { version = "1.7.0", default-features = false } +rmcp = { version = "1.8.0", default-features = false } runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" } rustls = { version = "0.23", default-features = false, features = [ "aws_lc_rs", diff --git a/codex-rs/codex-mcp/src/mcp/auth.rs b/codex-rs/codex-mcp/src/mcp/auth.rs index ec67f07a82..78d55fb789 100644 --- a/codex-rs/codex-mcp/src/mcp/auth.rs +++ b/codex-rs/codex-mcp/src/mcp/auth.rs @@ -10,6 +10,7 @@ use codex_protocol::protocol::McpAuthStatus; use codex_rmcp_client::OAuthProviderError; use codex_rmcp_client::determine_streamable_http_auth_status; use codex_rmcp_client::discover_streamable_http_oauth; +use futures::FutureExt; use futures::future::join_all; use tracing::warn; @@ -217,6 +218,7 @@ async fn compute_auth_status( store_mode, keyring_backend_kind, ) + .boxed() .await } } diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs index f5c7da5297..003f65cd93 100644 --- a/codex-rs/rmcp-client/src/rmcp_client.rs +++ b/codex-rs/rmcp-client/src/rmcp_client.rs @@ -455,7 +455,7 @@ impl RmcpClient { .peer() .peer_info() .ok_or_else(|| anyhow!("handshake succeeded but server info was missing"))?; - let initialize_result = initialize_result_rmcp.clone(); + let initialize_result = initialize_result_rmcp.as_ref().clone(); { let mut initialize_context = self.initialize_context.lock().await; From c553cea9eae2648d74342e21ce68233893e81d2c Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 23 Jun 2026 16:19:19 +0100 Subject: [PATCH 10/11] Update vulnerable Hono and fast-uri dependencies (#29650) ## Summary - Pin `hono` to 4.12.25, the first patched release for the recent Hono security advisories. - Pin `fast-uri` to 3.1.1 to fix the percent-encoded path traversal vulnerability. - Refresh `pnpm-lock.yaml` with only those dependency updates. `hono` 4.12.25 is used instead of the newer 4.12.27 because the repository requires dependencies to be at least seven days old. --- package.json | 2 ++ pnpm-lock.yaml | 26 ++++++++++++++------------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index c510d787de..ddda581bf2 100644 --- a/package.json +++ b/package.json @@ -14,9 +14,11 @@ "@modelcontextprotocol/sdk": "1.26.0", "braces": "^3.0.3", "esbuild": "0.28.1", + "fast-uri": "3.1.1", "flatted": "3.4.2", "glob@10.4.5": "10.5.0", "handlebars": "4.7.9", + "hono": "4.12.25", "micromatch": "^4.0.8", "minimatch@3.1.2": "3.1.4", "minimatch@9.0.5": "9.0.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a363b29edc..2d4c6f3497 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,9 +8,11 @@ overrides: '@modelcontextprotocol/sdk': 1.26.0 braces: ^3.0.3 esbuild: 0.28.1 + fast-uri: 3.1.1 flatted: 3.4.2 glob@10.4.5: 10.5.0 handlebars: 4.7.9 + hono: 4.12.25 micromatch: ^4.0.8 minimatch@3.1.2: 3.1.4 minimatch@9.0.5: 9.0.7 @@ -455,7 +457,7 @@ packages: resolution: {integrity: sha512-TsQLe4i2gvoTtrHje625ngThGBySOgSK3Xo2XRYOdqGN1teR8+I7vchQC46uLJi8OF62YTYA3AhSpumtkhsaKQ==} engines: {node: '>=18.14.1'} peerDependencies: - hono: ^4 + hono: 4.12.25 '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} @@ -1341,8 +1343,8 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - fast-uri@3.1.0: - resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + fast-uri@3.1.1: + resolution: {integrity: sha512-h2r7rcm6Ee/J8o0LD5djLuFVcfbZxhvho4vvsbeV0aMvXjUgqv4YpxpkEx0d68l6+IleVfLAdVEfhR7QNMkGHQ==} fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -1484,8 +1486,8 @@ packages: resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} engines: {node: '>= 0.4'} - hono@4.12.12: - resolution: {integrity: sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==} + hono@4.12.25: + resolution: {integrity: sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==} engines: {node: '>=16.9.0'} html-escaper@2.0.2: @@ -2873,9 +2875,9 @@ snapshots: '@eslint/core': 0.15.2 levn: 0.4.1 - '@hono/node-server@1.19.13(hono@4.12.12)': + '@hono/node-server@1.19.13(hono@4.12.25)': dependencies: - hono: 4.12.12 + hono: 4.12.25 '@humanfs/core@0.19.1': {} @@ -3095,7 +3097,7 @@ snapshots: '@modelcontextprotocol/sdk@1.26.0(zod@3.25.76)': dependencies: - '@hono/node-server': 1.19.13(hono@4.12.12) + '@hono/node-server': 1.19.13(hono@4.12.25) ajv: 8.17.1 ajv-formats: 3.0.1(ajv@8.17.1) content-type: 1.0.5 @@ -3105,7 +3107,7 @@ snapshots: eventsource-parser: 3.0.6 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) - hono: 4.12.12 + hono: 4.12.25 jose: 6.1.3 json-schema-typed: 8.0.2 pkce-challenge: 5.0.0 @@ -3401,7 +3403,7 @@ snapshots: ajv@8.17.1: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.0 + fast-uri: 3.1.1 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -3905,7 +3907,7 @@ snapshots: fast-levenshtein@2.0.6: {} - fast-uri@3.1.0: {} + fast-uri@3.1.1: {} fastq@1.19.1: dependencies: @@ -4054,7 +4056,7 @@ snapshots: dependencies: function-bind: 1.1.2 - hono@4.12.12: {} + hono@4.12.25: {} html-escaper@2.0.2: {} From 02c326f646f80065bdb574d2fad50a86f93a98d7 Mon Sep 17 00:00:00 2001 From: Tom Date: Tue, 23 Jun 2026 09:26:30 -0700 Subject: [PATCH 11/11] [codex] Instrument rollout persistence bytes (#29498) - Add 1%-sampled rollout persistence metrics that report per-item and per-thread JSON byte totals before and after filtering when metrics export is enabled. - Tag each item with its exact response or event variant, including nested turn-item kinds for conditionally persisted completion events, so aggregate cloud-storage impact can be estimated by policy choice. --- codex-rs/Cargo.lock | 1 + codex-rs/rollout/src/lib.rs | 4 + codex-rs/rollout/src/persistence_metrics.rs | 406 ++++++++++++++++++ .../rollout/src/persistence_metrics_tests.rs | 260 +++++++++++ codex-rs/thread-store/Cargo.toml | 1 + codex-rs/thread-store/src/live_thread.rs | 16 +- .../thread-store/src/local/live_writer.rs | 9 + 7 files changed, 696 insertions(+), 1 deletion(-) create mode 100644 codex-rs/rollout/src/persistence_metrics.rs create mode 100644 codex-rs/rollout/src/persistence_metrics_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d892aea620..d4eaf1dd2e 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3979,6 +3979,7 @@ dependencies = [ "chrono", "codex-git-utils", "codex-install-context", + "codex-otel", "codex-protocol", "codex-rollout", "codex-state", diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs index 23be07996c..804b8ac101 100644 --- a/codex-rs/rollout/src/lib.rs +++ b/codex-rs/rollout/src/lib.rs @@ -8,6 +8,7 @@ pub(crate) mod compression; pub(crate) mod config; pub(crate) mod list; pub(crate) mod metadata; +mod persistence_metrics; pub(crate) mod policy; pub(crate) mod recorder; pub(crate) mod search; @@ -60,6 +61,9 @@ pub use list::read_session_meta_line; pub use list::read_thread_item_from_rollout; pub use list::rollout_date_parts; pub use metadata::builder_from_items; +pub use persistence_metrics::RolloutPersistenceBatchMeasurement; +pub use persistence_metrics::RolloutPersistenceTelemetry; +pub use persistence_metrics::measure_and_filter_rollout_items; pub use policy::is_persisted_rollout_item; pub use policy::persisted_rollout_items; pub use policy::should_persist_response_item_for_memories; diff --git a/codex-rs/rollout/src/persistence_metrics.rs b/codex-rs/rollout/src/persistence_metrics.rs new file mode 100644 index 0000000000..6f07dbdfd1 --- /dev/null +++ b/codex-rs/rollout/src/persistence_metrics.rs @@ -0,0 +1,406 @@ +use std::io::Write; +use std::sync::Arc; +use std::sync::Mutex; + +use codex_otel::MetricsClient; +use codex_protocol::ThreadId; +use codex_protocol::items::TurnItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; + +use crate::policy::is_persisted_rollout_item; + +const ITEM_BYTES_METRIC: &str = "codex.rollout.persistence.item_bytes"; +const APPEND_METRIC: &str = "codex.rollout.persistence.append"; +const TURN_BYTES_METRIC: &str = "codex.rollout.persistence.turn_bytes"; +const MEASUREMENT_ERROR_METRIC: &str = "codex.rollout.persistence.measurement_error"; +const SAMPLE_DENOMINATOR: u64 = 100; +const SAMPLE_RATE_LABEL: &str = "0.01"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PersistenceDecision { + Kept, + Dropped, +} + +impl PersistenceDecision { + fn as_str(self) -> &'static str { + match self { + Self::Kept => "kept", + Self::Dropped => "dropped", + } + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct RolloutSizeTotals { + pub items: u64, + pub payload_bytes: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RolloutItemMeasurement { + pub decision: PersistenceDecision, + pub rollout_item_type: String, + pub payload_bytes: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RolloutPersistenceBatchMeasurement { + pub pre_filter: RolloutSizeTotals, + pub post_filter: RolloutSizeTotals, + pub items: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct TurnSizeTotals { + pre_filter: RolloutSizeTotals, + post_filter: RolloutSizeTotals, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TurnOutcome { + Completed, + Aborted, +} + +impl TurnOutcome { + fn as_str(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Aborted => "aborted", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct CompletedTurnMeasurement { + totals: TurnSizeTotals, + outcome: TurnOutcome, +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct TurnMeasurementState { + pending: TurnSizeTotals, + active: Option, +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct TurnMeasurementUpdate { + completed: Vec, + boundary_errors: Vec<&'static str>, +} + +/// Measures logical JSON sizes while applying the shared rollout persistence policy once. +pub fn measure_and_filter_rollout_items( + items: &[RolloutItem], +) -> (Vec, RolloutPersistenceBatchMeasurement) { + let mut persisted = Vec::new(); + let mut measurement = RolloutPersistenceBatchMeasurement { + items: Vec::with_capacity(items.len()), + ..Default::default() + }; + + for item in items { + let kept = is_persisted_rollout_item(item); + let decision = if kept { + PersistenceDecision::Kept + } else { + PersistenceDecision::Dropped + }; + let payload_bytes = serialized_len(item).ok(); + add_to_totals(&mut measurement.pre_filter, payload_bytes); + if kept { + add_to_totals(&mut measurement.post_filter, payload_bytes); + persisted.push(item.clone()); + } + measurement.items.push(RolloutItemMeasurement { + decision, + rollout_item_type: rollout_item_type(item), + payload_bytes, + }); + } + + (persisted, measurement) +} + +fn add_to_totals(totals: &mut RolloutSizeTotals, payload_bytes: Option) { + totals.items = totals.items.saturating_add(1); + if let Some(payload_bytes) = payload_bytes { + totals.payload_bytes = totals.payload_bytes.saturating_add(payload_bytes); + } +} + +fn update_turn_measurements( + state: &mut TurnMeasurementState, + items: &[RolloutItem], + measurement: &RolloutPersistenceBatchMeasurement, +) -> TurnMeasurementUpdate { + let mut update = TurnMeasurementUpdate::default(); + for (item, item_measurement) in items.iter().zip(&measurement.items) { + match item { + RolloutItem::EventMsg(EventMsg::TurnStarted(_)) => { + if state.active.take().is_some() { + update.boundary_errors.push("event.turn_started"); + } + let mut totals = std::mem::take(&mut state.pending); + add_item_to_turn(&mut totals, item_measurement); + state.active = Some(totals); + } + RolloutItem::EventMsg(EventMsg::TurnComplete(_)) => { + finish_turn( + state, + item_measurement, + TurnOutcome::Completed, + "event.turn_complete", + &mut update, + ); + } + RolloutItem::EventMsg(EventMsg::TurnAborted(_)) => { + finish_turn( + state, + item_measurement, + TurnOutcome::Aborted, + "event.turn_aborted", + &mut update, + ); + } + _ => match state.active.as_mut() { + Some(totals) => add_item_to_turn(totals, item_measurement), + None => add_item_to_turn(&mut state.pending, item_measurement), + }, + } + } + update +} + +fn finish_turn( + state: &mut TurnMeasurementState, + item: &RolloutItemMeasurement, + outcome: TurnOutcome, + boundary_type: &'static str, + update: &mut TurnMeasurementUpdate, +) { + let Some(mut totals) = state.active.take() else { + state.pending = TurnSizeTotals::default(); + update.boundary_errors.push(boundary_type); + return; + }; + add_item_to_turn(&mut totals, item); + update + .completed + .push(CompletedTurnMeasurement { totals, outcome }); +} + +fn add_item_to_turn(totals: &mut TurnSizeTotals, item: &RolloutItemMeasurement) { + add_to_totals(&mut totals.pre_filter, item.payload_bytes); + if item.decision == PersistenceDecision::Kept { + add_to_totals(&mut totals.post_filter, item.payload_bytes); + } +} + +fn serialized_len(item: &RolloutItem) -> serde_json::Result { + let mut writer = CountingWriter::default(); + serde_json::to_writer(&mut writer, item)?; + Ok(writer.bytes) +} + +#[derive(Default)] +struct CountingWriter { + bytes: u64, +} + +impl Write for CountingWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.bytes = self.bytes.saturating_add(buf.len() as u64); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn rollout_item_type(item: &RolloutItem) -> String { + match item { + RolloutItem::SessionMeta(_) => "session_meta".to_string(), + RolloutItem::ResponseItem(item) => response_item_type(item).to_string(), + RolloutItem::InterAgentCommunication(_) => "inter_agent_communication".to_string(), + RolloutItem::Compacted(_) => "compacted".to_string(), + RolloutItem::TurnContext(_) => "turn_context".to_string(), + RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => { + format!("event.item_completed.{}", turn_item_type(&event.item)) + } + RolloutItem::EventMsg(event) => format!("event.{event}"), + } +} + +fn turn_item_type(item: &TurnItem) -> &'static str { + match item { + TurnItem::UserMessage(_) => "user_message", + TurnItem::HookPrompt(_) => "hook_prompt", + TurnItem::AgentMessage(_) => "agent_message", + TurnItem::Plan(_) => "plan", + TurnItem::Reasoning(_) => "reasoning", + TurnItem::WebSearch(_) => "web_search", + TurnItem::ImageView(_) => "image_view", + TurnItem::Sleep(_) => "sleep", + TurnItem::ImageGeneration(_) => "image_generation", + TurnItem::FileChange(_) => "file_change", + TurnItem::McpToolCall(_) => "mcp_tool_call", + TurnItem::ContextCompaction(_) => "context_compaction", + } +} + +fn response_item_type(item: &ResponseItem) -> &'static str { + match item { + ResponseItem::Message { .. } => "response.message", + ResponseItem::AgentMessage { .. } => "response.agent_message", + ResponseItem::Reasoning { .. } => "response.reasoning", + ResponseItem::LocalShellCall { .. } => "response.local_shell_call", + ResponseItem::FunctionCall { .. } => "response.function_call", + ResponseItem::ToolSearchCall { .. } => "response.tool_search_call", + ResponseItem::FunctionCallOutput { .. } => "response.function_call_output", + ResponseItem::ToolSearchOutput { .. } => "response.tool_search_output", + ResponseItem::CustomToolCall { .. } => "response.custom_tool_call", + ResponseItem::CustomToolCallOutput { .. } => "response.custom_tool_call_output", + ResponseItem::WebSearchCall { .. } => "response.web_search_call", + ResponseItem::ImageGenerationCall { .. } => "response.image_generation_call", + ResponseItem::Compaction { .. } => "response.compaction", + ResponseItem::CompactionTrigger { .. } => "response.compaction_trigger", + ResponseItem::ContextCompaction { .. } => "response.context_compaction", + ResponseItem::Other => "response.other", + } +} + +#[derive(Clone)] +pub struct RolloutPersistenceTelemetry { + metrics: Option, + sampled: bool, + turn_state: Option>>, +} + +impl RolloutPersistenceTelemetry { + pub fn new(thread_id: ThreadId) -> Self { + let metrics = codex_otel::global(); + let sampled = metrics.is_some() && is_thread_sampled(thread_id); + Self { + metrics, + sampled, + turn_state: sampled.then(|| Arc::new(Mutex::new(TurnMeasurementState::default()))), + } + } + + pub fn is_enabled(&self) -> bool { + self.enabled_metrics().is_some() + } + + pub fn record_batch( + &self, + items: &[RolloutItem], + measurement: &RolloutPersistenceBatchMeasurement, + ) { + let Some(metrics) = self.enabled_metrics() else { + return; + }; + + for item in &measurement.items { + if let Some(payload_bytes) = item.payload_bytes { + let _ = metrics.histogram( + ITEM_BYTES_METRIC, + saturating_i64(payload_bytes), + &[ + ("decision", item.decision.as_str()), + ("rollout_item_type", item.rollout_item_type.as_str()), + ("encoding", "rollout_item_json_v1"), + ("sample_rate", SAMPLE_RATE_LABEL), + ], + ); + } else { + let _ = metrics.counter( + MEASUREMENT_ERROR_METRIC, + /*inc*/ 1, + &[ + ("rollout_item_type", item.rollout_item_type.as_str()), + ("phase", "serialize"), + ], + ); + } + } + // Count successful input appends and the subset that remain storage operations after the + // persistence policy removes filtered items. + let _ = metrics.counter( + APPEND_METRIC, + /*inc*/ 1, + &[("stage", "pre_filter"), ("sample_rate", SAMPLE_RATE_LABEL)], + ); + if measurement.post_filter.items > 0 { + let _ = metrics.counter( + APPEND_METRIC, + /*inc*/ 1, + &[("stage", "post_filter"), ("sample_rate", SAMPLE_RATE_LABEL)], + ); + } + + let Some(turn_state) = self.turn_state.as_ref() else { + return; + }; + let turn_update = update_turn_measurements( + &mut turn_state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + items, + measurement, + ); + for boundary_type in turn_update.boundary_errors { + let _ = metrics.counter( + MEASUREMENT_ERROR_METRIC, + /*inc*/ 1, + &[ + ("rollout_item_type", boundary_type), + ("phase", "turn_boundary"), + ], + ); + } + for turn in turn_update.completed { + for (stage, totals) in [ + ("pre_filter", turn.totals.pre_filter), + ("post_filter", turn.totals.post_filter), + ] { + let _ = metrics.histogram( + TURN_BYTES_METRIC, + saturating_i64(totals.payload_bytes), + &[ + ("stage", stage), + ("outcome", turn.outcome.as_str()), + ("encoding", "rollout_item_json_v1"), + ("sample_rate", SAMPLE_RATE_LABEL), + ], + ); + } + } + } + + fn enabled_metrics(&self) -> Option<&MetricsClient> { + self.sampled.then_some(self.metrics.as_ref()).flatten() + } +} + +fn saturating_i64(value: u64) -> i64 { + value.try_into().unwrap_or(i64::MAX) +} + +fn is_thread_sampled(thread_id: ThreadId) -> bool { + let hash = thread_id + .to_string() + .bytes() + .fold(0xcbf29ce484222325_u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3) + }); + hash % SAMPLE_DENOMINATOR == 0 +} + +#[cfg(test)] +#[path = "persistence_metrics_tests.rs"] +mod tests; diff --git a/codex-rs/rollout/src/persistence_metrics_tests.rs b/codex-rs/rollout/src/persistence_metrics_tests.rs new file mode 100644 index 0000000000..963805f43d --- /dev/null +++ b/codex-rs/rollout/src/persistence_metrics_tests.rs @@ -0,0 +1,260 @@ +use codex_protocol::ThreadId; +use codex_protocol::items::TurnItem; +use codex_protocol::items::UserMessageItem; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnAbortedEvent; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnStartedEvent; +use pretty_assertions::assert_eq; + +use super::CompletedTurnMeasurement; +use super::TurnMeasurementState; +use super::TurnOutcome; +use super::TurnSizeTotals; +use super::is_thread_sampled; +use super::measure_and_filter_rollout_items; +use super::update_turn_measurements; + +fn retained_message(text: &str) -> RolloutItem { + RolloutItem::ResponseItem(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: text.to_string(), + }], + phase: None, + internal_chat_message_metadata_passthrough: None, + }) +} + +fn turn_started(turn_id: &str) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + })) +} + +fn turn_complete(turn_id: &str) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: turn_id.to_string(), + last_agent_message: None, + completed_at: None, + duration_ms: None, + time_to_first_token_ms: None, + })) +} + +fn turn_aborted(turn_id: &str) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::TurnAborted(TurnAbortedEvent { + turn_id: Some(turn_id.to_string()), + reason: TurnAbortReason::Interrupted, + completed_at: None, + duration_ms: None, + })) +} + +fn update_for_batch( + state: &mut TurnMeasurementState, + items: &[RolloutItem], +) -> super::TurnMeasurementUpdate { + let (_, measurement) = measure_and_filter_rollout_items(items); + update_turn_measurements(state, items, &measurement) +} + +#[test] +fn thread_sampling_is_stable_and_selects_whole_threads() { + let mut sampled = None; + let mut unsampled = None; + for value in 0..10_000_u128 { + let thread_id = ThreadId::from_string(&format!("00000000-0000-0000-0000-{value:012x}")) + .expect("valid thread id"); + if is_thread_sampled(thread_id) { + sampled.get_or_insert(thread_id); + } else { + unsampled.get_or_insert(thread_id); + } + if sampled.is_some() && unsampled.is_some() { + break; + } + } + + let sampled = sampled.expect("at least one sampled thread"); + let unsampled = unsampled.expect("at least one unsampled thread"); + assert!(is_thread_sampled(sampled)); + assert!(is_thread_sampled(sampled)); + assert!(!is_thread_sampled(unsampled)); + assert!(!is_thread_sampled(unsampled)); +} + +#[test] +fn mixed_batch_reports_exact_policy_counts_and_bytes() { + let kept = retained_message("hello"); + let dropped = RolloutItem::ResponseItem(ResponseItem::Other); + let items = vec![kept.clone(), dropped.clone()]; + + let (persisted, measurement) = measure_and_filter_rollout_items(&items); + let kept_bytes = serde_json::to_vec(&kept) + .expect("serialize kept item") + .len() as u64; + let dropped_bytes = serde_json::to_vec(&dropped) + .expect("serialize dropped item") + .len() as u64; + + assert_eq!( + serde_json::to_value(persisted).expect("serialize persisted items"), + serde_json::to_value([kept]).expect("serialize expected items") + ); + assert_eq!(measurement.pre_filter.items, 2); + assert_eq!( + measurement.pre_filter.payload_bytes, + kept_bytes + dropped_bytes + ); + assert_eq!(measurement.post_filter.items, 1); + assert_eq!(measurement.post_filter.payload_bytes, kept_bytes); + assert_eq!(measurement.items[0].payload_bytes, Some(kept_bytes)); + assert_eq!(measurement.items[1].payload_bytes, Some(dropped_bytes)); + assert_eq!(measurement.items[0].rollout_item_type, "response.message"); + assert_eq!(measurement.items[1].rollout_item_type, "response.other"); +} + +#[test] +fn retained_items_are_byte_identical() { + let item = retained_message("a moderately sized payload"); + let (persisted, measurement) = measure_and_filter_rollout_items(std::slice::from_ref(&item)); + + assert_eq!( + serde_json::to_vec(&persisted[0]).expect("serialize persisted item"), + serde_json::to_vec(&item).expect("serialize candidate item") + ); + assert_eq!( + measurement.post_filter.payload_bytes, + measurement.items[0].payload_bytes.expect("payload bytes") + ); +} + +#[test] +fn turn_measurements_span_batches_and_include_items_before_start() { + let first_turn = vec![ + retained_message("first prompt"), + turn_started("turn-1"), + retained_message("first response"), + RolloutItem::ResponseItem(ResponseItem::Other), + turn_complete("turn-1"), + ]; + let second_turn = vec![ + retained_message("second prompt"), + turn_started("turn-2"), + retained_message("second response"), + turn_aborted("turn-2"), + ]; + let (_, first_expected) = measure_and_filter_rollout_items(&first_turn); + let (_, second_expected) = measure_and_filter_rollout_items(&second_turn); + let batches = [ + first_turn[..1].to_vec(), + first_turn[1..3].to_vec(), + vec![ + first_turn[3].clone(), + first_turn[4].clone(), + second_turn[0].clone(), + ], + second_turn[1..].to_vec(), + ]; + + let mut state = TurnMeasurementState::default(); + let mut completed = Vec::new(); + let mut boundary_errors = Vec::new(); + for batch in batches { + let update = update_for_batch(&mut state, &batch); + completed.extend(update.completed); + boundary_errors.extend(update.boundary_errors); + } + + assert_eq!( + completed, + vec![ + CompletedTurnMeasurement { + totals: TurnSizeTotals { + pre_filter: first_expected.pre_filter, + post_filter: first_expected.post_filter, + }, + outcome: TurnOutcome::Completed, + }, + CompletedTurnMeasurement { + totals: TurnSizeTotals { + pre_filter: second_expected.pre_filter, + post_filter: second_expected.post_filter, + }, + outcome: TurnOutcome::Aborted, + }, + ] + ); + assert_eq!(boundary_errors, Vec::<&str>::new()); + assert_eq!(state, TurnMeasurementState::default()); +} + +#[test] +fn invalid_turn_boundaries_reset_partial_measurements() { + let mut state = TurnMeasurementState::default(); + let unmatched_completion = vec![retained_message("orphan"), turn_complete("turn-1")]; + let update = update_for_batch(&mut state, &unmatched_completion); + + assert_eq!(update.completed, Vec::new()); + assert_eq!(update.boundary_errors, vec!["event.turn_complete"]); + assert_eq!(state, TurnMeasurementState::default()); + + let replacement = vec![ + turn_started("turn-1"), + retained_message("discarded partial turn"), + turn_started("turn-2"), + retained_message("retained turn"), + turn_complete("turn-2"), + ]; + let (_, expected) = measure_and_filter_rollout_items(&replacement[2..]); + let update = update_for_batch(&mut state, &replacement); + + assert_eq!( + update.completed, + vec![CompletedTurnMeasurement { + totals: TurnSizeTotals { + pre_filter: expected.pre_filter, + post_filter: expected.post_filter, + }, + outcome: TurnOutcome::Completed, + }] + ); + assert_eq!(update.boundary_errors, vec!["event.turn_started"]); + assert_eq!(state, TurnMeasurementState::default()); +} + +#[test] +fn filtered_item_completion_includes_its_nested_item_type() { + let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: ThreadId::default(), + turn_id: "turn".to_string(), + item: TurnItem::UserMessage(UserMessageItem { + id: "item".to_string(), + client_id: None, + content: Vec::new(), + }), + completed_at_ms: 0, + })); + + let (_, measurement) = measure_and_filter_rollout_items(&[item]); + + assert_eq!( + measurement.items[0].rollout_item_type, + "event.item_completed.user_message" + ); + assert_eq!( + measurement.items[0].decision, + super::PersistenceDecision::Dropped + ); +} diff --git a/codex-rs/thread-store/Cargo.toml b/codex-rs/thread-store/Cargo.toml index 7c59cf72f3..35b3919c60 100644 --- a/codex-rs/thread-store/Cargo.toml +++ b/codex-rs/thread-store/Cargo.toml @@ -16,6 +16,7 @@ workspace = true chrono = { workspace = true, features = ["serde"] } codex-git-utils = { workspace = true } codex-install-context = { workspace = true } +codex-otel = { workspace = true } codex-protocol = { workspace = true } codex-rollout = { workspace = true } codex-state = { workspace = true } diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index da3d092da5..793bbf9965 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -4,6 +4,8 @@ use std::sync::Arc; use codex_protocol::ThreadId; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::ThreadMemoryMode; +use codex_rollout::RolloutPersistenceTelemetry; +use codex_rollout::measure_and_filter_rollout_items; use codex_rollout::persisted_rollout_items; use tokio::sync::Mutex; use tracing::warn; @@ -32,6 +34,7 @@ pub struct LiveThread { thread_id: ThreadId, thread_store: Arc, metadata_sync: Arc>, + persistence_telemetry: RolloutPersistenceTelemetry, } /// Owns a live thread while session initialization is still fallible. @@ -95,6 +98,7 @@ impl LiveThread { thread_id, thread_store, metadata_sync: Arc::new(Mutex::new(metadata_sync)), + persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id), }) } @@ -130,6 +134,7 @@ impl LiveThread { thread_id, thread_store, metadata_sync: Arc::new(Mutex::new(metadata_sync)), + persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id), }) } @@ -139,16 +144,25 @@ impl LiveThread { fields(item_count = items.len()) )] pub async fn append_items(&self, items: &[RolloutItem]) -> ThreadStoreResult<()> { - let canonical_items = persisted_rollout_items(items); + // Empty appends are intentionally ignored rather than represented as zero-sized batches. if items.is_empty() { return Ok(()); } + let (canonical_items, measurement) = if self.persistence_telemetry.is_enabled() { + let (canonical_items, measurement) = measure_and_filter_rollout_items(items); + (canonical_items, Some(measurement)) + } else { + (persisted_rollout_items(items), None) + }; self.thread_store .append_items(AppendThreadItemsParams { thread_id: self.thread_id, items: items.to_vec(), }) .await?; + if let Some(measurement) = measurement.as_ref() { + self.persistence_telemetry.record_batch(items, measurement); + } if canonical_items.is_empty() { return Ok(()); } diff --git a/codex-rs/thread-store/src/local/live_writer.rs b/codex-rs/thread-store/src/local/live_writer.rs index 24c31869f1..3e7541b36b 100644 --- a/codex-rs/thread-store/src/local/live_writer.rs +++ b/codex-rs/thread-store/src/local/live_writer.rs @@ -17,6 +17,8 @@ use crate::ResumeThreadParams; use crate::ThreadStoreError; use crate::ThreadStoreResult; +const ROLLOUT_SIZE_BYTES_METRIC: &str = "codex.rollout.size_bytes"; + pub(super) async fn create_thread( store: &LocalThreadStore, params: CreateThreadParams, @@ -128,8 +130,15 @@ pub(super) async fn shutdown_thread( thread_id: ThreadId, ) -> ThreadStoreResult<()> { let recorder = store.live_recorder(thread_id).await?; + let rollout_path = recorder.rollout_path().to_path_buf(); recorder.shutdown().await.map_err(thread_store_io_error)?; sync_materialized_rollout_path(store, thread_id).await?; + if let Some(metrics) = codex_otel::global() + && let Ok(metadata) = tokio::fs::metadata(rollout_path).await + { + let size_bytes = i64::try_from(metadata.len()).unwrap_or(i64::MAX); + let _ = metrics.histogram(ROLLOUT_SIZE_BYTES_METRIC, size_bytes, &[]); + } store.live_recorders.lock().await.remove(&thread_id); Ok(()) }